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};
17 use regex::{Captures, Regex};
18 use rustfix::{apply_suggestions, get_suggestions_from_json, Filter};
20 use std::collections::hash_map::DefaultHasher;
21 use std::collections::{HashMap, HashSet, VecDeque};
23 use std::ffi::{OsStr, OsString};
25 use std::fs::{self, create_dir_all, File, OpenOptions};
26 use std::hash::{Hash, Hasher};
27 use std::io::prelude::*;
28 use std::io::{self, BufReader};
29 use std::path::{Path, PathBuf};
30 use std::process::{Child, Command, ExitStatus, Output, Stdio};
33 use lazy_static::lazy_static;
36 use crate::extract_gdb_version;
37 use crate::is_android_gdb_target;
43 fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
45 use winapi::um::errhandlingapi::SetErrorMode;
46 use winapi::um::winbase::SEM_NOGPFAULTERRORBOX;
49 static ref LOCK: Mutex<()> = { Mutex::new(()) };
51 // Error mode is a global variable, so lock it so only one thread will change it
52 let _lock = LOCK.lock().unwrap();
54 // Tell Windows to not show any UI on errors (such as terminating abnormally).
55 // This is important for running tests, since some of them use abnormal
56 // termination by design. This mode is inherited by all child processes.
58 let old_mode = SetErrorMode(SEM_NOGPFAULTERRORBOX); // read inherited flags
59 SetErrorMode(old_mode | SEM_NOGPFAULTERRORBOX);
61 SetErrorMode(old_mode);
67 fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
71 /// The name of the environment variable that holds dynamic library locations.
72 pub fn dylib_env_var() -> &'static str {
75 } else if cfg!(target_os = "macos") {
77 } else if cfg!(target_os = "haiku") {
84 /// The platform-specific library name
85 pub fn get_lib_name(lib: &str, dylib: bool) -> String {
86 // In some casess (e.g. MUSL), we build a static
87 // library, rather than a dynamic library.
88 // In this case, the only path we can pass
89 // with '--extern-meta' is the '.lib' file
91 return format!("lib{}.rlib", lib);
95 format!("{}.dll", lib)
96 } else if cfg!(target_os = "macos") {
97 format!("lib{}.dylib", lib)
99 format!("lib{}.so", lib)
103 #[derive(Debug, PartialEq)]
110 #[derive(Debug, PartialEq)]
111 pub struct Mismatch {
112 pub line_number: u32,
113 pub lines: Vec<DiffLine>,
117 fn new(line_number: u32) -> Mismatch {
118 Mismatch { line_number: line_number, lines: Vec::new() }
122 // Produces a diff between the expected output and actual output.
123 pub fn make_diff(expected: &str, actual: &str, context_size: usize) -> Vec<Mismatch> {
124 let mut line_number = 1;
125 let mut context_queue: VecDeque<&str> = VecDeque::with_capacity(context_size);
126 let mut lines_since_mismatch = context_size + 1;
127 let mut results = Vec::new();
128 let mut mismatch = Mismatch::new(0);
130 for result in diff::lines(expected, actual) {
132 diff::Result::Left(str) => {
133 if lines_since_mismatch >= context_size && lines_since_mismatch > 0 {
134 results.push(mismatch);
135 mismatch = Mismatch::new(line_number - context_queue.len() as u32);
138 while let Some(line) = context_queue.pop_front() {
139 mismatch.lines.push(DiffLine::Context(line.to_owned()));
142 mismatch.lines.push(DiffLine::Expected(str.to_owned()));
144 lines_since_mismatch = 0;
146 diff::Result::Right(str) => {
147 if lines_since_mismatch >= context_size && lines_since_mismatch > 0 {
148 results.push(mismatch);
149 mismatch = Mismatch::new(line_number - context_queue.len() as u32);
152 while let Some(line) = context_queue.pop_front() {
153 mismatch.lines.push(DiffLine::Context(line.to_owned()));
156 mismatch.lines.push(DiffLine::Resulting(str.to_owned()));
157 lines_since_mismatch = 0;
159 diff::Result::Both(str, _) => {
160 if context_queue.len() >= context_size {
161 let _ = context_queue.pop_front();
164 if lines_since_mismatch < context_size {
165 mismatch.lines.push(DiffLine::Context(str.to_owned()));
166 } else if context_size > 0 {
167 context_queue.push_back(str);
171 lines_since_mismatch += 1;
176 results.push(mismatch);
182 fn print_diff(expected: &str, actual: &str, context_size: usize) {
183 write_diff(expected, actual, context_size, std::io::stdout());
186 fn write_diff(expected: &str, actual: &str, context_size: usize, mut dest: impl io::Write) {
187 let diff_results = make_diff(expected, actual, context_size);
188 for result in diff_results {
189 let mut line_number = result.line_number;
190 for line in result.lines {
192 DiffLine::Expected(e) => {
193 writeln!(dest, "-\t{}", e).unwrap();
196 DiffLine::Context(c) => {
197 writeln!(dest, "{}\t{}", line_number, c).unwrap();
200 DiffLine::Resulting(r) => {
201 writeln!(dest, "+\t{}", r).unwrap();
205 writeln!(dest).unwrap();
209 pub fn run(config: Config, testpaths: &TestPaths, revision: Option<&str>) {
210 match &*config.target {
211 "arm-linux-androideabi"
212 | "armv7-linux-androideabi"
213 | "thumbv7neon-linux-androideabi"
214 | "aarch64-linux-android" => {
215 if !config.adb_device_status {
216 panic!("android device not available");
221 // android has its own gdb handling
222 if config.debugger == Some(Debugger::Gdb) && config.gdb.is_none() {
223 panic!("gdb not available but debuginfo gdb debuginfo test requested");
229 // We're going to be dumping a lot of info. Start on a new line.
232 debug!("running {:?}", testpaths.file.display());
233 let props = TestProps::from_file(&testpaths.file, revision, &config);
235 let cx = TestCx { config: &config, props: &props, testpaths, revision: revision };
236 create_dir_all(&cx.output_base_dir()).unwrap();
238 if config.mode == Incremental {
239 // Incremental tests are special because they cannot be run in
241 assert!(!props.revisions.is_empty(), "Incremental tests require revisions.");
242 cx.init_incremental_test();
243 for revision in &props.revisions {
244 let revision_props = TestProps::from_file(&testpaths.file, Some(revision), &config);
245 let rev_cx = TestCx {
247 props: &revision_props,
249 revision: Some(revision),
251 rev_cx.run_revision();
260 pub fn compute_stamp_hash(config: &Config) -> String {
261 let mut hash = DefaultHasher::new();
262 config.stage_id.hash(&mut hash);
264 match config.debugger {
265 Some(Debugger::Cdb) => {
266 config.cdb.hash(&mut hash);
269 Some(Debugger::Gdb) => {
270 config.gdb.hash(&mut hash);
271 env::var_os("PATH").hash(&mut hash);
272 env::var_os("PYTHONPATH").hash(&mut hash);
275 Some(Debugger::Lldb) => {
276 config.lldb_python.hash(&mut hash);
277 config.lldb_python_dir.hash(&mut hash);
278 env::var_os("PATH").hash(&mut hash);
279 env::var_os("PYTHONPATH").hash(&mut hash);
285 if let Ui = config.mode {
286 config.force_pass_mode.hash(&mut hash);
289 format!("{:x}", hash.finish())
292 struct TestCx<'test> {
293 config: &'test Config,
294 props: &'test TestProps,
295 testpaths: &'test TestPaths,
296 revision: Option<&'test str>,
299 struct DebuggerCommands {
300 commands: Vec<String>,
301 check_lines: Vec<String>,
302 breakpoint_lines: Vec<usize>,
315 /// Will this test be executed? Should we use `make_exe_name`?
316 #[derive(Copy, Clone, PartialEq)]
322 /// Should `--emit metadata` be used?
323 #[derive(Copy, Clone)]
329 impl<'test> TestCx<'test> {
330 /// Code executed for each revision in turn (or, if there are no
331 /// revisions, exactly once, with revision == None).
332 fn run_revision(&self) {
333 if self.props.should_ice {
334 if self.config.mode != CompileFail && self.config.mode != Incremental {
335 self.fatal("cannot use should-ice in a test that is not cfail");
338 match self.config.mode {
339 CompileFail => self.run_cfail_test(),
340 RunFail => self.run_rfail_test(),
341 RunPassValgrind => self.run_valgrind_test(),
342 Pretty => self.run_pretty_test(),
343 DebugInfo => self.run_debuginfo_test(),
344 Codegen => self.run_codegen_test(),
345 Rustdoc => self.run_rustdoc_test(),
346 CodegenUnits => self.run_codegen_units_test(),
347 Incremental => self.run_incremental_test(),
348 RunMake => self.run_rmake_test(),
349 Ui => self.run_ui_test(),
350 MirOpt => self.run_mir_opt_test(),
351 Assembly => self.run_assembly_test(),
352 JsDocTest => self.run_js_doc_test(),
356 fn pass_mode(&self) -> Option<PassMode> {
357 self.props.pass_mode(self.config)
360 fn should_run(&self, pm: Option<PassMode>) -> WillExecute {
361 match self.config.mode {
362 Ui if pm == Some(PassMode::Run) || self.props.fail_mode == Some(FailMode::Run) => {
365 Ui => WillExecute::No,
366 mode => panic!("unimplemented for mode {:?}", mode),
370 fn should_run_successfully(&self, pm: Option<PassMode>) -> bool {
371 match self.config.mode {
372 Ui => pm == Some(PassMode::Run),
373 mode => panic!("unimplemented for mode {:?}", mode),
377 fn should_compile_successfully(&self, pm: Option<PassMode>) -> bool {
378 match self.config.mode {
379 CompileFail => false,
381 Ui => pm.is_some() || self.props.fail_mode > Some(FailMode::Build),
384 self.revision.expect("incremental tests require a list of revisions");
385 if revision.starts_with("rpass") || revision.starts_with("rfail") {
387 } else if revision.starts_with("cfail") {
388 // FIXME: would be nice if incremental revs could start with "cpass"
391 panic!("revision name must begin with rpass, rfail, or cfail");
394 mode => panic!("unimplemented for mode {:?}", mode),
398 fn check_if_test_should_compile(&self, proc_res: &ProcRes, pm: Option<PassMode>) {
399 if self.should_compile_successfully(pm) {
400 if !proc_res.status.success() {
401 self.fatal_proc_rec("test compilation failed although it shouldn't!", proc_res);
404 if proc_res.status.success() {
406 &format!("{} test compiled successfully!", self.config.mode)[..],
411 self.check_correct_failure_status(proc_res);
415 fn run_cfail_test(&self) {
416 let pm = self.pass_mode();
417 let proc_res = self.compile_test(WillExecute::No, self.should_emit_metadata(pm));
418 self.check_if_test_should_compile(&proc_res, pm);
419 self.check_no_compiler_crash(&proc_res, self.props.should_ice);
421 let output_to_check = self.get_output(&proc_res);
422 let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
423 if !expected_errors.is_empty() {
424 if !self.props.error_patterns.is_empty() {
425 self.fatal("both error pattern and expected errors specified");
427 self.check_expected_errors(expected_errors, &proc_res);
429 self.check_error_patterns(&output_to_check, &proc_res, pm);
431 if self.props.should_ice {
432 match proc_res.status.code() {
434 _ => self.fatal("expected ICE"),
438 self.check_forbid_output(&output_to_check, &proc_res);
441 fn run_rfail_test(&self) {
442 let pm = self.pass_mode();
443 let proc_res = self.compile_test(WillExecute::Yes, self.should_emit_metadata(pm));
445 if !proc_res.status.success() {
446 self.fatal_proc_rec("compilation failed!", &proc_res);
449 let proc_res = self.exec_compiled_test();
451 // The value our Makefile configures valgrind to return on failure
452 const VALGRIND_ERR: i32 = 100;
453 if proc_res.status.code() == Some(VALGRIND_ERR) {
454 self.fatal_proc_rec("run-fail test isn't valgrind-clean!", &proc_res);
457 let output_to_check = self.get_output(&proc_res);
458 self.check_correct_failure_status(&proc_res);
459 self.check_error_patterns(&output_to_check, &proc_res, pm);
462 fn get_output(&self, proc_res: &ProcRes) -> String {
463 if self.props.check_stdout {
464 format!("{}{}", proc_res.stdout, proc_res.stderr)
466 proc_res.stderr.clone()
470 fn check_correct_failure_status(&self, proc_res: &ProcRes) {
471 let expected_status = Some(self.props.failure_status);
472 let received_status = proc_res.status.code();
474 if expected_status != received_status {
477 "Error: expected failure status ({:?}) but received status {:?}.",
478 expected_status, received_status
485 fn run_rpass_test(&self) {
486 let emit_metadata = self.should_emit_metadata(self.pass_mode());
487 let proc_res = self.compile_test(WillExecute::Yes, emit_metadata);
489 if !proc_res.status.success() {
490 self.fatal_proc_rec("compilation failed!", &proc_res);
493 // FIXME(#41968): Move this check to tidy?
494 let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
496 expected_errors.is_empty(),
497 "run-pass tests with expected warnings should be moved to ui/"
500 let proc_res = self.exec_compiled_test();
501 if !proc_res.status.success() {
502 self.fatal_proc_rec("test run failed!", &proc_res);
506 fn run_valgrind_test(&self) {
507 assert!(self.revision.is_none(), "revisions not relevant here");
509 if self.config.valgrind_path.is_none() {
510 assert!(!self.config.force_valgrind);
511 return self.run_rpass_test();
514 let mut proc_res = self.compile_test(WillExecute::Yes, EmitMetadata::No);
516 if !proc_res.status.success() {
517 self.fatal_proc_rec("compilation failed!", &proc_res);
520 let mut new_config = self.config.clone();
521 new_config.runtool = new_config.valgrind_path.clone();
522 let new_cx = TestCx { config: &new_config, ..*self };
523 proc_res = new_cx.exec_compiled_test();
525 if !proc_res.status.success() {
526 self.fatal_proc_rec("test run failed!", &proc_res);
530 fn run_pretty_test(&self) {
531 if self.props.pp_exact.is_some() {
532 logv(self.config, "testing for exact pretty-printing".to_owned());
534 logv(self.config, "testing for converging pretty-printing".to_owned());
537 let rounds = match self.props.pp_exact {
542 let src = fs::read_to_string(&self.testpaths.file).unwrap();
543 let mut srcs = vec![src];
546 while round < rounds {
549 format!("pretty-printing round {} revision {:?}", round, self.revision),
552 if round == 0 { ReadFrom::Path } else { ReadFrom::Stdin(srcs[round].to_owned()) };
554 let proc_res = self.print_source(read_from, &self.props.pretty_mode);
555 if !proc_res.status.success() {
558 "pretty-printing failed in round {} revision {:?}",
565 let ProcRes { stdout, .. } = proc_res;
570 let mut expected = match self.props.pp_exact {
572 let filepath = self.testpaths.file.parent().unwrap().join(file);
573 fs::read_to_string(&filepath).unwrap()
575 None => srcs[srcs.len() - 2].clone(),
577 let mut actual = srcs[srcs.len() - 1].clone();
579 if self.props.pp_exact.is_some() {
580 // Now we have to care about line endings
581 let cr = "\r".to_owned();
582 actual = actual.replace(&cr, "").to_owned();
583 expected = expected.replace(&cr, "").to_owned();
586 self.compare_source(&expected, &actual);
588 // If we're only making sure that the output matches then just stop here
589 if self.props.pretty_compare_only {
593 // Finally, let's make sure it actually appears to remain valid code
594 let proc_res = self.typecheck_source(actual);
595 if !proc_res.status.success() {
596 self.fatal_proc_rec("pretty-printed source does not typecheck", &proc_res);
599 if !self.props.pretty_expanded {
603 // additionally, run `--pretty expanded` and try to build it.
604 let proc_res = self.print_source(ReadFrom::Path, "expanded");
605 if !proc_res.status.success() {
606 self.fatal_proc_rec("pretty-printing (expanded) failed", &proc_res);
609 let ProcRes { stdout: expanded_src, .. } = proc_res;
610 let proc_res = self.typecheck_source(expanded_src);
611 if !proc_res.status.success() {
612 self.fatal_proc_rec("pretty-printed source (expanded) does not typecheck", &proc_res);
616 fn print_source(&self, read_from: ReadFrom, pretty_type: &str) -> ProcRes {
617 let aux_dir = self.aux_output_dir_name();
618 let input: &str = match read_from {
619 ReadFrom::Stdin(_) => "-",
620 ReadFrom::Path => self.testpaths.file.to_str().unwrap(),
623 let mut rustc = Command::new(&self.config.rustc_path);
626 .args(&["-Z", &format!("unpretty={}", pretty_type)])
627 .args(&["--target", &self.config.target])
630 .args(&self.props.compile_flags)
631 .envs(self.props.exec_env.clone());
632 self.maybe_add_external_args(
634 self.split_maybe_args(&self.config.target_rustcflags),
637 let src = match read_from {
638 ReadFrom::Stdin(src) => Some(src),
639 ReadFrom::Path => None,
642 self.compose_and_run(
644 self.config.compile_lib_path.to_str().unwrap(),
645 Some(aux_dir.to_str().unwrap()),
650 fn compare_source(&self, expected: &str, actual: &str) {
651 if expected != actual {
653 "pretty-printed source does not match expected source\n\
655 ------------------------------------------\n\
657 ------------------------------------------\n\
659 ------------------------------------------\n\
661 ------------------------------------------\n\
668 fn set_revision_flags(&self, cmd: &mut Command) {
669 if let Some(revision) = self.revision {
670 // Normalize revisions to be lowercase and replace `-`s with `_`s.
671 // Otherwise the `--cfg` flag is not valid.
672 let normalized_revision = revision.to_lowercase().replace("-", "_");
673 cmd.args(&["--cfg", &normalized_revision]);
677 fn typecheck_source(&self, src: String) -> ProcRes {
678 let mut rustc = Command::new(&self.config.rustc_path);
680 let out_dir = self.output_base_name().with_extension("pretty-out");
681 let _ = fs::remove_dir_all(&out_dir);
682 create_dir_all(&out_dir).unwrap();
684 let target = if self.props.force_host { &*self.config.host } else { &*self.config.target };
686 let aux_dir = self.aux_output_dir_name();
693 .arg(&format!("--target={}", target))
695 .arg(&self.config.build_base)
698 self.set_revision_flags(&mut rustc);
699 self.maybe_add_external_args(
701 self.split_maybe_args(&self.config.target_rustcflags),
703 rustc.args(&self.props.compile_flags);
705 self.compose_and_run_compiler(rustc, Some(src))
708 fn run_debuginfo_test(&self) {
709 match self.config.debugger.unwrap() {
710 Debugger::Cdb => self.run_debuginfo_cdb_test(),
711 Debugger::Gdb => self.run_debuginfo_gdb_test(),
712 Debugger::Lldb => self.run_debuginfo_lldb_test(),
716 fn run_debuginfo_cdb_test(&self) {
717 assert!(self.revision.is_none(), "revisions not relevant here");
719 let config = Config {
720 target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
721 host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
722 ..self.config.clone()
725 let test_cx = TestCx { config: &config, ..*self };
727 test_cx.run_debuginfo_cdb_test_no_opt();
730 fn run_debuginfo_cdb_test_no_opt(&self) {
731 // compile test file (it should have 'compile-flags:-g' in the header)
732 let compile_result = self.compile_test(WillExecute::Yes, EmitMetadata::No);
733 if !compile_result.status.success() {
734 self.fatal_proc_rec("compilation failed!", &compile_result);
737 let exe_file = self.make_exe_name();
740 static PREFIXES: &'static [&'static str] = &["cdb", "cdbg"];
741 // No "native rust support" variation for CDB yet.
745 // Parse debugger commands etc from test files
746 let DebuggerCommands { commands, check_lines, breakpoint_lines, .. } =
747 self.parse_debugger_commands(prefixes);
749 // https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-commands
750 let mut script_str = String::with_capacity(2048);
751 script_str.push_str("version\n"); // List CDB (and more) version info in test output
752 script_str.push_str(".nvlist\n"); // List loaded `*.natvis` files, bulk of custom MSVC debug
754 // Set breakpoints on every line that contains the string "#break"
755 let source_file_name = self.testpaths.file.file_name().unwrap().to_string_lossy();
756 for line in &breakpoint_lines {
757 script_str.push_str(&format!("bp `{}:{}`\n", source_file_name, line));
760 // Append the other `cdb-command:`s
761 for line in &commands {
762 script_str.push_str(line);
763 script_str.push_str("\n");
766 script_str.push_str("\nqq\n"); // Quit the debugger (including remote debugger, if any)
768 // Write the script into a file
769 debug!("script_str = {}", script_str);
770 self.dump_output_file(&script_str, "debugger.script");
771 let debugger_script = self.make_out_name("debugger.script");
773 let cdb_path = &self.config.cdb.as_ref().unwrap();
774 let mut cdb = Command::new(cdb_path);
775 cdb.arg("-lines") // Enable source line debugging.
777 .arg(&debugger_script)
780 let debugger_run_result = self.compose_and_run(
782 self.config.run_lib_path.to_str().unwrap(),
787 if !debugger_run_result.status.success() {
788 self.fatal_proc_rec("Error while running CDB", &debugger_run_result);
791 self.check_debugger_output(&debugger_run_result, &check_lines);
794 fn run_debuginfo_gdb_test(&self) {
795 assert!(self.revision.is_none(), "revisions not relevant here");
797 let config = Config {
798 target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
799 host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
800 ..self.config.clone()
803 let test_cx = TestCx { config: &config, ..*self };
805 test_cx.run_debuginfo_gdb_test_no_opt();
808 fn run_debuginfo_gdb_test_no_opt(&self) {
809 let prefixes = if self.config.gdb_native_rust {
811 static PREFIXES: &'static [&'static str] = &["gdb", "gdbr"];
812 println!("NOTE: compiletest thinks it is using GDB with native rust support");
816 static PREFIXES: &'static [&'static str] = &["gdb", "gdbg"];
817 println!("NOTE: compiletest thinks it is using GDB without native rust support");
821 let DebuggerCommands { commands, check_lines, breakpoint_lines } =
822 self.parse_debugger_commands(prefixes);
823 let mut cmds = commands.join("\n");
825 // compile test file (it should have 'compile-flags:-g' in the header)
826 let compiler_run_result = self.compile_test(WillExecute::Yes, EmitMetadata::No);
827 if !compiler_run_result.status.success() {
828 self.fatal_proc_rec("compilation failed!", &compiler_run_result);
831 let exe_file = self.make_exe_name();
833 let debugger_run_result;
834 if is_android_gdb_target(&self.config.target) {
835 cmds = cmds.replace("run", "continue");
837 let tool_path = match self.config.android_cross_path.to_str() {
838 Some(x) => x.to_owned(),
839 None => self.fatal("cannot find android cross path"),
842 // write debugger script
843 let mut script_str = String::with_capacity(2048);
844 script_str.push_str(&format!("set charset {}\n", Self::charset()));
845 script_str.push_str(&format!("set sysroot {}\n", tool_path));
846 script_str.push_str(&format!("file {}\n", exe_file.to_str().unwrap()));
847 script_str.push_str("target remote :5039\n");
848 script_str.push_str(&format!(
849 "set solib-search-path \
850 ./{}/stage2/lib/rustlib/{}/lib/\n",
851 self.config.host, self.config.target
853 for line in &breakpoint_lines {
857 self.testpaths.file.file_name().unwrap().to_string_lossy(),
862 script_str.push_str(&cmds);
863 script_str.push_str("\nquit\n");
865 debug!("script_str = {}", script_str);
866 self.dump_output_file(&script_str, "debugger.script");
868 let adb_path = &self.config.adb_path;
870 Command::new(adb_path)
873 .arg(&self.config.adb_test_dir)
875 .expect(&format!("failed to exec `{:?}`", adb_path));
877 Command::new(adb_path)
878 .args(&["forward", "tcp:5039", "tcp:5039"])
880 .expect(&format!("failed to exec `{:?}`", adb_path));
882 let adb_arg = format!(
883 "export LD_LIBRARY_PATH={}; \
884 gdbserver{} :5039 {}/{}",
885 self.config.adb_test_dir.clone(),
886 if self.config.target.contains("aarch64") { "64" } else { "" },
887 self.config.adb_test_dir.clone(),
888 exe_file.file_name().unwrap().to_str().unwrap()
891 debug!("adb arg: {}", adb_arg);
892 let mut adb = Command::new(adb_path)
893 .args(&["shell", &adb_arg])
894 .stdout(Stdio::piped())
895 .stderr(Stdio::inherit())
897 .expect(&format!("failed to exec `{:?}`", adb_path));
899 // Wait for the gdbserver to print out "Listening on port ..."
900 // at which point we know that it's started and then we can
901 // execute the debugger below.
902 let mut stdout = BufReader::new(adb.stdout.take().unwrap());
903 let mut line = String::new();
906 stdout.read_line(&mut line).unwrap();
907 if line.starts_with("Listening on port 5039") {
913 let mut debugger_script = OsString::from("-command=");
914 debugger_script.push(self.make_out_name("debugger.script"));
915 let debugger_opts: &[&OsStr] =
916 &["-quiet".as_ref(), "-batch".as_ref(), "-nx".as_ref(), &debugger_script];
918 let gdb_path = self.config.gdb.as_ref().unwrap();
919 let Output { status, stdout, stderr } = Command::new(&gdb_path)
922 .expect(&format!("failed to exec `{:?}`", gdb_path));
924 let mut gdb = Command::new(&format!("{}-gdb", self.config.target));
925 gdb.args(debugger_opts);
926 let cmdline = self.make_cmdline(&gdb, "");
927 logv(self.config, format!("executing {}", cmdline));
931 debugger_run_result = ProcRes {
933 stdout: String::from_utf8(stdout).unwrap(),
934 stderr: String::from_utf8(stderr).unwrap(),
937 if adb.kill().is_err() {
938 println!("Adb process is already finished.");
942 self.config.find_rust_src_root().expect("Could not find Rust source root");
943 let rust_pp_module_rel_path = Path::new("./src/etc");
944 let rust_pp_module_abs_path =
945 rust_src_root.join(rust_pp_module_rel_path).to_str().unwrap().to_owned();
946 // write debugger script
947 let mut script_str = String::with_capacity(2048);
948 script_str.push_str(&format!("set charset {}\n", Self::charset()));
949 script_str.push_str("show version\n");
951 match self.config.gdb_version {
953 println!("NOTE: compiletest thinks it is using GDB version {}", version);
955 if version > extract_gdb_version("7.4").unwrap() {
956 // Add the directory containing the pretty printers to
957 // GDB's script auto loading safe path
958 script_str.push_str(&format!(
959 "add-auto-load-safe-path {}\n",
960 rust_pp_module_abs_path.replace(r"\", r"\\")
966 "NOTE: compiletest does not know which version of \
972 // The following line actually doesn't have to do anything with
973 // pretty printing, it just tells GDB to print values on one line:
974 script_str.push_str("set print pretty off\n");
976 // Add the pretty printer directory to GDB's source-file search path
977 script_str.push_str(&format!("directory {}\n", rust_pp_module_abs_path));
979 // Load the target executable
981 .push_str(&format!("file {}\n", exe_file.to_str().unwrap().replace(r"\", r"\\")));
983 // Force GDB to print values in the Rust format.
984 if self.config.gdb_native_rust {
985 script_str.push_str("set language rust\n");
988 // Add line breakpoints
989 for line in &breakpoint_lines {
990 script_str.push_str(&format!(
992 self.testpaths.file.file_name().unwrap().to_string_lossy(),
997 script_str.push_str(&cmds);
998 script_str.push_str("\nquit\n");
1000 debug!("script_str = {}", script_str);
1001 self.dump_output_file(&script_str, "debugger.script");
1003 let mut debugger_script = OsString::from("-command=");
1004 debugger_script.push(self.make_out_name("debugger.script"));
1006 let debugger_opts: &[&OsStr] =
1007 &["-quiet".as_ref(), "-batch".as_ref(), "-nx".as_ref(), &debugger_script];
1009 let mut gdb = Command::new(self.config.gdb.as_ref().unwrap());
1010 gdb.args(debugger_opts).env("PYTHONPATH", rust_pp_module_abs_path);
1012 debugger_run_result =
1013 self.compose_and_run(gdb, self.config.run_lib_path.to_str().unwrap(), None, None);
1016 if !debugger_run_result.status.success() {
1017 self.fatal_proc_rec("gdb failed to execute", &debugger_run_result);
1020 self.check_debugger_output(&debugger_run_result, &check_lines);
1023 fn run_debuginfo_lldb_test(&self) {
1024 assert!(self.revision.is_none(), "revisions not relevant here");
1026 if self.config.lldb_python_dir.is_none() {
1027 self.fatal("Can't run LLDB test because LLDB's python path is not set.");
1030 let config = Config {
1031 target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
1032 host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
1033 ..self.config.clone()
1036 let test_cx = TestCx { config: &config, ..*self };
1038 test_cx.run_debuginfo_lldb_test_no_opt();
1041 fn run_debuginfo_lldb_test_no_opt(&self) {
1042 // compile test file (it should have 'compile-flags:-g' in the header)
1043 let compile_result = self.compile_test(WillExecute::Yes, EmitMetadata::No);
1044 if !compile_result.status.success() {
1045 self.fatal_proc_rec("compilation failed!", &compile_result);
1048 let exe_file = self.make_exe_name();
1050 match self.config.lldb_version {
1051 Some(ref version) => {
1052 println!("NOTE: compiletest thinks it is using LLDB version {}", version);
1056 "NOTE: compiletest does not know which version of \
1062 let prefixes = if self.config.lldb_native_rust {
1063 static PREFIXES: &'static [&'static str] = &["lldb", "lldbr"];
1064 println!("NOTE: compiletest thinks it is using LLDB with native rust support");
1067 static PREFIXES: &'static [&'static str] = &["lldb", "lldbg"];
1068 println!("NOTE: compiletest thinks it is using LLDB without native rust support");
1072 // Parse debugger commands etc from test files
1073 let DebuggerCommands { commands, check_lines, breakpoint_lines, .. } =
1074 self.parse_debugger_commands(prefixes);
1076 // Write debugger script:
1077 // We don't want to hang when calling `quit` while the process is still running
1078 let mut script_str = String::from("settings set auto-confirm true\n");
1080 // Make LLDB emit its version, so we have it documented in the test output
1081 script_str.push_str("version\n");
1083 // Switch LLDB into "Rust mode"
1085 self.config.find_rust_src_root().expect("Could not find Rust source root");
1086 let rust_pp_module_rel_path = Path::new("./src/etc/lldb_rust_formatters.py");
1087 let rust_pp_module_abs_path =
1088 rust_src_root.join(rust_pp_module_rel_path).to_str().unwrap().to_owned();
1091 .push_str(&format!("command script import {}\n", &rust_pp_module_abs_path[..])[..]);
1092 script_str.push_str("type summary add --no-value ");
1093 script_str.push_str("--python-function lldb_rust_formatters.print_val ");
1094 script_str.push_str("-x \".*\" --category Rust\n");
1095 script_str.push_str("type category enable Rust\n");
1097 // Set breakpoints on every line that contains the string "#break"
1098 let source_file_name = self.testpaths.file.file_name().unwrap().to_string_lossy();
1099 for line in &breakpoint_lines {
1100 script_str.push_str(&format!(
1101 "breakpoint set --file '{}' --line {}\n",
1102 source_file_name, line
1106 // Append the other commands
1107 for line in &commands {
1108 script_str.push_str(line);
1109 script_str.push_str("\n");
1112 // Finally, quit the debugger
1113 script_str.push_str("\nquit\n");
1115 // Write the script into a file
1116 debug!("script_str = {}", script_str);
1117 self.dump_output_file(&script_str, "debugger.script");
1118 let debugger_script = self.make_out_name("debugger.script");
1120 // Let LLDB execute the script via lldb_batchmode.py
1121 let debugger_run_result = self.run_lldb(&exe_file, &debugger_script, &rust_src_root);
1123 if !debugger_run_result.status.success() {
1124 self.fatal_proc_rec("Error while running LLDB", &debugger_run_result);
1127 self.check_debugger_output(&debugger_run_result, &check_lines);
1132 test_executable: &Path,
1133 debugger_script: &Path,
1134 rust_src_root: &Path,
1136 // Prepare the lldb_batchmode which executes the debugger script
1137 let lldb_script_path = rust_src_root.join("src/etc/lldb_batchmode.py");
1139 Command::new(&self.config.lldb_python)
1140 .arg(&lldb_script_path)
1141 .arg(test_executable)
1142 .arg(debugger_script)
1143 .env("PYTHONPATH", self.config.lldb_python_dir.as_ref().unwrap()),
1147 fn cmd2procres(&self, cmd: &mut Command) -> ProcRes {
1148 let (status, out, err) = match cmd.output() {
1149 Ok(Output { status, stdout, stderr }) => {
1150 (status, String::from_utf8(stdout).unwrap(), String::from_utf8(stderr).unwrap())
1152 Err(e) => self.fatal(&format!(
1153 "Failed to setup Python process for \
1159 self.dump_output(&out, &err);
1160 ProcRes { status, stdout: out, stderr: err, cmdline: format!("{:?}", cmd) }
1163 fn parse_debugger_commands(&self, debugger_prefixes: &[&str]) -> DebuggerCommands {
1164 let directives = debugger_prefixes
1166 .map(|prefix| (format!("{}-command", prefix), format!("{}-check", prefix)))
1167 .collect::<Vec<_>>();
1169 let mut breakpoint_lines = vec![];
1170 let mut commands = vec![];
1171 let mut check_lines = vec![];
1172 let mut counter = 1;
1173 let reader = BufReader::new(File::open(&self.testpaths.file).unwrap());
1174 for line in reader.lines() {
1178 if line.starts_with("//") { line[2..].trim_start() } else { line.as_str() };
1180 if line.contains("#break") {
1181 breakpoint_lines.push(counter);
1184 for &(ref command_directive, ref check_directive) in &directives {
1186 .parse_name_value_directive(&line, command_directive)
1187 .map(|cmd| commands.push(cmd));
1190 .parse_name_value_directive(&line, check_directive)
1191 .map(|cmd| check_lines.push(cmd));
1194 Err(e) => self.fatal(&format!("Error while parsing debugger commands: {}", e)),
1199 DebuggerCommands { commands, check_lines, breakpoint_lines }
1202 fn cleanup_debug_info_options(&self, options: &Option<String>) -> Option<String> {
1203 if options.is_none() {
1207 // Remove options that are either unwanted (-O) or may lead to duplicates due to RUSTFLAGS.
1208 let options_to_remove = ["-O".to_owned(), "-g".to_owned(), "--debuginfo".to_owned()];
1209 let new_options = self
1210 .split_maybe_args(options)
1212 .filter(|x| !options_to_remove.contains(x))
1213 .collect::<Vec<String>>();
1215 Some(new_options.join(" "))
1218 fn maybe_add_external_args(&self, cmd: &mut Command, args: Vec<String>) {
1219 // Filter out the arguments that should not be added by runtest here.
1221 // Notable use-cases are: do not add our optimisation flag if
1222 // `compile-flags: -Copt-level=x` and similar for debug-info level as well.
1223 const OPT_FLAGS: &[&str] = &["-O", "-Copt-level=", /*-C<space>*/ "opt-level="];
1224 const DEBUG_FLAGS: &[&str] = &["-g", "-Cdebuginfo=", /*-C<space>*/ "debuginfo="];
1226 // FIXME: ideally we would "just" check the `cmd` itself, but it does not allow inspecting
1227 // its arguments. They need to be collected separately. For now I cannot be bothered to
1228 // implement this the "right" way.
1230 self.props.compile_flags.iter().any(|arg| OPT_FLAGS.iter().any(|f| arg.starts_with(f)));
1231 let have_debug_flag = self
1235 .any(|arg| DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)));
1238 if OPT_FLAGS.iter().any(|f| arg.starts_with(f)) && have_opt_flag {
1241 if DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)) && have_debug_flag {
1248 fn check_debugger_output(&self, debugger_run_result: &ProcRes, check_lines: &[String]) {
1249 let num_check_lines = check_lines.len();
1251 let mut check_line_index = 0;
1252 for line in debugger_run_result.stdout.lines() {
1253 if check_line_index >= num_check_lines {
1257 if check_single_line(line, &(check_lines[check_line_index])[..]) {
1258 check_line_index += 1;
1261 if check_line_index != num_check_lines && num_check_lines > 0 {
1262 self.fatal_proc_rec(
1263 &format!("line not found in debugger output: {}", check_lines[check_line_index]),
1264 debugger_run_result,
1268 fn check_single_line(line: &str, check_line: &str) -> bool {
1269 // Allow check lines to leave parts unspecified (e.g., uninitialized
1270 // bits in the wrong case of an enum) with the notation "[...]".
1271 let line = line.trim();
1272 let check_line = check_line.trim();
1273 let can_start_anywhere = check_line.starts_with("[...]");
1274 let can_end_anywhere = check_line.ends_with("[...]");
1276 let check_fragments: Vec<&str> =
1277 check_line.split("[...]").filter(|frag| !frag.is_empty()).collect();
1278 if check_fragments.is_empty() {
1282 let (mut rest, first_fragment) = if can_start_anywhere {
1283 match line.find(check_fragments[0]) {
1284 Some(pos) => (&line[pos + check_fragments[0].len()..], 1),
1285 None => return false,
1291 for current_fragment in &check_fragments[first_fragment..] {
1292 match rest.find(current_fragment) {
1294 rest = &rest[pos + current_fragment.len()..];
1296 None => return false,
1300 if !can_end_anywhere && !rest.is_empty() {
1308 fn check_error_patterns(
1310 output_to_check: &str,
1312 pm: Option<PassMode>,
1314 debug!("check_error_patterns");
1315 if self.props.error_patterns.is_empty() {
1320 self.fatal(&format!(
1321 "no error pattern specified in {:?}",
1322 self.testpaths.file.display()
1327 let mut missing_patterns: Vec<String> = Vec::new();
1329 for pattern in &self.props.error_patterns {
1330 if output_to_check.contains(pattern.trim()) {
1331 debug!("found error pattern {}", pattern);
1333 missing_patterns.push(pattern.to_string());
1337 if missing_patterns.is_empty() {
1341 if missing_patterns.len() == 1 {
1342 self.fatal_proc_rec(
1343 &format!("error pattern '{}' not found!", missing_patterns[0]),
1347 for pattern in missing_patterns {
1348 self.error(&format!("error pattern '{}' not found!", pattern));
1350 self.fatal_proc_rec("multiple error patterns not found", proc_res);
1354 fn check_no_compiler_crash(&self, proc_res: &ProcRes, should_ice: bool) {
1355 match proc_res.status.code() {
1356 Some(101) if !should_ice => {
1357 self.fatal_proc_rec("compiler encountered internal error", proc_res)
1359 None => self.fatal_proc_rec("compiler terminated by signal", proc_res),
1364 fn check_forbid_output(&self, output_to_check: &str, proc_res: &ProcRes) {
1365 for pat in &self.props.forbid_output {
1366 if output_to_check.contains(pat) {
1367 self.fatal_proc_rec("forbidden pattern found in compiler output", proc_res);
1372 fn check_expected_errors(&self, expected_errors: Vec<errors::Error>, proc_res: &ProcRes) {
1374 "check_expected_errors: expected_errors={:?} proc_res.status={:?}",
1375 expected_errors, proc_res.status
1377 if proc_res.status.success()
1378 && expected_errors.iter().any(|x| x.kind == Some(ErrorKind::Error))
1380 self.fatal_proc_rec("process did not return an error status", proc_res);
1383 // On Windows, keep all '\' path separators to match the paths reported in the JSON output
1384 // from the compiler
1385 let os_file_name = self.testpaths.file.display().to_string();
1387 // on windows, translate all '\' path separators to '/'
1388 let file_name = format!("{}", self.testpaths.file.display()).replace(r"\", "/");
1390 // If the testcase being checked contains at least one expected "help"
1391 // message, then we'll ensure that all "help" messages are expected.
1392 // Otherwise, all "help" messages reported by the compiler will be ignored.
1393 // This logic also applies to "note" messages.
1394 let expect_help = expected_errors.iter().any(|ee| ee.kind == Some(ErrorKind::Help));
1395 let expect_note = expected_errors.iter().any(|ee| ee.kind == Some(ErrorKind::Note));
1397 // Parse the JSON output from the compiler and extract out the messages.
1398 let actual_errors = json::parse_output(&os_file_name, &proc_res.stderr, proc_res);
1399 let mut unexpected = Vec::new();
1400 let mut found = vec![false; expected_errors.len()];
1401 for actual_error in &actual_errors {
1403 expected_errors.iter().enumerate().position(|(index, expected_error)| {
1405 && actual_error.line_num == expected_error.line_num
1406 && (expected_error.kind.is_none()
1407 || actual_error.kind == expected_error.kind)
1408 && actual_error.msg.contains(&expected_error.msg)
1413 // found a match, everybody is happy
1414 assert!(!found[index]);
1415 found[index] = true;
1419 if self.is_unexpected_compiler_message(actual_error, expect_help, expect_note) {
1420 self.error(&format!(
1421 "{}:{}: unexpected {}: '{}'",
1423 actual_error.line_num,
1427 .map_or(String::from("message"), |k| k.to_string()),
1430 unexpected.push(actual_error);
1436 let mut not_found = Vec::new();
1437 // anything not yet found is a problem
1438 for (index, expected_error) in expected_errors.iter().enumerate() {
1440 self.error(&format!(
1441 "{}:{}: expected {} not found: {}",
1443 expected_error.line_num,
1444 expected_error.kind.as_ref().map_or("message".into(), |k| k.to_string()),
1447 not_found.push(expected_error);
1451 if !unexpected.is_empty() || !not_found.is_empty() {
1452 self.error(&format!(
1453 "{} unexpected errors found, {} expected errors not found",
1457 println!("status: {}\ncommand: {}", proc_res.status, proc_res.cmdline);
1458 if !unexpected.is_empty() {
1459 println!("unexpected errors (from JSON output): {:#?}\n", unexpected);
1461 if !not_found.is_empty() {
1462 println!("not found errors (from test file): {:#?}\n", not_found);
1468 /// Returns `true` if we should report an error about `actual_error`,
1469 /// which did not match any of the expected error. We always require
1470 /// errors/warnings to be explicitly listed, but only require
1471 /// helps/notes if there are explicit helps/notes given.
1472 fn is_unexpected_compiler_message(
1474 actual_error: &Error,
1478 match actual_error.kind {
1479 Some(ErrorKind::Help) => expect_help,
1480 Some(ErrorKind::Note) => expect_note,
1481 Some(ErrorKind::Error) | Some(ErrorKind::Warning) => true,
1482 Some(ErrorKind::Suggestion) | None => false,
1486 fn should_emit_metadata(&self, pm: Option<PassMode>) -> EmitMetadata {
1487 match (pm, self.props.fail_mode, self.config.mode) {
1488 (Some(PassMode::Check), ..) | (_, Some(FailMode::Check), Ui) => EmitMetadata::Yes,
1489 _ => EmitMetadata::No,
1493 fn compile_test(&self, will_execute: WillExecute, emit_metadata: EmitMetadata) -> ProcRes {
1494 self.compile_test_general(will_execute, emit_metadata, self.props.local_pass_mode())
1497 fn compile_test_general(
1499 will_execute: WillExecute,
1500 emit_metadata: EmitMetadata,
1501 local_pm: Option<PassMode>,
1503 // Only use `make_exe_name` when the test ends up being executed.
1504 let output_file = match will_execute {
1505 WillExecute::Yes => TargetLocation::ThisFile(self.make_exe_name()),
1506 WillExecute::No => TargetLocation::ThisDirectory(self.output_base_dir()),
1509 let allow_unused = match self.config.mode {
1510 CompileFail | Ui => {
1511 // compile-fail and ui tests tend to have tons of unused code as
1512 // it's just testing various pieces of the compile, but we don't
1513 // want to actually assert warnings about all this code. Instead
1514 // let's just ignore unused code warnings by defaults and tests
1515 // can turn it back on if needed.
1516 if !self.is_rustdoc()
1517 // Note that we use the local pass mode here as we don't want
1518 // to set unused to allow if we've overridden the pass mode
1519 // via command line flags.
1520 && local_pm != Some(PassMode::Run)
1527 _ => AllowUnused::No,
1531 self.make_compile_args(&self.testpaths.file, output_file, emit_metadata, allow_unused);
1533 rustc.arg("-L").arg(&self.aux_output_dir_name());
1535 self.compose_and_run_compiler(rustc, None)
1538 fn document(&self, out_dir: &Path) -> ProcRes {
1539 if self.props.build_aux_docs {
1540 for rel_ab in &self.props.aux_builds {
1541 let aux_testpaths = self.compute_aux_test_paths(rel_ab);
1543 self.props.from_aux_file(&aux_testpaths.file, self.revision, self.config);
1544 let aux_cx = TestCx {
1545 config: self.config,
1547 testpaths: &aux_testpaths,
1548 revision: self.revision,
1550 // Create the directory for the stdout/stderr files.
1551 create_dir_all(aux_cx.output_base_dir()).unwrap();
1552 let auxres = aux_cx.document(out_dir);
1553 if !auxres.status.success() {
1559 let aux_dir = self.aux_output_dir_name();
1561 let rustdoc_path = self.config.rustdoc_path.as_ref().expect("--rustdoc-path passed");
1562 let mut rustdoc = Command::new(rustdoc_path);
1566 .arg(self.config.run_lib_path.to_str().unwrap())
1571 .arg(&self.testpaths.file)
1572 .args(&self.props.compile_flags);
1574 if let Some(ref linker) = self.config.linker {
1575 rustdoc.arg(format!("-Clinker={}", linker));
1578 self.compose_and_run_compiler(rustdoc, None)
1581 fn exec_compiled_test(&self) -> ProcRes {
1582 let env = &self.props.exec_env;
1584 let proc_res = match &*self.config.target {
1585 // This is pretty similar to below, we're transforming:
1587 // program arg1 arg2
1591 // remote-test-client run program:support-lib.so arg1 arg2
1593 // The test-client program will upload `program` to the emulator
1594 // along with all other support libraries listed (in this case
1595 // `support-lib.so`. It will then execute the program on the
1596 // emulator with the arguments specified (in the environment we give
1597 // the process) and then report back the same result.
1598 _ if self.config.remote_test_client.is_some() => {
1599 let aux_dir = self.aux_output_dir_name();
1600 let ProcArgs { mut prog, args } = self.make_run_args();
1601 if let Ok(entries) = aux_dir.read_dir() {
1602 for entry in entries {
1603 let entry = entry.unwrap();
1604 if !entry.path().is_file() {
1608 prog.push_str(entry.path().to_str().unwrap());
1611 let mut test_client =
1612 Command::new(self.config.remote_test_client.as_ref().unwrap());
1613 test_client.args(&["run", &prog]).args(args).envs(env.clone());
1614 self.compose_and_run(
1616 self.config.run_lib_path.to_str().unwrap(),
1617 Some(aux_dir.to_str().unwrap()),
1621 _ if self.config.target.contains("vxworks") => {
1622 let aux_dir = self.aux_output_dir_name();
1623 let ProcArgs { prog, args } = self.make_run_args();
1624 let mut wr_run = Command::new("wr-run");
1625 wr_run.args(&[&prog]).args(args).envs(env.clone());
1626 self.compose_and_run(
1628 self.config.run_lib_path.to_str().unwrap(),
1629 Some(aux_dir.to_str().unwrap()),
1634 let aux_dir = self.aux_output_dir_name();
1635 let ProcArgs { prog, args } = self.make_run_args();
1636 let mut program = Command::new(&prog);
1637 program.args(args).current_dir(&self.output_base_dir()).envs(env.clone());
1638 self.compose_and_run(
1640 self.config.run_lib_path.to_str().unwrap(),
1641 Some(aux_dir.to_str().unwrap()),
1647 if proc_res.status.success() {
1648 // delete the executable after running it to save space.
1649 // it is ok if the deletion failed.
1650 let _ = fs::remove_file(self.make_exe_name());
1656 /// For each `aux-build: foo/bar` annotation, we check to find the
1657 /// file in a `auxiliary` directory relative to the test itself.
1658 fn compute_aux_test_paths(&self, rel_ab: &str) -> TestPaths {
1663 .expect("test file path has no parent")
1666 if !test_ab.exists() {
1667 self.fatal(&format!("aux-build `{}` source not found", test_ab.display()))
1675 .join(self.output_testname_unique())
1679 .expect("aux-build path has no parent")
1684 fn is_vxworks_pure_static(&self) -> bool {
1685 if self.config.target.contains("vxworks") {
1686 match env::var("RUST_VXWORKS_TEST_DYLINK") {
1695 fn is_vxworks_pure_dynamic(&self) -> bool {
1696 self.config.target.contains("vxworks") && !self.is_vxworks_pure_static()
1699 fn compose_and_run_compiler(&self, mut rustc: Command, input: Option<String>) -> ProcRes {
1700 let aux_dir = self.aux_output_dir_name();
1702 if !self.props.aux_builds.is_empty() {
1703 let _ = fs::remove_dir_all(&aux_dir);
1704 create_dir_all(&aux_dir).unwrap();
1707 for rel_ab in &self.props.aux_builds {
1708 self.build_auxiliary(rel_ab, &aux_dir);
1711 for (aux_name, aux_path) in &self.props.aux_crates {
1712 let is_dylib = self.build_auxiliary(&aux_path, &aux_dir);
1714 get_lib_name(&aux_path.trim_end_matches(".rs").replace('-', "_"), is_dylib);
1715 rustc.arg("--extern").arg(format!("{}={}/{}", aux_name, aux_dir.display(), lib_name));
1718 self.props.unset_rustc_env.clone().iter().fold(&mut rustc, |rustc, v| rustc.env_remove(v));
1719 rustc.envs(self.props.rustc_env.clone());
1720 self.compose_and_run(
1722 self.config.compile_lib_path.to_str().unwrap(),
1723 Some(aux_dir.to_str().unwrap()),
1728 /// Builds an aux dependency.
1730 /// Returns whether or not it is a dylib.
1731 fn build_auxiliary(&self, source_path: &str, aux_dir: &Path) -> bool {
1732 let aux_testpaths = self.compute_aux_test_paths(source_path);
1733 let aux_props = self.props.from_aux_file(&aux_testpaths.file, self.revision, self.config);
1734 let aux_output = TargetLocation::ThisDirectory(self.aux_output_dir_name());
1735 let aux_cx = TestCx {
1736 config: self.config,
1738 testpaths: &aux_testpaths,
1739 revision: self.revision,
1741 // Create the directory for the stdout/stderr files.
1742 create_dir_all(aux_cx.output_base_dir()).unwrap();
1743 let input_file = &aux_testpaths.file;
1745 aux_cx.make_compile_args(input_file, aux_output, EmitMetadata::No, AllowUnused::No);
1747 let (dylib, crate_type) = if aux_props.no_prefer_dynamic {
1749 } else if self.config.target.contains("cloudabi")
1750 || self.config.target.contains("emscripten")
1751 || (self.config.target.contains("musl")
1752 && !aux_props.force_host
1753 && !self.config.host.contains("musl"))
1754 || self.config.target.contains("wasm32")
1755 || self.config.target.contains("nvptx")
1756 || self.is_vxworks_pure_static()
1758 // We primarily compile all auxiliary libraries as dynamic libraries
1759 // to avoid code size bloat and large binaries as much as possible
1760 // for the test suite (otherwise including libstd statically in all
1761 // executables takes up quite a bit of space).
1763 // For targets like MUSL or Emscripten, however, there is no support for
1764 // dynamic libraries so we just go back to building a normal library. Note,
1765 // however, that for MUSL if the library is built with `force_host` then
1766 // it's ok to be a dylib as the host should always support dylibs.
1767 (false, Some("lib"))
1769 (true, Some("dylib"))
1772 if let Some(crate_type) = crate_type {
1773 aux_rustc.args(&["--crate-type", crate_type]);
1776 aux_rustc.arg("-L").arg(&aux_dir);
1778 let auxres = aux_cx.compose_and_run(
1780 aux_cx.config.compile_lib_path.to_str().unwrap(),
1781 Some(aux_dir.to_str().unwrap()),
1784 if !auxres.status.success() {
1785 self.fatal_proc_rec(
1787 "auxiliary build of {:?} failed to compile: ",
1788 aux_testpaths.file.display()
1798 mut command: Command,
1800 aux_path: Option<&str>,
1801 input: Option<String>,
1804 let cmdline = self.make_cmdline(&command, lib_path);
1805 logv(self.config, format!("executing {}", cmdline));
1809 command.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::piped());
1811 // Need to be sure to put both the lib_path and the aux path in the dylib
1812 // search path for the child.
1813 let mut path = env::split_paths(&env::var_os(dylib_env_var()).unwrap_or(OsString::new()))
1814 .collect::<Vec<_>>();
1815 if let Some(p) = aux_path {
1816 path.insert(0, PathBuf::from(p))
1818 path.insert(0, PathBuf::from(lib_path));
1820 // Add the new dylib search path var
1821 let newpath = env::join_paths(&path).unwrap();
1822 command.env(dylib_env_var(), newpath);
1824 let mut child = disable_error_reporting(|| command.spawn())
1825 .expect(&format!("failed to exec `{:?}`", &command));
1826 if let Some(input) = input {
1827 child.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap();
1830 let Output { status, stdout, stderr } =
1831 read2_abbreviated(child).expect("failed to read output");
1833 let result = ProcRes {
1835 stdout: String::from_utf8_lossy(&stdout).into_owned(),
1836 stderr: String::from_utf8_lossy(&stderr).into_owned(),
1840 self.dump_output(&result.stdout, &result.stderr);
1845 fn is_rustdoc(&self) -> bool {
1846 self.config.src_base.ends_with("rustdoc-ui") || self.config.src_base.ends_with("rustdoc-js")
1849 fn make_compile_args(
1852 output_file: TargetLocation,
1853 emit_metadata: EmitMetadata,
1854 allow_unused: AllowUnused,
1856 let is_rustdoc = self.is_rustdoc();
1857 let mut rustc = if !is_rustdoc {
1858 Command::new(&self.config.rustc_path)
1860 Command::new(&self.config.rustdoc_path.clone().expect("no rustdoc built yet"))
1862 // FIXME Why is -L here?
1863 rustc.arg(input_file); //.arg("-L").arg(&self.config.build_base);
1865 // Use a single thread for efficiency and a deterministic error message order
1866 rustc.arg("-Zthreads=1");
1868 // Optionally prevent default --target if specified in test compile-flags.
1869 let custom_target = self.props.compile_flags.iter().any(|x| x.starts_with("--target"));
1873 if self.props.force_host { &*self.config.host } else { &*self.config.target };
1875 rustc.arg(&format!("--target={}", target));
1877 self.set_revision_flags(&mut rustc);
1880 if let Some(ref incremental_dir) = self.props.incremental_dir {
1881 rustc.args(&["-C", &format!("incremental={}", incremental_dir.display())]);
1882 rustc.args(&["-Z", "incremental-verify-ich"]);
1885 if self.config.mode == CodegenUnits {
1886 rustc.args(&["-Z", "human_readable_cgu_names"]);
1890 match self.config.mode {
1891 CompileFail | Incremental => {
1892 // If we are extracting and matching errors in the new
1893 // fashion, then you want JSON mode. Old-skool error
1894 // patterns still match the raw compiler output.
1895 if self.props.error_patterns.is_empty() {
1896 rustc.args(&["--error-format", "json"]);
1898 rustc.arg("-Zui-testing");
1899 rustc.arg("-Zdeduplicate-diagnostics=no");
1902 if !self.props.compile_flags.iter().any(|s| s.starts_with("--error-format")) {
1903 rustc.args(&["--error-format", "json"]);
1905 rustc.arg("-Zui-testing");
1906 rustc.arg("-Zdeduplicate-diagnostics=no");
1911 "-Zmir-opt-level=3",
1912 "-Zdump-mir-exclude-pass-number",
1915 let mir_dump_dir = self.get_mir_dump_dir();
1916 let _ = fs::remove_dir_all(&mir_dump_dir);
1917 create_dir_all(mir_dump_dir.as_path()).unwrap();
1918 let mut dir_opt = "-Zdump-mir-dir=".to_string();
1919 dir_opt.push_str(mir_dump_dir.to_str().unwrap());
1920 debug!("dir_opt: {:?}", dir_opt);
1924 RunFail | RunPassValgrind | Pretty | DebugInfo | Codegen | Rustdoc | RunMake
1925 | CodegenUnits | JsDocTest | Assembly => {
1926 // do not use JSON output
1930 if let (false, EmitMetadata::Yes) = (is_rustdoc, emit_metadata) {
1931 rustc.args(&["--emit", "metadata"]);
1935 if self.config.target == "wasm32-unknown-unknown" || self.is_vxworks_pure_static() {
1936 // rustc.arg("-g"); // get any backtrace at all on errors
1937 } else if !self.props.no_prefer_dynamic {
1938 rustc.args(&["-C", "prefer-dynamic"]);
1943 TargetLocation::ThisFile(path) => {
1944 rustc.arg("-o").arg(path);
1946 TargetLocation::ThisDirectory(path) => {
1948 // `rustdoc` uses `-o` for the output directory.
1949 rustc.arg("-o").arg(path);
1951 rustc.arg("--out-dir").arg(path);
1956 match self.config.compare_mode {
1957 Some(CompareMode::Nll) => {
1958 rustc.args(&["-Zborrowck=mir"]);
1960 Some(CompareMode::Polonius) => {
1961 rustc.args(&["-Zpolonius", "-Zborrowck=mir"]);
1966 if self.props.force_host {
1967 self.maybe_add_external_args(
1969 self.split_maybe_args(&self.config.host_rustcflags),
1972 self.maybe_add_external_args(
1974 self.split_maybe_args(&self.config.target_rustcflags),
1977 if let Some(ref linker) = self.config.linker {
1978 rustc.arg(format!("-Clinker={}", linker));
1983 // Use dynamic musl for tests because static doesn't allow creating dylibs
1984 if self.config.host.contains("musl") || self.is_vxworks_pure_dynamic() {
1985 rustc.arg("-Ctarget-feature=-crt-static");
1988 if let AllowUnused::Yes = allow_unused {
1989 rustc.args(&["-A", "unused"]);
1992 rustc.args(&self.props.compile_flags);
1997 fn make_exe_name(&self) -> PathBuf {
1998 // Using a single letter here to keep the path length down for
1999 // Windows. Some test names get very long. rustc creates `rcgu`
2000 // files with the module name appended to it which can more than
2001 // double the length.
2002 let mut f = self.output_base_dir().join("a");
2003 // FIXME: This is using the host architecture exe suffix, not target!
2004 if self.config.target.contains("emscripten") {
2005 f = f.with_extra_extension("js");
2006 } else if self.config.target.contains("wasm32") {
2007 f = f.with_extra_extension("wasm");
2008 } else if !env::consts::EXE_SUFFIX.is_empty() {
2009 f = f.with_extra_extension(env::consts::EXE_SUFFIX);
2014 fn make_run_args(&self) -> ProcArgs {
2015 // If we've got another tool to run under (valgrind),
2016 // then split apart its command
2017 let mut args = self.split_maybe_args(&self.config.runtool);
2019 // If this is emscripten, then run tests under nodejs
2020 if self.config.target.contains("emscripten") {
2021 if let Some(ref p) = self.config.nodejs {
2022 args.push(p.clone());
2024 self.fatal("no NodeJS binary found (--nodejs)");
2026 // If this is otherwise wasm, then run tests under nodejs with our
2028 } else if self.config.target.contains("wasm32") {
2029 if let Some(ref p) = self.config.nodejs {
2030 args.push(p.clone());
2032 self.fatal("no NodeJS binary found (--nodejs)");
2039 .unwrap() // chop off `ui`
2041 .unwrap() // chop off `test`
2043 .unwrap(); // chop off `src`
2044 args.push(src.join("src/etc/wasm32-shim.js").display().to_string());
2047 let exe_file = self.make_exe_name();
2049 // FIXME (#9639): This needs to handle non-utf8 paths
2050 args.push(exe_file.to_str().unwrap().to_owned());
2052 // Add the arguments in the run_flags directive
2053 args.extend(self.split_maybe_args(&self.props.run_flags));
2055 let prog = args.remove(0);
2056 ProcArgs { prog, args }
2059 fn split_maybe_args(&self, argstr: &Option<String>) -> Vec<String> {
2064 if s.chars().all(|c| c.is_whitespace()) { None } else { Some(s.to_owned()) }
2071 fn make_cmdline(&self, command: &Command, libpath: &str) -> String {
2074 // Linux and mac don't require adjusting the library search path
2076 format!("{:?}", command)
2078 // Build the LD_LIBRARY_PATH variable as it would be seen on the command line
2079 // for diagnostic purposes
2080 fn lib_path_cmd_prefix(path: &str) -> String {
2081 format!("{}=\"{}\"", util::lib_path_env_var(), util::make_new_path(path))
2084 format!("{} {:?}", lib_path_cmd_prefix(libpath), command)
2088 fn dump_output(&self, out: &str, err: &str) {
2089 let revision = if let Some(r) = self.revision { format!("{}.", r) } else { String::new() };
2091 self.dump_output_file(out, &format!("{}out", revision));
2092 self.dump_output_file(err, &format!("{}err", revision));
2093 self.maybe_dump_to_stdout(out, err);
2096 fn dump_output_file(&self, out: &str, extension: &str) {
2097 let outfile = self.make_out_name(extension);
2098 fs::write(&outfile, out).unwrap();
2101 /// Creates a filename for output with the given extension.
2102 /// E.g., `/.../testname.revision.mode/testname.extension`.
2103 fn make_out_name(&self, extension: &str) -> PathBuf {
2104 self.output_base_name().with_extension(extension)
2107 /// Gets the directory where auxiliary files are written.
2108 /// E.g., `/.../testname.revision.mode/auxiliary/`.
2109 fn aux_output_dir_name(&self) -> PathBuf {
2110 self.output_base_dir()
2112 .with_extra_extension(self.config.mode.disambiguator())
2115 /// Generates a unique name for the test, such as `testname.revision.mode`.
2116 fn output_testname_unique(&self) -> PathBuf {
2117 output_testname_unique(self.config, self.testpaths, self.safe_revision())
2120 /// The revision, ignored for incremental compilation since it wants all revisions in
2121 /// the same directory.
2122 fn safe_revision(&self) -> Option<&str> {
2123 if self.config.mode == Incremental { None } else { self.revision }
2126 /// Gets the absolute path to the directory where all output for the given
2127 /// test/revision should reside.
2128 /// E.g., `/path/to/build/host-triple/test/ui/relative/testname.revision.mode/`.
2129 fn output_base_dir(&self) -> PathBuf {
2130 output_base_dir(self.config, self.testpaths, self.safe_revision())
2133 /// Gets the absolute path to the base filename used as output for the given
2135 /// E.g., `/.../relative/testname.revision.mode/testname`.
2136 fn output_base_name(&self) -> PathBuf {
2137 output_base_name(self.config, self.testpaths, self.safe_revision())
2140 fn maybe_dump_to_stdout(&self, out: &str, err: &str) {
2141 if self.config.verbose {
2142 println!("------{}------------------------------", "stdout");
2143 println!("{}", out);
2144 println!("------{}------------------------------", "stderr");
2145 println!("{}", err);
2146 println!("------------------------------------------");
2150 fn error(&self, err: &str) {
2151 match self.revision {
2152 Some(rev) => println!("\nerror in revision `{}`: {}", rev, err),
2153 None => println!("\nerror: {}", err),
2157 fn fatal(&self, err: &str) -> ! {
2159 error!("fatal error, panic: {:?}", err);
2160 panic!("fatal error");
2163 fn fatal_proc_rec(&self, err: &str, proc_res: &ProcRes) -> ! {
2165 proc_res.fatal(None);
2168 // codegen tests (using FileCheck)
2170 fn compile_test_and_save_ir(&self) -> ProcRes {
2171 let aux_dir = self.aux_output_dir_name();
2173 let output_file = TargetLocation::ThisDirectory(self.output_base_dir());
2174 let input_file = &self.testpaths.file;
2176 self.make_compile_args(input_file, output_file, EmitMetadata::No, AllowUnused::No);
2177 rustc.arg("-L").arg(aux_dir).arg("--emit=llvm-ir");
2179 self.compose_and_run_compiler(rustc, None)
2182 fn compile_test_and_save_assembly(&self) -> (ProcRes, PathBuf) {
2183 // This works with both `--emit asm` (as default output name for the assembly)
2184 // and `ptx-linker` because the latter can write output at requested location.
2185 let output_path = self.output_base_name().with_extension("s");
2187 let output_file = TargetLocation::ThisFile(output_path.clone());
2188 let input_file = &self.testpaths.file;
2190 self.make_compile_args(input_file, output_file, EmitMetadata::No, AllowUnused::No);
2192 rustc.arg("-L").arg(self.aux_output_dir_name());
2194 match self.props.assembly_output.as_ref().map(AsRef::as_ref) {
2195 Some("emit-asm") => {
2196 rustc.arg("--emit=asm");
2199 Some("ptx-linker") => {
2200 // No extra flags needed.
2203 Some(_) => self.fatal("unknown 'assembly-output' header"),
2204 None => self.fatal("missing 'assembly-output' header"),
2207 (self.compose_and_run_compiler(rustc, None), output_path)
2210 fn verify_with_filecheck(&self, output: &Path) -> ProcRes {
2211 let mut filecheck = Command::new(self.config.llvm_filecheck.as_ref().unwrap());
2212 filecheck.arg("--input-file").arg(output).arg(&self.testpaths.file);
2213 // It would be more appropriate to make most of the arguments configurable through
2214 // a comment-attribute similar to `compile-flags`. For example, --check-prefixes is a very
2217 // For now, though…
2218 if let Some(rev) = self.revision {
2219 let prefixes = format!("CHECK,{}", rev);
2220 filecheck.args(&["--check-prefixes", &prefixes]);
2222 self.compose_and_run(filecheck, "", None, None)
2225 fn run_codegen_test(&self) {
2226 if self.config.llvm_filecheck.is_none() {
2227 self.fatal("missing --llvm-filecheck");
2230 let proc_res = self.compile_test_and_save_ir();
2231 if !proc_res.status.success() {
2232 self.fatal_proc_rec("compilation failed!", &proc_res);
2235 let output_path = self.output_base_name().with_extension("ll");
2236 let proc_res = self.verify_with_filecheck(&output_path);
2237 if !proc_res.status.success() {
2238 self.fatal_proc_rec("verification with 'FileCheck' failed", &proc_res);
2242 fn run_assembly_test(&self) {
2243 if self.config.llvm_filecheck.is_none() {
2244 self.fatal("missing --llvm-filecheck");
2247 let (proc_res, output_path) = self.compile_test_and_save_assembly();
2248 if !proc_res.status.success() {
2249 self.fatal_proc_rec("compilation failed!", &proc_res);
2252 let proc_res = self.verify_with_filecheck(&output_path);
2253 if !proc_res.status.success() {
2254 self.fatal_proc_rec("verification with 'FileCheck' failed", &proc_res);
2258 fn charset() -> &'static str {
2259 // FreeBSD 10.1 defaults to GDB 6.1.1 which doesn't support "auto" charset
2260 if cfg!(target_os = "freebsd") { "ISO-8859-1" } else { "UTF-8" }
2263 fn run_rustdoc_test(&self) {
2264 assert!(self.revision.is_none(), "revisions not relevant here");
2266 let out_dir = self.output_base_dir();
2267 let _ = fs::remove_dir_all(&out_dir);
2268 create_dir_all(&out_dir).unwrap();
2270 let proc_res = self.document(&out_dir);
2271 if !proc_res.status.success() {
2272 self.fatal_proc_rec("rustdoc failed!", &proc_res);
2275 if self.props.check_test_line_numbers_match {
2276 self.check_rustdoc_test_option(proc_res);
2278 let root = self.config.find_rust_src_root().unwrap();
2279 let res = self.cmd2procres(
2280 Command::new(&self.config.docck_python)
2281 .arg(root.join("src/etc/htmldocck.py"))
2283 .arg(&self.testpaths.file),
2285 if !res.status.success() {
2286 self.fatal_proc_rec("htmldocck failed!", &res);
2291 fn get_lines<P: AsRef<Path>>(
2294 mut other_files: Option<&mut Vec<String>>,
2296 let content = fs::read_to_string(&path).unwrap();
2297 let mut ignore = false;
2301 .filter_map(|(line_nb, line)| {
2302 if (line.trim_start().starts_with("pub mod ")
2303 || line.trim_start().starts_with("mod "))
2304 && line.ends_with(';')
2306 if let Some(ref mut other_files) = other_files {
2307 other_files.push(line.rsplit("mod ").next().unwrap().replace(";", ""));
2311 let sline = line.split("///").last().unwrap_or("");
2312 let line = sline.trim_start();
2313 if line.starts_with("```") {
2329 fn check_rustdoc_test_option(&self, res: ProcRes) {
2330 let mut other_files = Vec::new();
2331 let mut files: HashMap<String, Vec<usize>> = HashMap::new();
2332 let cwd = env::current_dir().unwrap();
2337 .unwrap_or(&self.testpaths.file)
2340 .replace('\\', "/"),
2341 self.get_lines(&self.testpaths.file, Some(&mut other_files)),
2343 for other_file in other_files {
2344 let mut path = self.testpaths.file.clone();
2345 path.set_file_name(&format!("{}.rs", other_file));
2347 path.strip_prefix(&cwd).unwrap_or(&path).to_str().unwrap().replace('\\', "/"),
2348 self.get_lines(&path, None),
2353 for _ in res.stdout.split('\n').filter(|s| s.starts_with("test ")).inspect(|s| {
2354 let tmp: Vec<&str> = s.split(" - ").collect();
2356 let path = tmp[0].rsplit("test ").next().unwrap();
2357 if let Some(ref mut v) = files.get_mut(&path.replace('\\', "/")) {
2359 let mut iter = tmp[1].split("(line ");
2369 if let Ok(pos) = v.binary_search(&line) {
2372 self.fatal_proc_rec(
2373 &format!("Not found doc test: \"{}\" in \"{}\":{:?}", s, path, v),
2381 self.fatal_proc_rec(&format!("No test has been found... {:?}", files), &res);
2383 for (entry, v) in &files {
2385 self.fatal_proc_rec(
2387 "Not found test at line{} \"{}\":{:?}",
2388 if v.len() > 1 { "s" } else { "" },
2399 fn run_codegen_units_test(&self) {
2400 assert!(self.revision.is_none(), "revisions not relevant here");
2402 let proc_res = self.compile_test(WillExecute::No, EmitMetadata::No);
2404 if !proc_res.status.success() {
2405 self.fatal_proc_rec("compilation failed!", &proc_res);
2408 self.check_no_compiler_crash(&proc_res, self.props.should_ice);
2410 const PREFIX: &'static str = "MONO_ITEM ";
2411 const CGU_MARKER: &'static str = "@@";
2413 let actual: Vec<MonoItem> = proc_res
2416 .filter(|line| line.starts_with(PREFIX))
2417 .map(|line| str_to_mono_item(line, true))
2420 let expected: Vec<MonoItem> = errors::load_errors(&self.testpaths.file, None)
2422 .map(|e| str_to_mono_item(&e.msg[..], false))
2425 let mut missing = Vec::new();
2426 let mut wrong_cgus = Vec::new();
2428 for expected_item in &expected {
2429 let actual_item_with_same_name = actual.iter().find(|ti| ti.name == expected_item.name);
2431 if let Some(actual_item) = actual_item_with_same_name {
2432 if !expected_item.codegen_units.is_empty() &&
2433 // Also check for codegen units
2434 expected_item.codegen_units != actual_item.codegen_units
2436 wrong_cgus.push((expected_item.clone(), actual_item.clone()));
2439 missing.push(expected_item.string.clone());
2443 let unexpected: Vec<_> = actual
2445 .filter(|acgu| !expected.iter().any(|ecgu| acgu.name == ecgu.name))
2446 .map(|acgu| acgu.string.clone())
2449 if !missing.is_empty() {
2452 println!("\nThese items should have been contained but were not:\n");
2454 for item in &missing {
2455 println!("{}", item);
2461 if !unexpected.is_empty() {
2463 let mut sorted = unexpected.clone();
2468 println!("\nThese items were contained but should not have been:\n");
2470 for item in sorted {
2471 println!("{}", item);
2477 if !wrong_cgus.is_empty() {
2478 wrong_cgus.sort_by_key(|pair| pair.0.name.clone());
2479 println!("\nThe following items were assigned to wrong codegen units:\n");
2481 for &(ref expected_item, ref actual_item) in &wrong_cgus {
2482 println!("{}", expected_item.name);
2483 println!(" expected: {}", codegen_units_to_str(&expected_item.codegen_units));
2484 println!(" actual: {}", codegen_units_to_str(&actual_item.codegen_units));
2489 if !(missing.is_empty() && unexpected.is_empty() && wrong_cgus.is_empty()) {
2493 #[derive(Clone, Eq, PartialEq)]
2496 codegen_units: HashSet<String>,
2500 // [MONO_ITEM] name [@@ (cgu)+]
2501 fn str_to_mono_item(s: &str, cgu_has_crate_disambiguator: bool) -> MonoItem {
2502 let s = if s.starts_with(PREFIX) { (&s[PREFIX.len()..]).trim() } else { s.trim() };
2504 let full_string = format!("{}{}", PREFIX, s);
2506 let parts: Vec<&str> =
2507 s.split(CGU_MARKER).map(str::trim).filter(|s| !s.is_empty()).collect();
2509 let name = parts[0].trim();
2511 let cgus = if parts.len() > 1 {
2512 let cgus_str = parts[1];
2517 .filter(|s| !s.is_empty())
2519 if cgu_has_crate_disambiguator {
2520 remove_crate_disambiguator_from_cgu(s)
2530 MonoItem { name: name.to_owned(), codegen_units: cgus, string: full_string }
2533 fn codegen_units_to_str(cgus: &HashSet<String>) -> String {
2534 let mut cgus: Vec<_> = cgus.iter().collect();
2537 let mut string = String::new();
2539 string.push_str(&cgu[..]);
2540 string.push_str(" ");
2546 // Given a cgu-name-prefix of the form <crate-name>.<crate-disambiguator> or
2547 // the form <crate-name1>.<crate-disambiguator1>-in-<crate-name2>.<crate-disambiguator2>,
2548 // remove all crate-disambiguators.
2549 fn remove_crate_disambiguator_from_cgu(cgu: &str) -> String {
2551 static ref RE: Regex =
2552 Regex::new(r"^[^\.]+(?P<d1>\.[[:alnum:]]+)(-in-[^\.]+(?P<d2>\.[[:alnum:]]+))?")
2557 RE.captures(cgu).unwrap_or_else(|| panic!("invalid cgu name encountered: {}", cgu));
2559 let mut new_name = cgu.to_owned();
2561 if let Some(d2) = captures.name("d2") {
2562 new_name.replace_range(d2.start()..d2.end(), "");
2565 let d1 = captures.name("d1").unwrap();
2566 new_name.replace_range(d1.start()..d1.end(), "");
2572 fn init_incremental_test(&self) {
2573 // (See `run_incremental_test` for an overview of how incremental tests work.)
2575 // Before any of the revisions have executed, create the
2576 // incremental workproduct directory. Delete any old
2577 // incremental work products that may be there from prior
2579 let incremental_dir = self.incremental_dir();
2580 if incremental_dir.exists() {
2581 // Canonicalizing the path will convert it to the //?/ format
2582 // on Windows, which enables paths longer than 260 character
2583 let canonicalized = incremental_dir.canonicalize().unwrap();
2584 fs::remove_dir_all(canonicalized).unwrap();
2586 fs::create_dir_all(&incremental_dir).unwrap();
2588 if self.config.verbose {
2589 print!("init_incremental_test: incremental_dir={}", incremental_dir.display());
2593 fn run_incremental_test(&self) {
2594 // Basic plan for a test incremental/foo/bar.rs:
2595 // - load list of revisions rpass1, cfail2, rpass3
2596 // - each should begin with `rpass`, `cfail`, or `rfail`
2597 // - if `rpass`, expect compile and execution to succeed
2598 // - if `cfail`, expect compilation to fail
2599 // - if `rfail`, expect execution to fail
2600 // - create a directory build/foo/bar.incremental
2601 // - compile foo/bar.rs with -C incremental=.../foo/bar.incremental and -C rpass1
2602 // - because name of revision starts with "rpass", expect success
2603 // - compile foo/bar.rs with -C incremental=.../foo/bar.incremental and -C cfail2
2604 // - because name of revision starts with "cfail", expect an error
2605 // - load expected errors as usual, but filter for those that end in `[rfail2]`
2606 // - compile foo/bar.rs with -C incremental=.../foo/bar.incremental and -C rpass3
2607 // - because name of revision starts with "rpass", expect success
2608 // - execute build/foo/bar.exe and save output
2610 // FIXME -- use non-incremental mode as an oracle? That doesn't apply
2611 // to #[rustc_dirty] and clean tests I guess
2613 let revision = self.revision.expect("incremental tests require a list of revisions");
2615 // Incremental workproduct directory should have already been created.
2616 let incremental_dir = self.incremental_dir();
2617 assert!(incremental_dir.exists(), "init_incremental_test failed to create incremental dir");
2619 // Add an extra flag pointing at the incremental directory.
2620 let mut revision_props = self.props.clone();
2621 revision_props.incremental_dir = Some(incremental_dir);
2623 let revision_cx = TestCx {
2624 config: self.config,
2625 props: &revision_props,
2626 testpaths: self.testpaths,
2627 revision: self.revision,
2630 if self.config.verbose {
2631 print!("revision={:?} revision_props={:#?}", revision, revision_props);
2634 if revision.starts_with("rpass") {
2635 if revision_cx.props.should_ice {
2636 revision_cx.fatal("can only use should-ice in cfail tests");
2638 revision_cx.run_rpass_test();
2639 } else if revision.starts_with("rfail") {
2640 if revision_cx.props.should_ice {
2641 revision_cx.fatal("can only use should-ice in cfail tests");
2643 revision_cx.run_rfail_test();
2644 } else if revision.starts_with("cfail") {
2645 revision_cx.run_cfail_test();
2647 revision_cx.fatal("revision name must begin with rpass, rfail, or cfail");
2651 /// Directory where incremental work products are stored.
2652 fn incremental_dir(&self) -> PathBuf {
2653 self.output_base_name().with_extension("inc")
2656 fn run_rmake_test(&self) {
2657 let cwd = env::current_dir().unwrap();
2658 let src_root = self.config.src_base.parent().unwrap().parent().unwrap().parent().unwrap();
2659 let src_root = cwd.join(&src_root);
2661 let tmpdir = cwd.join(self.output_base_name());
2662 if tmpdir.exists() {
2663 self.aggressive_rm_rf(&tmpdir).unwrap();
2665 create_dir_all(&tmpdir).unwrap();
2667 let host = &self.config.host;
2668 let make = if host.contains("dragonfly")
2669 || host.contains("freebsd")
2670 || host.contains("netbsd")
2671 || host.contains("openbsd")
2678 let mut cmd = Command::new(make);
2679 cmd.current_dir(&self.testpaths.file)
2680 .stdout(Stdio::piped())
2681 .stderr(Stdio::piped())
2682 .env("TARGET", &self.config.target)
2683 .env("PYTHON", &self.config.docck_python)
2685 .env("RUST_BUILD_STAGE", &self.config.stage_id)
2686 .env("RUSTC", cwd.join(&self.config.rustc_path))
2687 .env("TMPDIR", &tmpdir)
2688 .env("LD_LIB_PATH_ENVVAR", dylib_env_var())
2689 .env("HOST_RPATH_DIR", cwd.join(&self.config.compile_lib_path))
2690 .env("TARGET_RPATH_DIR", cwd.join(&self.config.run_lib_path))
2691 .env("LLVM_COMPONENTS", &self.config.llvm_components)
2692 // We for sure don't want these tests to run in parallel, so make
2693 // sure they don't have access to these vars if we run via `make`
2695 .env_remove("MAKEFLAGS")
2696 .env_remove("MFLAGS")
2697 .env_remove("CARGO_MAKEFLAGS");
2699 if let Some(ref rustdoc) = self.config.rustdoc_path {
2700 cmd.env("RUSTDOC", cwd.join(rustdoc));
2703 if let Some(ref node) = self.config.nodejs {
2704 cmd.env("NODE", node);
2707 if let Some(ref linker) = self.config.linker {
2708 cmd.env("RUSTC_LINKER", linker);
2711 if let Some(ref clang) = self.config.run_clang_based_tests_with {
2712 cmd.env("CLANG", clang);
2715 if let Some(ref filecheck) = self.config.llvm_filecheck {
2716 cmd.env("LLVM_FILECHECK", filecheck);
2719 if let Some(ref llvm_bin_dir) = self.config.llvm_bin_dir {
2720 cmd.env("LLVM_BIN_DIR", llvm_bin_dir);
2723 // We don't want RUSTFLAGS set from the outside to interfere with
2724 // compiler flags set in the test cases:
2725 cmd.env_remove("RUSTFLAGS");
2727 // Use dynamic musl for tests because static doesn't allow creating dylibs
2728 if self.config.host.contains("musl") {
2729 cmd.env("RUSTFLAGS", "-Ctarget-feature=-crt-static").env("IS_MUSL_HOST", "1");
2732 if self.config.target.contains("msvc") && self.config.cc != "" {
2733 // We need to pass a path to `lib.exe`, so assume that `cc` is `cl.exe`
2734 // and that `lib.exe` lives next to it.
2735 let lib = Path::new(&self.config.cc).parent().unwrap().join("lib.exe");
2737 // MSYS doesn't like passing flags of the form `/foo` as it thinks it's
2738 // a path and instead passes `C:\msys64\foo`, so convert all
2739 // `/`-arguments to MSVC here to `-` arguments.
2744 .map(|s| s.replace("/", "-"))
2745 .collect::<Vec<_>>()
2748 cmd.env("IS_MSVC", "1")
2749 .env("IS_WINDOWS", "1")
2750 .env("MSVC_LIB", format!("'{}' -nologo", lib.display()))
2751 .env("CC", format!("'{}' {}", self.config.cc, cflags))
2752 .env("CXX", format!("'{}'", &self.config.cxx));
2754 cmd.env("CC", format!("{} {}", self.config.cc, self.config.cflags))
2755 .env("CXX", format!("{} {}", self.config.cxx, self.config.cflags))
2756 .env("AR", &self.config.ar);
2758 if self.config.target.contains("windows") {
2759 cmd.env("IS_WINDOWS", "1");
2763 let output = cmd.spawn().and_then(read2_abbreviated).expect("failed to spawn `make`");
2764 if !output.status.success() {
2766 status: output.status,
2767 stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
2768 stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
2769 cmdline: format!("{:?}", cmd),
2771 self.fatal_proc_rec("make failed", &res);
2775 fn aggressive_rm_rf(&self, path: &Path) -> io::Result<()> {
2776 for e in path.read_dir()? {
2778 let path = entry.path();
2779 if entry.file_type()?.is_dir() {
2780 self.aggressive_rm_rf(&path)?;
2782 // Remove readonly files as well on windows (by default we can't)
2783 fs::remove_file(&path).or_else(|e| {
2784 if cfg!(windows) && e.kind() == io::ErrorKind::PermissionDenied {
2785 let mut meta = entry.metadata()?.permissions();
2786 meta.set_readonly(false);
2787 fs::set_permissions(&path, meta)?;
2788 fs::remove_file(&path)
2795 fs::remove_dir(path)
2798 fn run_js_doc_test(&self) {
2799 if let Some(nodejs) = &self.config.nodejs {
2800 let out_dir = self.output_base_dir();
2802 self.document(&out_dir);
2804 let root = self.config.find_rust_src_root().unwrap();
2805 let res = self.cmd2procres(
2806 Command::new(&nodejs)
2807 .arg(root.join("src/tools/rustdoc-js/tester.js"))
2808 .arg(out_dir.parent().expect("no parent"))
2809 .arg(self.testpaths.file.with_extension("js")),
2811 if !res.status.success() {
2812 self.fatal_proc_rec("rustdoc-js test failed!", &res);
2815 self.fatal("no nodeJS");
2819 fn load_compare_outputs(
2822 output_kind: TestOutput,
2823 explicit_format: bool,
2825 let (stderr_kind, stdout_kind) = match output_kind {
2826 TestOutput::Compile => (UI_STDERR, UI_STDOUT),
2827 TestOutput::Run => (UI_RUN_STDERR, UI_RUN_STDOUT),
2830 let expected_stderr = self.load_expected_output(stderr_kind);
2831 let expected_stdout = self.load_expected_output(stdout_kind);
2833 let normalized_stdout = match output_kind {
2834 TestOutput::Run if self.config.remote_test_client.is_some() => {
2835 // When tests are run using the remote-test-client, the string
2836 // 'uploaded "$TEST_BUILD_DIR/<test_executable>, waiting for result"'
2837 // is printed to stdout by the client and then captured in the ProcRes,
2838 // so it needs to be removed when comparing the run-pass test execution output
2840 static ref REMOTE_TEST_RE: Regex = Regex::new(
2841 "^uploaded \"\\$TEST_BUILD_DIR(/[[:alnum:]_\\-]+)+\", waiting for result\n"
2847 &self.normalize_output(&proc_res.stdout, &self.props.normalize_stdout),
2852 _ => self.normalize_output(&proc_res.stdout, &self.props.normalize_stdout),
2855 let stderr = if explicit_format {
2856 proc_res.stderr.clone()
2858 json::extract_rendered(&proc_res.stderr)
2861 let normalized_stderr = self.normalize_output(&stderr, &self.props.normalize_stderr);
2864 TestOutput::Compile => {
2865 if !self.props.dont_check_compiler_stdout {
2866 errors += self.compare_output("stdout", &normalized_stdout, &expected_stdout);
2868 if !self.props.dont_check_compiler_stderr {
2869 errors += self.compare_output("stderr", &normalized_stderr, &expected_stderr);
2872 TestOutput::Run => {
2873 errors += self.compare_output(stdout_kind, &normalized_stdout, &expected_stdout);
2874 errors += self.compare_output(stderr_kind, &normalized_stderr, &expected_stderr);
2880 fn run_ui_test(&self) {
2881 if let Some(FailMode::Build) = self.props.fail_mode {
2882 // Make sure a build-fail test cannot fail due to failing analysis (e.g. typeck).
2883 let pm = Some(PassMode::Check);
2884 let proc_res = self.compile_test_general(WillExecute::No, EmitMetadata::Yes, pm);
2885 self.check_if_test_should_compile(&proc_res, pm);
2888 let pm = self.pass_mode();
2889 let should_run = self.should_run(pm);
2890 let emit_metadata = self.should_emit_metadata(pm);
2891 let proc_res = self.compile_test(should_run, emit_metadata);
2892 self.check_if_test_should_compile(&proc_res, pm);
2894 // if the user specified a format in the ui test
2895 // print the output to the stderr file, otherwise extract
2896 // the rendered error messages from json and print them
2897 let explicit = self.props.compile_flags.iter().any(|s| s.contains("--error-format"));
2899 let expected_fixed = self.load_expected_output(UI_FIXED);
2901 let modes_to_prune = vec![CompareMode::Nll];
2902 self.prune_duplicate_outputs(&modes_to_prune);
2904 let mut errors = self.load_compare_outputs(&proc_res, TestOutput::Compile, explicit);
2906 if self.config.compare_mode.is_some() {
2907 // don't test rustfix with nll right now
2908 } else if self.config.rustfix_coverage {
2909 // Find out which tests have `MachineApplicable` suggestions but are missing
2910 // `run-rustfix` or `run-rustfix-only-machine-applicable` headers.
2912 // This will return an empty `Vec` in case the executed test file has a
2913 // `compile-flags: --error-format=xxxx` header with a value other than `json`.
2914 let suggestions = get_suggestions_from_json(
2917 Filter::MachineApplicableOnly,
2919 .unwrap_or_default();
2920 if suggestions.len() > 0
2921 && !self.props.run_rustfix
2922 && !self.props.rustfix_only_machine_applicable
2924 let mut coverage_file_path = self.config.build_base.clone();
2925 coverage_file_path.push("rustfix_missing_coverage.txt");
2926 debug!("coverage_file_path: {}", coverage_file_path.display());
2928 let mut file = OpenOptions::new()
2931 .open(coverage_file_path.as_path())
2932 .expect("could not create or open file");
2934 if let Err(_) = writeln!(file, "{}", self.testpaths.file.display()) {
2935 panic!("couldn't write to {}", coverage_file_path.display());
2938 } else if self.props.run_rustfix {
2939 // Apply suggestions from rustc to the code itself
2940 let unfixed_code = self.load_expected_output_from_path(&self.testpaths.file).unwrap();
2941 let suggestions = get_suggestions_from_json(
2944 if self.props.rustfix_only_machine_applicable {
2945 Filter::MachineApplicableOnly
2951 let fixed_code = apply_suggestions(&unfixed_code, &suggestions).expect(&format!(
2952 "failed to apply suggestions for {:?} with rustfix",
2956 errors += self.compare_output("fixed", &fixed_code, &expected_fixed);
2957 } else if !expected_fixed.is_empty() {
2959 "the `// run-rustfix` directive wasn't found but a `*.fixed` \
2965 println!("To update references, rerun the tests and pass the `--bless` flag");
2966 let relative_path_to_file =
2967 self.testpaths.relative_dir.join(self.testpaths.file.file_name().unwrap());
2969 "To only update this specific test, also pass `--test-args {}`",
2970 relative_path_to_file.display(),
2972 self.fatal_proc_rec(
2973 &format!("{} errors occurred comparing output.", errors),
2978 let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
2980 if let WillExecute::Yes = should_run {
2981 let proc_res = self.exec_compiled_test();
2982 let run_output_errors = if self.props.check_run_results {
2983 self.load_compare_outputs(&proc_res, TestOutput::Run, explicit)
2987 if run_output_errors > 0 {
2988 self.fatal_proc_rec(
2989 &format!("{} errors occurred comparing run output.", run_output_errors),
2993 if self.should_run_successfully(pm) {
2994 if !proc_res.status.success() {
2995 self.fatal_proc_rec("test run failed!", &proc_res);
2998 if proc_res.status.success() {
2999 self.fatal_proc_rec("test run succeeded!", &proc_res);
3002 if !self.props.error_patterns.is_empty() {
3003 // "// error-pattern" comments
3004 self.check_error_patterns(&proc_res.stderr, &proc_res, pm);
3009 "run_ui_test: explicit={:?} config.compare_mode={:?} expected_errors={:?} \
3010 proc_res.status={:?} props.error_patterns={:?}",
3012 self.config.compare_mode,
3015 self.props.error_patterns
3017 if !explicit && self.config.compare_mode.is_none() {
3018 let check_patterns =
3019 should_run == WillExecute::No && !self.props.error_patterns.is_empty();
3021 let check_annotations = !check_patterns || !expected_errors.is_empty();
3024 // "// error-pattern" comments
3025 self.check_error_patterns(&proc_res.stderr, &proc_res, pm);
3028 if check_annotations {
3029 // "//~ERROR comments"
3030 self.check_expected_errors(expected_errors, &proc_res);
3034 if self.props.run_rustfix && self.config.compare_mode.is_none() {
3035 // And finally, compile the fixed code and make sure it both
3036 // succeeds and has no diagnostics.
3037 let mut rustc = self.make_compile_args(
3038 &self.testpaths.file.with_extension(UI_FIXED),
3039 TargetLocation::ThisFile(self.make_exe_name()),
3043 rustc.arg("-L").arg(&self.aux_output_dir_name());
3044 let res = self.compose_and_run_compiler(rustc, None);
3045 if !res.status.success() {
3046 self.fatal_proc_rec("failed to compile fixed code", &res);
3048 if !res.stderr.is_empty() && !self.props.rustfix_only_machine_applicable {
3049 self.fatal_proc_rec("fixed code is still producing diagnostics", &res);
3054 fn run_mir_opt_test(&self) {
3055 let proc_res = self.compile_test(WillExecute::Yes, EmitMetadata::No);
3057 if !proc_res.status.success() {
3058 self.fatal_proc_rec("compilation failed!", &proc_res);
3061 let proc_res = self.exec_compiled_test();
3063 if !proc_res.status.success() {
3064 self.fatal_proc_rec("test run failed!", &proc_res);
3066 self.check_mir_dump();
3069 fn check_mir_dump(&self) {
3070 let test_file_contents = fs::read_to_string(&self.testpaths.file).unwrap();
3072 let mut test_dir = self.testpaths.file.with_extension("");
3074 if test_file_contents.lines().any(|l| l == "// EMIT_MIR_FOR_EACH_BIT_WIDTH") {
3075 test_dir.push(get_pointer_width(&self.config.target))
3078 if self.config.bless {
3079 let _ = std::fs::remove_dir_all(&test_dir);
3081 for l in test_file_contents.lines() {
3082 if l.starts_with("// EMIT_MIR ") {
3083 let test_name = l.trim_start_matches("// EMIT_MIR ");
3084 let expected_file = test_dir.join(test_name);
3086 let dumped_string = if test_name.ends_with(".diff") {
3087 let test_name = test_name.trim_end_matches(".diff");
3088 let before = format!("{}.before.mir", test_name);
3089 let after = format!("{}.after.mir", test_name);
3090 let before = self.get_mir_dump_dir().join(before);
3091 let after = self.get_mir_dump_dir().join(after);
3093 "comparing the contents of: {} with {}",
3097 let before = fs::read_to_string(before).unwrap();
3098 let after = fs::read_to_string(after).unwrap();
3099 let before = self.normalize_output(&before, &[]);
3100 let after = self.normalize_output(&after, &[]);
3101 let mut dumped_string = String::new();
3102 for result in diff::lines(&before, &after) {
3103 use std::fmt::Write;
3105 diff::Result::Left(s) => writeln!(dumped_string, "- {}", s).unwrap(),
3106 diff::Result::Right(s) => writeln!(dumped_string, "+ {}", s).unwrap(),
3107 diff::Result::Both(s, _) => writeln!(dumped_string, " {}", s).unwrap(),
3112 let mut output_file = PathBuf::new();
3113 output_file.push(self.get_mir_dump_dir());
3114 output_file.push(test_name);
3116 "comparing the contents of: {} with {}",
3117 output_file.display(),
3118 expected_file.display()
3120 if !output_file.exists() {
3122 "Output file `{}` from test does not exist, available files are in `{}`",
3123 output_file.display(),
3124 output_file.parent().unwrap().display()
3127 self.check_mir_test_timestamp(test_name, &output_file);
3128 let dumped_string = fs::read_to_string(&output_file).unwrap();
3129 self.normalize_output(&dumped_string, &[])
3131 if self.config.bless {
3132 let _ = std::fs::create_dir_all(&test_dir);
3133 let _ = std::fs::remove_file(&expected_file);
3134 std::fs::write(expected_file, dumped_string.as_bytes()).unwrap();
3136 if !expected_file.exists() {
3138 "Output file `{}` from test does not exist",
3139 expected_file.display()
3142 let expected_string = fs::read_to_string(&expected_file).unwrap();
3143 if dumped_string != expected_string {
3144 print_diff(&dumped_string, &expected_string, 3);
3146 "Actual MIR output differs from expected MIR output {}",
3147 expected_file.display()
3154 if let Some(idx) = test_file_contents.find("// END RUST SOURCE") {
3155 let (_, tests_text) = test_file_contents.split_at(idx + "// END_RUST SOURCE".len());
3156 let tests_text_str = String::from(tests_text);
3157 let mut curr_test: Option<&str> = None;
3158 let mut curr_test_contents = vec![ExpectedLine::Elision];
3159 for l in tests_text_str.lines() {
3160 debug!("line: {:?}", l);
3161 if l.starts_with("// START ") {
3162 let (_, t) = l.split_at("// START ".len());
3163 curr_test = Some(t);
3164 } else if l.starts_with("// END") {
3165 let (_, t) = l.split_at("// END ".len());
3166 if Some(t) != curr_test {
3167 panic!("mismatched START END test name");
3169 self.compare_mir_test_output(curr_test.unwrap(), &curr_test_contents);
3171 curr_test_contents.clear();
3172 curr_test_contents.push(ExpectedLine::Elision);
3173 } else if l.is_empty() {
3175 } else if l.starts_with("//") && l.split_at("//".len()).1.trim() == "..." {
3176 curr_test_contents.push(ExpectedLine::Elision)
3177 } else if l.starts_with("// ") {
3178 let (_, test_content) = l.split_at("// ".len());
3179 curr_test_contents.push(ExpectedLine::Text(test_content));
3185 fn check_mir_test_timestamp(&self, test_name: &str, output_file: &Path) {
3186 let t = |file| fs::metadata(file).unwrap().modified().unwrap();
3187 let source_file = &self.testpaths.file;
3188 let output_time = t(output_file);
3189 let source_time = t(source_file);
3190 if source_time > output_time {
3191 debug!("source file time: {:?} output file time: {:?}", source_time, output_time);
3193 "test source file `{}` is newer than potentially stale output file `{}`.",
3194 source_file.display(),
3200 fn compare_mir_test_output(&self, test_name: &str, expected_content: &[ExpectedLine<&str>]) {
3201 let mut output_file = PathBuf::new();
3202 output_file.push(self.get_mir_dump_dir());
3203 output_file.push(test_name);
3204 debug!("comparing the contents of: {:?}", output_file);
3205 debug!("with: {:?}", expected_content);
3206 if !output_file.exists() {
3207 panic!("Output file `{}` from test does not exist", output_file.display());
3209 self.check_mir_test_timestamp(test_name, &output_file);
3211 let dumped_string = fs::read_to_string(&output_file).unwrap();
3212 let mut dumped_lines =
3213 dumped_string.lines().map(|l| nocomment_mir_line(l)).filter(|l| !l.is_empty());
3214 let mut expected_lines = expected_content
3216 .filter(|&l| if let &ExpectedLine::Text(l) = l { !l.is_empty() } else { true })
3219 let compare = |expected_line, dumped_line| {
3220 let e_norm = normalize_mir_line(expected_line);
3221 let d_norm = normalize_mir_line(dumped_line);
3222 debug!("found: {:?}", d_norm);
3223 debug!("expected: {:?}", e_norm);
3227 let error = |expected_line, extra_msg| {
3228 let normalize_all = dumped_string
3230 .map(nocomment_mir_line)
3231 .filter(|l| !l.is_empty())
3232 .collect::<Vec<_>>()
3234 let f = |l: &ExpectedLine<_>| match l {
3235 &ExpectedLine::Elision => "... (elided)".into(),
3236 &ExpectedLine::Text(t) => t,
3238 let expected_content =
3239 expected_content.iter().map(|l| f(l)).collect::<Vec<_>>().join("\n");
3241 "Did not find expected line, error: {}\n\
3242 Expected Line: {:?}\n\
3246 extra_msg, expected_line, test_name, expected_content, normalize_all
3250 // We expect each non-empty line to appear consecutively, non-consecutive lines
3251 // must be separated by at least one Elision
3252 let mut start_block_line = None;
3253 while let Some(dumped_line) = dumped_lines.next() {
3254 match expected_lines.next() {
3255 Some(&ExpectedLine::Text(expected_line)) => {
3256 let normalized_expected_line = normalize_mir_line(expected_line);
3257 if normalized_expected_line.contains(":{") {
3258 start_block_line = Some(expected_line);
3261 if !compare(expected_line, dumped_line) {
3262 error!("{:?}", start_block_line);
3266 "Mismatch in lines\n\
3267 Current block: {}\n\
3269 start_block_line.unwrap_or("None"),
3275 Some(&ExpectedLine::Elision) => {
3276 // skip any number of elisions in a row.
3277 while let Some(&&ExpectedLine::Elision) = expected_lines.peek() {
3278 expected_lines.next();
3280 if let Some(&ExpectedLine::Text(expected_line)) = expected_lines.next() {
3281 let mut found = compare(expected_line, dumped_line);
3285 while let Some(dumped_line) = dumped_lines.next() {
3286 found = compare(expected_line, dumped_line);
3292 error(expected_line, "ran out of mir dump to match against".into());
3301 fn get_mir_dump_dir(&self) -> PathBuf {
3302 let mut mir_dump_dir = PathBuf::from(self.config.build_base.as_path());
3303 debug!("input_file: {:?}", self.testpaths.file);
3304 mir_dump_dir.push(&self.testpaths.relative_dir);
3305 mir_dump_dir.push(self.testpaths.file.file_stem().unwrap());
3309 fn normalize_output(&self, output: &str, custom_rules: &[(String, String)]) -> String {
3310 let cflags = self.props.compile_flags.join(" ");
3311 let json = cflags.contains("--error-format json")
3312 || cflags.contains("--error-format pretty-json")
3313 || cflags.contains("--error-format=json")
3314 || cflags.contains("--error-format=pretty-json")
3315 || cflags.contains("--output-format json")
3316 || cflags.contains("--output-format=json");
3318 let mut normalized = output.to_string();
3320 let mut normalize_path = |from: &Path, to: &str| {
3321 let mut from = from.display().to_string();
3323 from = from.replace("\\", "\\\\");
3325 normalized = normalized.replace(&from, to);
3328 let parent_dir = self.testpaths.file.parent().unwrap();
3329 normalize_path(parent_dir, "$DIR");
3331 // Paths into the libstd/libcore
3332 let src_dir = self.config.src_base.parent().unwrap().parent().unwrap();
3333 normalize_path(src_dir, "$SRC_DIR");
3335 // Paths into the build directory
3336 let test_build_dir = &self.config.build_base;
3337 let parent_build_dir = test_build_dir.parent().unwrap().parent().unwrap().parent().unwrap();
3339 // eg. /home/user/rust/build/x86_64-unknown-linux-gnu/test/ui
3340 normalize_path(test_build_dir, "$TEST_BUILD_DIR");
3341 // eg. /home/user/rust/build
3342 normalize_path(parent_build_dir, "$BUILD_DIR");
3344 // Paths into lib directory.
3345 normalize_path(&parent_build_dir.parent().unwrap().join("lib"), "$LIB_DIR");
3348 // escaped newlines in json strings should be readable
3349 // in the stderr files. There's no point int being correct,
3350 // since only humans process the stderr files.
3351 // Thus we just turn escaped newlines back into newlines.
3352 normalized = normalized.replace("\\n", "\n");
3355 // If there are `$SRC_DIR` normalizations with line and column numbers, then replace them
3356 // with placeholders as we do not want tests needing updated when compiler source code
3358 // eg. $SRC_DIR/libcore/mem.rs:323:14 becomes $SRC_DIR/libcore/mem.rs:LL:COL
3359 normalized = Regex::new("SRC_DIR(.+):\\d+:\\d+")
3361 .replace_all(&normalized, "SRC_DIR$1:LL:COL")
3364 normalized = Self::normalize_platform_differences(&normalized);
3365 normalized = normalized.replace("\t", "\\t"); // makes tabs visible
3367 // Remove test annotations like `//~ ERROR text` from the output,
3368 // since they duplicate actual errors and make the output hard to read.
3370 Regex::new("\\s*//(\\[.*\\])?~.*").unwrap().replace_all(&normalized, "").into_owned();
3372 for rule in custom_rules {
3373 let re = Regex::new(&rule.0).expect("bad regex in custom normalization rule");
3374 normalized = re.replace_all(&normalized, &rule.1[..]).into_owned();
3379 /// Normalize output differences across platforms. Generally changes Windows output to be more
3382 /// Replaces backslashes in paths with forward slashes, and replaces CRLF line endings
3384 fn normalize_platform_differences(output: &str) -> String {
3386 /// Used to find Windows paths.
3388 /// It's not possible to detect paths in the error messages generally, but this is a
3389 /// decent enough heuristic.
3390 static ref PATH_BACKSLASH_RE: Regex = Regex::new(r#"(?x)
3392 # Match paths that don't include spaces.
3393 (?:\\[\pL\pN\.\-_']+)+\.\pL+
3395 # If the path starts with a well-known root, then allow spaces.
3396 \$(?:DIR|SRC_DIR|TEST_BUILD_DIR|BUILD_DIR|LIB_DIR)(?:\\[\pL\pN\.\-_' ]+)+
3401 let output = output.replace(r"\\", r"\");
3404 .replace_all(&output, |caps: &Captures<'_>| {
3405 println!("{}", &caps[0]);
3406 caps[0].replace(r"\", "/")
3408 .replace("\r\n", "\n")
3411 fn expected_output_path(&self, kind: &str) -> PathBuf {
3413 expected_output_path(&self.testpaths, self.revision, &self.config.compare_mode, kind);
3416 if let Some(CompareMode::Polonius) = self.config.compare_mode {
3417 path = expected_output_path(
3420 &Some(CompareMode::Nll),
3427 path = expected_output_path(&self.testpaths, self.revision, &None, kind);
3433 fn load_expected_output(&self, kind: &str) -> String {
3434 let path = self.expected_output_path(kind);
3436 match self.load_expected_output_from_path(&path) {
3438 Err(x) => self.fatal(&x),
3445 fn load_expected_output_from_path(&self, path: &Path) -> Result<String, String> {
3446 fs::read_to_string(path).map_err(|err| {
3447 format!("failed to load expected output from `{}`: {}", path.display(), err)
3451 fn delete_file(&self, file: &PathBuf) {
3452 if let Err(e) = fs::remove_file(file) {
3453 self.fatal(&format!("failed to delete `{}`: {}", file.display(), e,));
3457 fn compare_output(&self, kind: &str, actual: &str, expected: &str) -> usize {
3458 if actual == expected {
3462 if !self.config.bless {
3463 if expected.is_empty() {
3464 println!("normalized {}:\n{}\n", kind, actual);
3466 println!("diff of {}:\n", kind);
3467 print_diff(expected, actual, 3);
3471 let mode = self.config.compare_mode.as_ref().map_or("", |m| m.to_str());
3472 let output_file = self
3474 .with_extra_extension(self.revision.unwrap_or(""))
3475 .with_extra_extension(mode)
3476 .with_extra_extension(kind);
3478 let mut files = vec![output_file];
3479 if self.config.bless {
3480 files.push(expected_output_path(
3483 &self.config.compare_mode,
3488 for output_file in &files {
3489 if actual.is_empty() {
3490 self.delete_file(output_file);
3491 } else if let Err(err) = fs::write(&output_file, &actual) {
3492 self.fatal(&format!(
3493 "failed to write {} to `{}`: {}",
3495 output_file.display(),
3501 println!("\nThe actual {0} differed from the expected {0}.", kind);
3502 for output_file in files {
3503 println!("Actual {} saved to {}", kind, output_file.display());
3505 if self.config.bless { 0 } else { 1 }
3508 fn prune_duplicate_output(&self, mode: CompareMode, kind: &str, canon_content: &str) {
3509 let examined_path = expected_output_path(&self.testpaths, self.revision, &Some(mode), kind);
3511 let examined_content =
3512 self.load_expected_output_from_path(&examined_path).unwrap_or_else(|_| String::new());
3514 if examined_path.exists() && canon_content == &examined_content {
3515 self.delete_file(&examined_path);
3519 fn prune_duplicate_outputs(&self, modes: &[CompareMode]) {
3520 if self.config.bless {
3521 for kind in UI_EXTENSIONS {
3522 let canon_comparison_path =
3523 expected_output_path(&self.testpaths, self.revision, &None, kind);
3525 if let Ok(canon) = self.load_expected_output_from_path(&canon_comparison_path) {
3527 self.prune_duplicate_output(mode.clone(), kind, &canon);
3534 fn create_stamp(&self) {
3535 let stamp = crate::stamp(&self.config, self.testpaths, self.revision);
3536 fs::write(&stamp, compute_stamp_hash(&self.config)).unwrap();
3545 pub struct ProcRes {
3553 pub fn fatal(&self, err: Option<&str>) -> ! {
3554 if let Some(e) = err {
3555 println!("\nerror: {}", e);
3562 ------------------------------------------\n\
3564 ------------------------------------------\n\
3566 ------------------------------------------\n\
3568 ------------------------------------------\n\
3572 json::extract_rendered(&self.stdout),
3573 json::extract_rendered(&self.stderr),
3575 // Use resume_unwind instead of panic!() to prevent a panic message + backtrace from
3576 // compiletest, which is unnecessary noise.
3577 std::panic::resume_unwind(Box::new(()));
3581 enum TargetLocation {
3583 ThisDirectory(PathBuf),
3586 #[derive(Clone, PartialEq, Eq)]
3587 enum ExpectedLine<T: AsRef<str>> {
3597 impl<T> fmt::Debug for ExpectedLine<T>
3599 T: AsRef<str> + fmt::Debug,
3601 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3602 if let &ExpectedLine::Text(ref t) = self {
3603 write!(formatter, "{:?}", t)
3605 write!(formatter, "\"...\" (Elision)")
3610 fn normalize_mir_line(line: &str) -> String {
3611 nocomment_mir_line(line).replace(char::is_whitespace, "")
3614 fn nocomment_mir_line(line: &str) -> &str {
3615 if let Some(idx) = line.find("//") {
3616 let (l, _) = line.split_at(idx);
3623 fn read2_abbreviated(mut child: Child) -> io::Result<Output> {
3624 use crate::read2::read2;
3625 use std::mem::replace;
3627 const HEAD_LEN: usize = 160 * 1024;
3628 const TAIL_LEN: usize = 256 * 1024;
3632 Abbreviated { head: Vec<u8>, skipped: usize, tail: Box<[u8]> },
3636 fn extend(&mut self, data: &[u8]) {
3637 let new_self = match *self {
3638 ProcOutput::Full(ref mut bytes) => {
3639 bytes.extend_from_slice(data);
3640 let new_len = bytes.len();
3641 if new_len <= HEAD_LEN + TAIL_LEN {
3644 let tail = bytes.split_off(new_len - TAIL_LEN).into_boxed_slice();
3645 let head = replace(bytes, Vec::new());
3646 let skipped = new_len - HEAD_LEN - TAIL_LEN;
3647 ProcOutput::Abbreviated { head, skipped, tail }
3649 ProcOutput::Abbreviated { ref mut skipped, ref mut tail, .. } => {
3650 *skipped += data.len();
3651 if data.len() <= TAIL_LEN {
3652 tail[..data.len()].copy_from_slice(data);
3653 tail.rotate_left(data.len());
3655 tail.copy_from_slice(&data[(data.len() - TAIL_LEN)..]);
3663 fn into_bytes(self) -> Vec<u8> {
3665 ProcOutput::Full(bytes) => bytes,
3666 ProcOutput::Abbreviated { mut head, skipped, tail } => {
3667 write!(&mut head, "\n\n<<<<<< SKIPPED {} BYTES >>>>>>\n\n", skipped).unwrap();
3668 head.extend_from_slice(&tail);
3675 let mut stdout = ProcOutput::Full(Vec::new());
3676 let mut stderr = ProcOutput::Full(Vec::new());
3678 drop(child.stdin.take());
3680 child.stdout.take().unwrap(),
3681 child.stderr.take().unwrap(),
3682 &mut |is_stdout, data, _| {
3683 if is_stdout { &mut stdout } else { &mut stderr }.extend(data);
3687 let status = child.wait()?;
3689 Ok(Output { status, stdout: stdout.into_bytes(), stderr: stderr.into_bytes() })