1 // ignore-tidy-filelength
3 use crate::common
::{CompareMode, PassMode}
;
4 use crate::common
::{expected_output_path, UI_EXTENSIONS, UI_FIXED, UI_STDERR, UI_STDOUT}
;
5 use crate::common
::{UI_RUN_STDERR, UI_RUN_STDOUT}
;
6 use crate::common
::{output_base_dir, output_base_name, output_testname_unique}
;
7 use crate::common
::{Codegen, CodegenUnits, Rustdoc}
;
8 use crate::common
::{DebugInfoCdb, DebugInfoGdbLldb, DebugInfoGdb, DebugInfoLldb}
;
9 use crate::common
::{CompileFail, Pretty, RunFail, RunPassValgrind}
;
10 use crate::common
::{Config, TestPaths}
;
11 use crate::common
::{Incremental, MirOpt, RunMake, Ui, JsDocTest, Assembly}
;
13 use crate::errors
::{self, Error, ErrorKind}
;
14 use crate::header
::TestProps
;
16 use regex
::{Captures, Regex}
;
17 use rustfix
::{apply_suggestions, get_suggestions_from_json, Filter}
;
18 use crate::util
::{logv, PathBufExt}
;
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 const SEM_NOGPFAULTERRORBOX
: u32 = 0x0002;
47 fn SetErrorMode(mode
: u32) -> u32;
51 static ref LOCK
: Mutex
<()> = { Mutex::new(()) }
;
53 // Error mode is a global variable, so lock it so only one thread will change it
54 let _lock
= LOCK
.lock().unwrap();
56 // Tell Windows to not show any UI on errors (such as terminating abnormally).
57 // This is important for running tests, since some of them use abnormal
58 // termination by design. This mode is inherited by all child processes.
60 let old_mode
= SetErrorMode(SEM_NOGPFAULTERRORBOX
); // read inherited flags
61 SetErrorMode(old_mode
| SEM_NOGPFAULTERRORBOX
);
63 SetErrorMode(old_mode
);
69 fn disable_error_reporting
<F
: FnOnce() -> R
, R
>(f
: F
) -> R
{
73 /// The name of the environment variable that holds dynamic library locations.
74 pub fn dylib_env_var() -> &'
static str {
77 } else if cfg
!(target_os
= "macos") {
79 } else if cfg
!(target_os
= "haiku") {
86 /// The platform-specific library name
87 pub fn get_lib_name(lib
: &str, dylib
: bool
) -> String
{
88 // In some casess (e.g. MUSL), we build a static
89 // library, rather than a dynamic library.
90 // In this case, the only path we can pass
91 // with '--extern-meta' is the '.lib' file
93 return format
!("lib{}.rlib", lib
);
97 format
!("{}.dll", lib
)
98 } else if cfg
!(target_os
= "macos") {
99 format
!("lib{}.dylib", lib
)
101 format
!("lib{}.so", lib
)
105 #[derive(Debug, PartialEq)]
112 #[derive(Debug, PartialEq)]
113 pub struct Mismatch
{
114 pub line_number
: u32,
115 pub lines
: Vec
<DiffLine
>,
119 fn new(line_number
: u32) -> Mismatch
{
121 line_number
: line_number
,
127 // Produces a diff between the expected output and actual output.
128 pub fn make_diff(expected
: &str, actual
: &str, context_size
: usize) -> Vec
<Mismatch
> {
129 let mut line_number
= 1;
130 let mut context_queue
: VecDeque
<&str> = VecDeque
::with_capacity(context_size
);
131 let mut lines_since_mismatch
= context_size
+ 1;
132 let mut results
= Vec
::new();
133 let mut mismatch
= Mismatch
::new(0);
135 for result
in diff
::lines(expected
, actual
) {
137 diff
::Result
::Left(str) => {
138 if lines_since_mismatch
>= context_size
&& lines_since_mismatch
> 0 {
139 results
.push(mismatch
);
140 mismatch
= Mismatch
::new(line_number
- context_queue
.len() as u32);
143 while let Some(line
) = context_queue
.pop_front() {
144 mismatch
.lines
.push(DiffLine
::Context(line
.to_owned()));
147 mismatch
.lines
.push(DiffLine
::Expected(str.to_owned()));
149 lines_since_mismatch
= 0;
151 diff
::Result
::Right(str) => {
152 if lines_since_mismatch
>= context_size
&& lines_since_mismatch
> 0 {
153 results
.push(mismatch
);
154 mismatch
= Mismatch
::new(line_number
- context_queue
.len() as u32);
157 while let Some(line
) = context_queue
.pop_front() {
158 mismatch
.lines
.push(DiffLine
::Context(line
.to_owned()));
161 mismatch
.lines
.push(DiffLine
::Resulting(str.to_owned()));
162 lines_since_mismatch
= 0;
164 diff
::Result
::Both(str, _
) => {
165 if context_queue
.len() >= context_size
{
166 let _
= context_queue
.pop_front();
169 if lines_since_mismatch
< context_size
{
170 mismatch
.lines
.push(DiffLine
::Context(str.to_owned()));
171 } else if context_size
> 0 {
172 context_queue
.push_back(str);
176 lines_since_mismatch
+= 1;
181 results
.push(mismatch
);
187 pub fn run(config
: Config
, testpaths
: &TestPaths
, revision
: Option
<&str>) {
188 match &*config
.target
{
189 "arm-linux-androideabi"
190 | "armv7-linux-androideabi"
191 | "thumbv7neon-linux-androideabi"
192 | "aarch64-linux-android" => {
193 if !config
.adb_device_status
{
194 panic
!("android device not available");
199 // android has its own gdb handling
200 if config
.mode
== DebugInfoGdb
&& config
.gdb
.is_none() {
201 panic
!("gdb not available but debuginfo gdb debuginfo test requested");
207 // We're going to be dumping a lot of info. Start on a new line.
210 debug
!("running {:?}", testpaths
.file
.display());
211 let props
= TestProps
::from_file(&testpaths
.file
, revision
, &config
);
219 create_dir_all(&cx
.output_base_dir()).unwrap();
221 if config
.mode
== Incremental
{
222 // Incremental tests are special because they cannot be run in
225 !props
.revisions
.is_empty(),
226 "Incremental tests require revisions."
228 cx
.init_incremental_test();
229 for revision
in &props
.revisions
{
230 let revision_props
= TestProps
::from_file(&testpaths
.file
, Some(revision
), &config
);
231 let rev_cx
= TestCx
{
233 props
: &revision_props
,
235 revision
: Some(revision
),
237 rev_cx
.run_revision();
246 pub fn compute_stamp_hash(config
: &Config
) -> String
{
247 let mut hash
= DefaultHasher
::new();
248 config
.stage_id
.hash(&mut hash
);
250 if config
.mode
== DebugInfoCdb
{
251 config
.cdb
.hash(&mut hash
);
254 if config
.mode
== DebugInfoGdb
|| config
.mode
== DebugInfoGdbLldb
{
256 None
=> env
::var_os("PATH").hash(&mut hash
),
257 Some(ref s
) if s
.is_empty() => env
::var_os("PATH").hash(&mut hash
),
258 Some(ref s
) => s
.hash(&mut hash
),
262 if config
.mode
== DebugInfoLldb
|| config
.mode
== DebugInfoGdbLldb
{
263 env
::var_os("PATH").hash(&mut hash
);
264 env
::var_os("PYTHONPATH").hash(&mut hash
);
267 if let Ui
| Incremental
| Pretty
= config
.mode
{
268 config
.force_pass_mode
.hash(&mut hash
);
271 format
!("{:x}", hash
.finish())
274 struct TestCx
<'test
> {
275 config
: &'test Config
,
276 props
: &'test TestProps
,
277 testpaths
: &'test TestPaths
,
278 revision
: Option
<&'test
str>,
281 struct DebuggerCommands
{
282 commands
: Vec
<String
>,
283 check_lines
: Vec
<String
>,
284 breakpoint_lines
: Vec
<usize>,
297 impl<'test
> TestCx
<'test
> {
298 /// Code executed for each revision in turn (or, if there are no
299 /// revisions, exactly once, with revision == None).
300 fn run_revision(&self) {
301 match self.config
.mode
{
302 CompileFail
=> self.run_cfail_test(),
303 RunFail
=> self.run_rfail_test(),
304 RunPassValgrind
=> self.run_valgrind_test(),
305 Pretty
=> self.run_pretty_test(),
306 DebugInfoGdbLldb
=> {
307 self.run_debuginfo_gdb_test();
308 self.run_debuginfo_lldb_test();
310 DebugInfoCdb
=> self.run_debuginfo_cdb_test(),
311 DebugInfoGdb
=> self.run_debuginfo_gdb_test(),
312 DebugInfoLldb
=> self.run_debuginfo_lldb_test(),
313 Codegen
=> self.run_codegen_test(),
314 Rustdoc
=> self.run_rustdoc_test(),
315 CodegenUnits
=> self.run_codegen_units_test(),
316 Incremental
=> self.run_incremental_test(),
317 RunMake
=> self.run_rmake_test(),
318 Ui
=> self.run_ui_test(),
319 MirOpt
=> self.run_mir_opt_test(),
320 Assembly
=> self.run_assembly_test(),
321 JsDocTest
=> self.run_js_doc_test(),
325 fn pass_mode(&self) -> Option
<PassMode
> {
326 self.props
.pass_mode(self.config
)
329 fn should_run(&self) -> bool
{
330 let pass_mode
= self.pass_mode();
331 match self.config
.mode
{
332 Ui
=> pass_mode
== Some(PassMode
::Run
) || pass_mode
== Some(PassMode
::RunFail
),
333 mode
=> panic
!("unimplemented for mode {:?}", mode
),
337 fn should_run_successfully(&self) -> bool
{
338 let pass_mode
= self.pass_mode();
339 match self.config
.mode
{
340 Ui
=> pass_mode
== Some(PassMode
::Run
),
341 mode
=> panic
!("unimplemented for mode {:?}", mode
),
345 fn should_compile_successfully(&self) -> bool
{
346 match self.config
.mode
{
347 CompileFail
=> false,
349 Ui
=> self.pass_mode().is_some(),
351 let revision
= self.revision
352 .expect("incremental tests require a list of revisions");
353 if revision
.starts_with("rpass") || revision
.starts_with("rfail") {
355 } else if revision
.starts_with("cfail") {
356 // FIXME: would be nice if incremental revs could start with "cpass"
357 self.pass_mode().is_some()
359 panic
!("revision name must begin with rpass, rfail, or cfail");
362 mode
=> panic
!("unimplemented for mode {:?}", mode
),
366 fn check_if_test_should_compile(&self, proc_res
: &ProcRes
) {
367 if self.should_compile_successfully() {
368 if !proc_res
.status
.success() {
369 self.fatal_proc_rec("test compilation failed although it shouldn't!", proc_res
);
372 if proc_res
.status
.success() {
374 &format
!("{} test compiled successfully!", self.config
.mode
)[..],
379 self.check_correct_failure_status(proc_res
);
383 fn run_cfail_test(&self) {
384 let proc_res
= self.compile_test();
385 self.check_if_test_should_compile(&proc_res
);
386 self.check_no_compiler_crash(&proc_res
);
388 let output_to_check
= self.get_output(&proc_res
);
389 let expected_errors
= errors
::load_errors(&self.testpaths
.file
, self.revision
);
390 if !expected_errors
.is_empty() {
391 if !self.props
.error_patterns
.is_empty() {
392 self.fatal("both error pattern and expected errors specified");
394 self.check_expected_errors(expected_errors
, &proc_res
);
396 self.check_error_patterns(&output_to_check
, &proc_res
);
399 self.check_forbid_output(&output_to_check
, &proc_res
);
402 fn run_rfail_test(&self) {
403 let proc_res
= self.compile_test();
405 if !proc_res
.status
.success() {
406 self.fatal_proc_rec("compilation failed!", &proc_res
);
409 let proc_res
= self.exec_compiled_test();
411 // The value our Makefile configures valgrind to return on failure
412 const VALGRIND_ERR
: i32 = 100;
413 if proc_res
.status
.code() == Some(VALGRIND_ERR
) {
414 self.fatal_proc_rec("run-fail test isn't valgrind-clean!", &proc_res
);
417 let output_to_check
= self.get_output(&proc_res
);
418 self.check_correct_failure_status(&proc_res
);
419 self.check_error_patterns(&output_to_check
, &proc_res
);
422 fn get_output(&self, proc_res
: &ProcRes
) -> String
{
423 if self.props
.check_stdout
{
424 format
!("{}{}", proc_res
.stdout
, proc_res
.stderr
)
426 proc_res
.stderr
.clone()
430 fn check_correct_failure_status(&self, proc_res
: &ProcRes
) {
431 let expected_status
= Some(self.props
.failure_status
);
432 let received_status
= proc_res
.status
.code();
434 if expected_status
!= received_status
{
437 "Error: expected failure status ({:?}) but received status {:?}.",
438 expected_status
, received_status
445 fn run_rpass_test(&self) {
446 let proc_res
= self.compile_test();
448 if !proc_res
.status
.success() {
449 self.fatal_proc_rec("compilation failed!", &proc_res
);
452 // FIXME(#41968): Move this check to tidy?
453 let expected_errors
= errors
::load_errors(&self.testpaths
.file
, self.revision
);
455 expected_errors
.is_empty(),
456 "run-pass tests with expected warnings should be moved to ui/"
459 let proc_res
= self.exec_compiled_test();
460 if !proc_res
.status
.success() {
461 self.fatal_proc_rec("test run failed!", &proc_res
);
465 fn run_valgrind_test(&self) {
466 assert
!(self.revision
.is_none(), "revisions not relevant here");
468 if self.config
.valgrind_path
.is_none() {
469 assert
!(!self.config
.force_valgrind
);
470 return self.run_rpass_test();
473 let mut proc_res
= self.compile_test();
475 if !proc_res
.status
.success() {
476 self.fatal_proc_rec("compilation failed!", &proc_res
);
479 let mut new_config
= self.config
.clone();
480 new_config
.runtool
= new_config
.valgrind_path
.clone();
481 let new_cx
= TestCx
{
485 proc_res
= new_cx
.exec_compiled_test();
487 if !proc_res
.status
.success() {
488 self.fatal_proc_rec("test run failed!", &proc_res
);
492 fn run_pretty_test(&self) {
493 if self.props
.pp_exact
.is_some() {
494 logv(self.config
, "testing for exact pretty-printing".to_owned());
498 "testing for converging pretty-printing".to_owned(),
502 let rounds
= match self.props
.pp_exact
{
507 let src
= fs
::read_to_string(&self.testpaths
.file
).unwrap();
508 let mut srcs
= vec
![src
];
511 while round
< rounds
{
515 "pretty-printing round {} revision {:?}",
519 let read_from
= if round
== 0 {
522 ReadFrom
::Stdin(srcs
[round
].to_owned())
525 let proc_res
= self.print_source(read_from
,
526 &self.props
.pretty_mode
);
527 if !proc_res
.status
.success() {
530 "pretty-printing failed in round {} revision {:?}",
537 let ProcRes { stdout, .. }
= proc_res
;
542 let mut expected
= match self.props
.pp_exact
{
544 let filepath
= self.testpaths
.file
.parent().unwrap().join(file
);
545 fs
::read_to_string(&filepath
).unwrap()
547 None
=> srcs
[srcs
.len() - 2].clone(),
549 let mut actual
= srcs
[srcs
.len() - 1].clone();
551 if self.props
.pp_exact
.is_some() {
552 // Now we have to care about line endings
553 let cr
= "\r".to_owned();
554 actual
= actual
.replace(&cr
, "").to_owned();
555 expected
= expected
.replace(&cr
, "").to_owned();
558 self.compare_source(&expected
, &actual
);
560 // If we're only making sure that the output matches then just stop here
561 if self.props
.pretty_compare_only
{
565 // Finally, let's make sure it actually appears to remain valid code
566 let proc_res
= self.typecheck_source(actual
);
567 if !proc_res
.status
.success() {
568 self.fatal_proc_rec("pretty-printed source does not typecheck", &proc_res
);
571 if !self.props
.pretty_expanded
{
575 // additionally, run `--pretty expanded` and try to build it.
576 let proc_res
= self.print_source(ReadFrom
::Path
, "expanded");
577 if !proc_res
.status
.success() {
578 self.fatal_proc_rec("pretty-printing (expanded) failed", &proc_res
);
582 stdout
: expanded_src
,
585 let proc_res
= self.typecheck_source(expanded_src
);
586 if !proc_res
.status
.success() {
588 "pretty-printed source (expanded) does not typecheck",
594 fn print_source(&self, read_from
: ReadFrom
, pretty_type
: &str) -> ProcRes
{
595 let aux_dir
= self.aux_output_dir_name();
596 let input
: &str = match read_from
{
597 ReadFrom
::Stdin(_
) => "-",
598 ReadFrom
::Path
=> self.testpaths
.file
.to_str().unwrap(),
601 let mut rustc
= Command
::new(&self.config
.rustc_path
);
604 .args(&["-Z", &format
!("unpretty={}", pretty_type
)])
605 .args(&["--target", &self.config
.target
])
608 .args(&self.props
.compile_flags
)
609 .envs(self.props
.exec_env
.clone());
610 self.maybe_add_external_args(&mut rustc
,
611 self.split_maybe_args(&self.config
.target_rustcflags
));
613 let src
= match read_from
{
614 ReadFrom
::Stdin(src
) => Some(src
),
615 ReadFrom
::Path
=> None
618 self.compose_and_run(
620 self.config
.compile_lib_path
.to_str().unwrap(),
621 Some(aux_dir
.to_str().unwrap()),
626 fn compare_source(&self, expected
: &str, actual
: &str) {
627 if expected
!= actual
{
629 "pretty-printed source does not match expected source\n\
631 ------------------------------------------\n\
633 ------------------------------------------\n\
635 ------------------------------------------\n\
637 ------------------------------------------\n\
644 fn set_revision_flags(&self, cmd
: &mut Command
) {
645 if let Some(revision
) = self.revision
{
646 // Normalize revisions to be lowercase and replace `-`s with `_`s.
647 // Otherwise the `--cfg` flag is not valid.
648 let normalized_revision
= revision
.to_lowercase().replace("-", "_");
649 cmd
.args(&["--cfg", &normalized_revision
]);
653 fn typecheck_source(&self, src
: String
) -> ProcRes
{
654 let mut rustc
= Command
::new(&self.config
.rustc_path
);
656 let out_dir
= self.output_base_name().with_extension("pretty-out");
657 let _
= fs
::remove_dir_all(&out_dir
);
658 create_dir_all(&out_dir
).unwrap();
660 let target
= if self.props
.force_host
{
666 let aux_dir
= self.aux_output_dir_name();
673 .arg(&format
!("--target={}", target
))
675 .arg(&self.config
.build_base
)
678 self.set_revision_flags(&mut rustc
);
679 self.maybe_add_external_args(&mut rustc
,
680 self.split_maybe_args(&self.config
.target_rustcflags
));
681 rustc
.args(&self.props
.compile_flags
);
683 self.compose_and_run_compiler(rustc
, Some(src
))
686 fn run_debuginfo_cdb_test(&self) {
687 assert
!(self.revision
.is_none(), "revisions not relevant here");
689 let config
= Config
{
690 target_rustcflags
: self.cleanup_debug_info_options(&self.config
.target_rustcflags
),
691 host_rustcflags
: self.cleanup_debug_info_options(&self.config
.host_rustcflags
),
693 ..self.config
.clone()
696 let test_cx
= TestCx
{
701 test_cx
.run_debuginfo_cdb_test_no_opt();
704 fn run_debuginfo_cdb_test_no_opt(&self) {
705 // compile test file (it should have 'compile-flags:-g' in the header)
706 let compile_result
= self.compile_test();
707 if !compile_result
.status
.success() {
708 self.fatal_proc_rec("compilation failed!", &compile_result
);
711 let exe_file
= self.make_exe_name();
714 static PREFIXES
: &'
static [&'
static str] = &["cdb", "cdbg"];
715 // No "native rust support" variation for CDB yet.
719 // Parse debugger commands etc from test files
720 let DebuggerCommands
{
725 } = self.parse_debugger_commands(prefixes
);
727 // https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-commands
728 let mut script_str
= String
::with_capacity(2048);
729 script_str
.push_str("version\n"); // List CDB (and more) version info in test output
730 script_str
.push_str(".nvlist\n"); // List loaded `*.natvis` files, bulk of custom MSVC debug
732 // Set breakpoints on every line that contains the string "#break"
733 let source_file_name
= self.testpaths
.file
.file_name().unwrap().to_string_lossy();
734 for line
in &breakpoint_lines
{
735 script_str
.push_str(&format
!(
737 source_file_name
, line
741 // Append the other `cdb-command:`s
742 for line
in &commands
{
743 script_str
.push_str(line
);
744 script_str
.push_str("\n");
747 script_str
.push_str("\nqq\n"); // Quit the debugger (including remote debugger, if any)
749 // Write the script into a file
750 debug
!("script_str = {}", script_str
);
751 self.dump_output_file(&script_str
, "debugger.script");
752 let debugger_script
= self.make_out_name("debugger.script");
754 let cdb_path
= &self.config
.cdb
.as_ref().unwrap();
755 let mut cdb
= Command
::new(cdb_path
);
757 .arg("-lines") // Enable source line debugging.
758 .arg("-cf").arg(&debugger_script
)
761 let debugger_run_result
= self.compose_and_run(
763 self.config
.run_lib_path
.to_str().unwrap(),
768 if !debugger_run_result
.status
.success() {
769 self.fatal_proc_rec("Error while running CDB", &debugger_run_result
);
772 self.check_debugger_output(&debugger_run_result
, &check_lines
);
775 fn run_debuginfo_gdb_test(&self) {
776 assert
!(self.revision
.is_none(), "revisions not relevant here");
778 let config
= Config
{
779 target_rustcflags
: self.cleanup_debug_info_options(&self.config
.target_rustcflags
),
780 host_rustcflags
: self.cleanup_debug_info_options(&self.config
.host_rustcflags
),
782 ..self.config
.clone()
785 let test_cx
= TestCx
{
790 test_cx
.run_debuginfo_gdb_test_no_opt();
793 fn run_debuginfo_gdb_test_no_opt(&self) {
794 let prefixes
= if self.config
.gdb_native_rust
{
796 static PREFIXES
: &'
static [&'
static str] = &["gdb", "gdbr"];
797 println
!("NOTE: compiletest thinks it is using GDB with native rust support");
801 static PREFIXES
: &'
static [&'
static str] = &["gdb", "gdbg"];
802 println
!("NOTE: compiletest thinks it is using GDB without native rust support");
806 let DebuggerCommands
{
810 } = self.parse_debugger_commands(prefixes
);
811 let mut cmds
= commands
.join("\n");
813 // compile test file (it should have 'compile-flags:-g' in the header)
814 let compiler_run_result
= self.compile_test();
815 if !compiler_run_result
.status
.success() {
816 self.fatal_proc_rec("compilation failed!", &compiler_run_result
);
819 let exe_file
= self.make_exe_name();
821 let debugger_run_result
;
822 if is_android_gdb_target(&self.config
.target
) {
823 cmds
= cmds
.replace("run", "continue");
825 let tool_path
= match self.config
.android_cross_path
.to_str() {
826 Some(x
) => x
.to_owned(),
827 None
=> self.fatal("cannot find android cross path"),
830 // write debugger script
831 let mut script_str
= String
::with_capacity(2048);
832 script_str
.push_str(&format
!("set charset {}\n", Self::charset()));
833 script_str
.push_str(&format
!("set sysroot {}\n", tool_path
));
834 script_str
.push_str(&format
!("file {}\n", exe_file
.to_str().unwrap()));
835 script_str
.push_str("target remote :5039\n");
836 script_str
.push_str(&format
!(
837 "set solib-search-path \
838 ./{}/stage2/lib/rustlib/{}/lib/\n",
839 self.config
.host
, self.config
.target
841 for line
in &breakpoint_lines
{
845 self.testpaths
.file
.file_name().unwrap().to_string_lossy(),
850 script_str
.push_str(&cmds
);
851 script_str
.push_str("\nquit\n");
853 debug
!("script_str = {}", script_str
);
854 self.dump_output_file(&script_str
, "debugger.script");
856 let adb_path
= &self.config
.adb_path
;
858 Command
::new(adb_path
)
861 .arg(&self.config
.adb_test_dir
)
863 .expect(&format
!("failed to exec `{:?}`", adb_path
));
865 Command
::new(adb_path
)
866 .args(&["forward", "tcp:5039", "tcp:5039"])
868 .expect(&format
!("failed to exec `{:?}`", adb_path
));
870 let adb_arg
= format
!(
871 "export LD_LIBRARY_PATH={}; \
872 gdbserver{} :5039 {}/{}",
873 self.config
.adb_test_dir
.clone(),
874 if self.config
.target
.contains("aarch64") {
879 self.config
.adb_test_dir
.clone(),
880 exe_file
.file_name().unwrap().to_str().unwrap()
883 debug
!("adb arg: {}", adb_arg
);
884 let mut adb
= Command
::new(adb_path
)
885 .args(&["shell", &adb_arg
])
886 .stdout(Stdio
::piped())
887 .stderr(Stdio
::inherit())
889 .expect(&format
!("failed to exec `{:?}`", adb_path
));
891 // Wait for the gdbserver to print out "Listening on port ..."
892 // at which point we know that it's started and then we can
893 // execute the debugger below.
894 let mut stdout
= BufReader
::new(adb
.stdout
.take().unwrap());
895 let mut line
= String
::new();
898 stdout
.read_line(&mut line
).unwrap();
899 if line
.starts_with("Listening on port 5039") {
905 let mut debugger_script
= OsString
::from("-command=");
906 debugger_script
.push(self.make_out_name("debugger.script"));
907 let debugger_opts
: &[&OsStr
] = &[
914 let gdb_path
= self.config
.gdb
.as_ref().unwrap();
919 } = 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.");
941 let rust_src_root
= self
943 .find_rust_src_root()
944 .expect("Could not find Rust source root");
945 let rust_pp_module_rel_path
= Path
::new("./src/etc");
946 let rust_pp_module_abs_path
= rust_src_root
947 .join(rust_pp_module_rel_path
)
951 // write debugger script
952 let mut script_str
= String
::with_capacity(2048);
953 script_str
.push_str(&format
!("set charset {}\n", Self::charset()));
954 script_str
.push_str("show version\n");
956 match self.config
.gdb_version
{
959 "NOTE: compiletest thinks it is using GDB version {}",
963 if version
> extract_gdb_version("7.4").unwrap() {
964 // Add the directory containing the pretty printers to
965 // GDB's script auto loading safe path
966 script_str
.push_str(&format
!(
967 "add-auto-load-safe-path {}\n",
968 rust_pp_module_abs_path
.replace(r
"\", r
"\\")
974 "NOTE: compiletest does not know which version of \
980 // The following line actually doesn't have to do anything with
981 // pretty printing, it just tells GDB to print values on one line:
982 script_str
.push_str("set print pretty off\n");
984 // Add the pretty printer directory to GDB's source-file search path
985 script_str
.push_str(&format
!("directory {}\n", rust_pp_module_abs_path
));
987 // Load the target executable
988 script_str
.push_str(&format
!(
990 exe_file
.to_str().unwrap().replace(r
"\", r
"\\")
993 // Force GDB to print values in the Rust format.
994 if self.config
.gdb_native_rust
{
995 script_str
.push_str("set language rust\n");
998 // Add line breakpoints
999 for line
in &breakpoint_lines
{
1000 script_str
.push_str(&format
!(
1002 self.testpaths
.file
.file_name().unwrap().to_string_lossy(),
1007 script_str
.push_str(&cmds
);
1008 script_str
.push_str("\nquit\n");
1010 debug
!("script_str = {}", script_str
);
1011 self.dump_output_file(&script_str
, "debugger.script");
1013 let mut debugger_script
= OsString
::from("-command=");
1014 debugger_script
.push(self.make_out_name("debugger.script"));
1016 let debugger_opts
: &[&OsStr
] = &[
1023 let mut gdb
= Command
::new(self.config
.gdb
.as_ref().unwrap());
1024 gdb
.args(debugger_opts
)
1025 .env("PYTHONPATH", rust_pp_module_abs_path
);
1027 debugger_run_result
= self.compose_and_run(
1029 self.config
.run_lib_path
.to_str().unwrap(),
1035 if !debugger_run_result
.status
.success() {
1036 self.fatal_proc_rec("gdb failed to execute", &debugger_run_result
);
1039 self.check_debugger_output(&debugger_run_result
, &check_lines
);
1042 fn run_debuginfo_lldb_test(&self) {
1043 assert
!(self.revision
.is_none(), "revisions not relevant here");
1045 if self.config
.lldb_python_dir
.is_none() {
1046 self.fatal("Can't run LLDB test because LLDB's python path is not set.");
1049 let config
= Config
{
1050 target_rustcflags
: self.cleanup_debug_info_options(&self.config
.target_rustcflags
),
1051 host_rustcflags
: self.cleanup_debug_info_options(&self.config
.host_rustcflags
),
1052 mode
: DebugInfoLldb
,
1053 ..self.config
.clone()
1056 let test_cx
= TestCx
{
1061 test_cx
.run_debuginfo_lldb_test_no_opt();
1064 fn run_debuginfo_lldb_test_no_opt(&self) {
1065 // compile test file (it should have 'compile-flags:-g' in the header)
1066 let compile_result
= self.compile_test();
1067 if !compile_result
.status
.success() {
1068 self.fatal_proc_rec("compilation failed!", &compile_result
);
1071 let exe_file
= self.make_exe_name();
1073 match self.config
.lldb_version
{
1074 Some(ref version
) => {
1076 "NOTE: compiletest thinks it is using LLDB version {}",
1082 "NOTE: compiletest does not know which version of \
1088 let prefixes
= if self.config
.lldb_native_rust
{
1089 static PREFIXES
: &'
static [&'
static str] = &["lldb", "lldbr"];
1090 println
!("NOTE: compiletest thinks it is using LLDB with native rust support");
1093 static PREFIXES
: &'
static [&'
static str] = &["lldb", "lldbg"];
1094 println
!("NOTE: compiletest thinks it is using LLDB without native rust support");
1098 // Parse debugger commands etc from test files
1099 let DebuggerCommands
{
1104 } = self.parse_debugger_commands(prefixes
);
1106 // Write debugger script:
1107 // We don't want to hang when calling `quit` while the process is still running
1108 let mut script_str
= String
::from("settings set auto-confirm true\n");
1110 // Make LLDB emit its version, so we have it documented in the test output
1111 script_str
.push_str("version\n");
1113 // Switch LLDB into "Rust mode"
1114 let rust_src_root
= self
1116 .find_rust_src_root()
1117 .expect("Could not find Rust source root");
1118 let rust_pp_module_rel_path
= Path
::new("./src/etc/lldb_rust_formatters.py");
1119 let rust_pp_module_abs_path
= rust_src_root
1120 .join(rust_pp_module_rel_path
)
1126 .push_str(&format
!("command script import {}\n", &rust_pp_module_abs_path
[..])[..]);
1127 script_str
.push_str("type summary add --no-value ");
1128 script_str
.push_str("--python-function lldb_rust_formatters.print_val ");
1129 script_str
.push_str("-x \".*\" --category Rust\n");
1130 script_str
.push_str("type category enable Rust\n");
1132 // Set breakpoints on every line that contains the string "#break"
1133 let source_file_name
= self.testpaths
.file
.file_name().unwrap().to_string_lossy();
1134 for line
in &breakpoint_lines
{
1135 script_str
.push_str(&format
!(
1136 "breakpoint set --file '{}' --line {}\n",
1137 source_file_name
, line
1141 // Append the other commands
1142 for line
in &commands
{
1143 script_str
.push_str(line
);
1144 script_str
.push_str("\n");
1147 // Finally, quit the debugger
1148 script_str
.push_str("\nquit\n");
1150 // Write the script into a file
1151 debug
!("script_str = {}", script_str
);
1152 self.dump_output_file(&script_str
, "debugger.script");
1153 let debugger_script
= self.make_out_name("debugger.script");
1155 // Let LLDB execute the script via lldb_batchmode.py
1156 let debugger_run_result
= self.run_lldb(&exe_file
, &debugger_script
, &rust_src_root
);
1158 if !debugger_run_result
.status
.success() {
1159 self.fatal_proc_rec("Error while running LLDB", &debugger_run_result
);
1162 self.check_debugger_output(&debugger_run_result
, &check_lines
);
1167 test_executable
: &Path
,
1168 debugger_script
: &Path
,
1169 rust_src_root
: &Path
,
1171 // Prepare the lldb_batchmode which executes the debugger script
1172 let lldb_script_path
= rust_src_root
.join("src/etc/lldb_batchmode.py");
1174 Command
::new(&self.config
.lldb_python
)
1175 .arg(&lldb_script_path
)
1176 .arg(test_executable
)
1177 .arg(debugger_script
)
1178 .env("PYTHONPATH", self.config
.lldb_python_dir
.as_ref().unwrap()),
1182 fn cmd2procres(&self, cmd
: &mut Command
) -> ProcRes
{
1183 let (status
, out
, err
) = match cmd
.output() {
1190 String
::from_utf8(stdout
).unwrap(),
1191 String
::from_utf8(stderr
).unwrap(),
1193 Err(e
) => self.fatal(&format
!(
1194 "Failed to setup Python process for \
1200 self.dump_output(&out
, &err
);
1205 cmdline
: format
!("{:?}", cmd
),
1209 fn parse_debugger_commands(&self, debugger_prefixes
: &[&str]) -> DebuggerCommands
{
1210 let directives
= debugger_prefixes
1212 .map(|prefix
| (format
!("{}-command", prefix
), format
!("{}-check", prefix
)))
1213 .collect
::<Vec
<_
>>();
1215 let mut breakpoint_lines
= vec
![];
1216 let mut commands
= vec
![];
1217 let mut check_lines
= vec
![];
1218 let mut counter
= 1;
1219 let reader
= BufReader
::new(File
::open(&self.testpaths
.file
).unwrap());
1220 for line
in reader
.lines() {
1223 let line
= if line
.starts_with("//") {
1224 line
[2..].trim_start()
1229 if line
.contains("#break") {
1230 breakpoint_lines
.push(counter
);
1233 for &(ref command_directive
, ref check_directive
) in &directives
{
1235 .parse_name_value_directive(&line
, command_directive
)
1236 .map(|cmd
| commands
.push(cmd
));
1239 .parse_name_value_directive(&line
, check_directive
)
1240 .map(|cmd
| check_lines
.push(cmd
));
1243 Err(e
) => self.fatal(&format
!("Error while parsing debugger commands: {}", e
)),
1255 fn cleanup_debug_info_options(&self, options
: &Option
<String
>) -> Option
<String
> {
1256 if options
.is_none() {
1260 // Remove options that are either unwanted (-O) or may lead to duplicates due to RUSTFLAGS.
1261 let options_to_remove
= ["-O".to_owned(), "-g".to_owned(), "--debuginfo".to_owned()];
1262 let new_options
= self
1263 .split_maybe_args(options
)
1265 .filter(|x
| !options_to_remove
.contains(x
))
1266 .collect
::<Vec
<String
>>();
1268 Some(new_options
.join(" "))
1271 fn maybe_add_external_args(&self, cmd
: &mut Command
, args
: Vec
<String
>) {
1272 // Filter out the arguments that should not be added by runtest here.
1274 // Notable use-cases are: do not add our optimisation flag if
1275 // `compile-flags: -Copt-level=x` and similar for debug-info level as well.
1276 const OPT_FLAGS
: &[&str] = &["-O", "-Copt-level=", /*-C<space>*/"opt-level="];
1277 const DEBUG_FLAGS
: &[&str] = &["-g", "-Cdebuginfo=", /*-C<space>*/"debuginfo="];
1279 // FIXME: ideally we would "just" check the `cmd` itself, but it does not allow inspecting
1280 // its arguments. They need to be collected separately. For now I cannot be bothered to
1281 // implement this the "right" way.
1282 let have_opt_flag
= self.props
.compile_flags
.iter().any(|arg
| {
1283 OPT_FLAGS
.iter().any(|f
| arg
.starts_with(f
))
1285 let have_debug_flag
= self.props
.compile_flags
.iter().any(|arg
| {
1286 DEBUG_FLAGS
.iter().any(|f
| arg
.starts_with(f
))
1290 if OPT_FLAGS
.iter().any(|f
| arg
.starts_with(f
)) && have_opt_flag
{
1293 if DEBUG_FLAGS
.iter().any(|f
| arg
.starts_with(f
)) && have_debug_flag
{
1300 fn check_debugger_output(&self, debugger_run_result
: &ProcRes
, check_lines
: &[String
]) {
1301 let num_check_lines
= check_lines
.len();
1303 let mut check_line_index
= 0;
1304 for line
in debugger_run_result
.stdout
.lines() {
1305 if check_line_index
>= num_check_lines
{
1309 if check_single_line(line
, &(check_lines
[check_line_index
])[..]) {
1310 check_line_index
+= 1;
1313 if check_line_index
!= num_check_lines
&& num_check_lines
> 0 {
1314 self.fatal_proc_rec(
1316 "line not found in debugger output: {}",
1317 check_lines
[check_line_index
]
1319 debugger_run_result
,
1323 fn check_single_line(line
: &str, check_line
: &str) -> bool
{
1324 // Allow check lines to leave parts unspecified (e.g., uninitialized
1325 // bits in the wrong case of an enum) with the notation "[...]".
1326 let line
= line
.trim();
1327 let check_line
= check_line
.trim();
1328 let can_start_anywhere
= check_line
.starts_with("[...]");
1329 let can_end_anywhere
= check_line
.ends_with("[...]");
1331 let check_fragments
: Vec
<&str> = check_line
1333 .filter(|frag
| !frag
.is_empty())
1335 if check_fragments
.is_empty() {
1339 let (mut rest
, first_fragment
) = if can_start_anywhere
{
1340 match line
.find(check_fragments
[0]) {
1341 Some(pos
) => (&line
[pos
+ check_fragments
[0].len()..], 1),
1342 None
=> return false,
1348 for current_fragment
in &check_fragments
[first_fragment
..] {
1349 match rest
.find(current_fragment
) {
1351 rest
= &rest
[pos
+ current_fragment
.len()..];
1353 None
=> return false,
1357 if !can_end_anywhere
&& !rest
.is_empty() {
1365 fn check_error_patterns(&self, output_to_check
: &str, proc_res
: &ProcRes
) {
1366 debug
!("check_error_patterns");
1367 if self.props
.error_patterns
.is_empty() {
1368 if self.pass_mode().is_some() {
1371 self.fatal(&format
!(
1372 "no error pattern specified in {:?}",
1373 self.testpaths
.file
.display()
1378 let mut missing_patterns
: Vec
<String
> = Vec
::new();
1380 for pattern
in &self.props
.error_patterns
{
1381 if output_to_check
.contains(pattern
.trim()) {
1382 debug
!("found error pattern {}", pattern
);
1384 missing_patterns
.push(pattern
.to_string());
1388 if missing_patterns
.is_empty() {
1392 if missing_patterns
.len() == 1 {
1393 self.fatal_proc_rec(
1394 &format
!("error pattern '{}' not found!", missing_patterns
[0]),
1398 for pattern
in missing_patterns
{
1399 self.error(&format
!("error pattern '{}' not found!", pattern
));
1401 self.fatal_proc_rec("multiple error patterns not found", proc_res
);
1405 fn check_no_compiler_crash(&self, proc_res
: &ProcRes
) {
1406 match proc_res
.status
.code() {
1407 Some(101) => self.fatal_proc_rec("compiler encountered internal error", proc_res
),
1408 None
=> self.fatal_proc_rec("compiler terminated by signal", proc_res
),
1413 fn check_forbid_output(&self, output_to_check
: &str, proc_res
: &ProcRes
) {
1414 for pat
in &self.props
.forbid_output
{
1415 if output_to_check
.contains(pat
) {
1416 self.fatal_proc_rec("forbidden pattern found in compiler output", proc_res
);
1421 fn check_expected_errors(&self, expected_errors
: Vec
<errors
::Error
>, proc_res
: &ProcRes
) {
1422 debug
!("check_expected_errors: expected_errors={:?} proc_res.status={:?}",
1423 expected_errors
, proc_res
.status
);
1424 if proc_res
.status
.success()
1427 .any(|x
| x
.kind
== Some(ErrorKind
::Error
))
1429 self.fatal_proc_rec("process did not return an error status", proc_res
);
1432 // On Windows, keep all '\' path separators to match the paths reported in the JSON output
1433 // from the compiler
1434 let os_file_name
= self.testpaths
.file
.display().to_string();
1436 // on windows, translate all '\' path separators to '/'
1437 let file_name
= format
!("{}", self.testpaths
.file
.display()).replace(r
"\", "/");
1439 // If the testcase being checked contains at least one expected "help"
1440 // message, then we'll ensure that all "help" messages are expected.
1441 // Otherwise, all "help" messages reported by the compiler will be ignored.
1442 // This logic also applies to "note" messages.
1443 let expect_help
= expected_errors
1445 .any(|ee
| ee
.kind
== Some(ErrorKind
::Help
));
1446 let expect_note
= expected_errors
1448 .any(|ee
| ee
.kind
== Some(ErrorKind
::Note
));
1450 // Parse the JSON output from the compiler and extract out the messages.
1451 let actual_errors
= json
::parse_output(&os_file_name
, &proc_res
.stderr
, proc_res
);
1452 let mut unexpected
= Vec
::new();
1453 let mut found
= vec
![false; expected_errors
.len()];
1454 for actual_error
in &actual_errors
{
1455 let opt_index
= expected_errors
.iter().enumerate().position(
1456 |(index
, expected_error
)| {
1457 !found
[index
] && actual_error
.line_num
== expected_error
.line_num
1458 && (expected_error
.kind
.is_none()
1459 || actual_error
.kind
== expected_error
.kind
)
1460 && actual_error
.msg
.contains(&expected_error
.msg
)
1466 // found a match, everybody is happy
1467 assert
!(!found
[index
]);
1468 found
[index
] = true;
1472 if self.is_unexpected_compiler_message(actual_error
, expect_help
, expect_note
) {
1473 self.error(&format
!(
1474 "{}:{}: unexpected {}: '{}'",
1476 actual_error
.line_num
,
1480 .map_or(String
::from("message"), |k
| k
.to_string()),
1483 unexpected
.push(actual_error
);
1489 let mut not_found
= Vec
::new();
1490 // anything not yet found is a problem
1491 for (index
, expected_error
) in expected_errors
.iter().enumerate() {
1493 self.error(&format
!(
1494 "{}:{}: expected {} not found: {}",
1496 expected_error
.line_num
,
1500 .map_or("message".into(), |k
| k
.to_string()),
1503 not_found
.push(expected_error
);
1507 if !unexpected
.is_empty() || !not_found
.is_empty() {
1508 self.error(&format
!(
1509 "{} unexpected errors found, {} expected errors not found",
1513 println
!("status: {}\ncommand: {}", proc_res
.status
, proc_res
.cmdline
);
1514 if !unexpected
.is_empty() {
1515 println
!("unexpected errors (from JSON output): {:#?}\n", unexpected
);
1517 if !not_found
.is_empty() {
1518 println
!("not found errors (from test file): {:#?}\n", not_found
);
1524 /// Returns `true` if we should report an error about `actual_error`,
1525 /// which did not match any of the expected error. We always require
1526 /// errors/warnings to be explicitly listed, but only require
1527 /// helps/notes if there are explicit helps/notes given.
1528 fn is_unexpected_compiler_message(
1530 actual_error
: &Error
,
1534 match actual_error
.kind
{
1535 Some(ErrorKind
::Help
) => expect_help
,
1536 Some(ErrorKind
::Note
) => expect_note
,
1537 Some(ErrorKind
::Error
) | Some(ErrorKind
::Warning
) => true,
1538 Some(ErrorKind
::Suggestion
) | None
=> false,
1542 fn compile_test(&self) -> ProcRes
{
1543 // Only use `make_exe_name` when the test ends up being executed.
1544 let will_execute
= match self.config
.mode
{
1545 Ui
=> self.should_run(),
1546 Incremental
=> self.revision
.unwrap().starts_with("r"),
1547 RunFail
| RunPassValgrind
| MirOpt
|
1548 DebugInfoCdb
| DebugInfoGdbLldb
| DebugInfoGdb
| DebugInfoLldb
=> true,
1551 let output_file
= if will_execute
{
1552 TargetLocation
::ThisFile(self.make_exe_name())
1554 TargetLocation
::ThisDirectory(self.output_base_dir())
1557 let mut rustc
= self.make_compile_args(&self.testpaths
.file
, output_file
);
1559 rustc
.arg("-L").arg(&self.aux_output_dir_name());
1561 match self.config
.mode
{
1562 CompileFail
| Ui
=> {
1563 // compile-fail and ui tests tend to have tons of unused code as
1564 // it's just testing various pieces of the compile, but we don't
1565 // want to actually assert warnings about all this code. Instead
1566 // let's just ignore unused code warnings by defaults and tests
1567 // can turn it back on if needed.
1568 if !self.config
.src_base
.ends_with("rustdoc-ui") &&
1569 // Note that we don't call pass_mode() here as we don't want
1570 // to set unused to allow if we've overriden the pass mode
1571 // via command line flags.
1572 self.props
.local_pass_mode() != Some(PassMode
::Run
) {
1573 rustc
.args(&["-A", "unused"]);
1579 self.compose_and_run_compiler(rustc
, None
)
1582 fn document(&self, out_dir
: &Path
) -> ProcRes
{
1583 if self.props
.build_aux_docs
{
1584 for rel_ab
in &self.props
.aux_builds
{
1585 let aux_testpaths
= self.compute_aux_test_paths(rel_ab
);
1588 .from_aux_file(&aux_testpaths
.file
, self.revision
, self.config
);
1589 let aux_cx
= TestCx
{
1590 config
: self.config
,
1592 testpaths
: &aux_testpaths
,
1593 revision
: self.revision
,
1595 // Create the directory for the stdout/stderr files.
1596 create_dir_all(aux_cx
.output_base_dir()).unwrap();
1597 let auxres
= aux_cx
.document(out_dir
);
1598 if !auxres
.status
.success() {
1604 let aux_dir
= self.aux_output_dir_name();
1606 let rustdoc_path
= self
1610 .expect("--rustdoc-path passed");
1611 let mut rustdoc
= Command
::new(rustdoc_path
);
1615 .arg(self.config
.run_lib_path
.to_str().unwrap())
1620 .arg(&self.testpaths
.file
)
1621 .args(&self.props
.compile_flags
);
1623 if let Some(ref linker
) = self.config
.linker
{
1624 rustdoc
.arg(format
!("-Clinker={}", linker
));
1627 self.compose_and_run_compiler(rustdoc
, None
)
1630 fn exec_compiled_test(&self) -> ProcRes
{
1631 let env
= &self.props
.exec_env
;
1633 let proc_res
= match &*self.config
.target
{
1634 // This is pretty similar to below, we're transforming:
1636 // program arg1 arg2
1640 // remote-test-client run program:support-lib.so arg1 arg2
1642 // The test-client program will upload `program` to the emulator
1643 // along with all other support libraries listed (in this case
1644 // `support-lib.so`. It will then execute the program on the
1645 // emulator with the arguments specified (in the environment we give
1646 // the process) and then report back the same result.
1647 _
if self.config
.remote_test_client
.is_some() => {
1648 let aux_dir
= self.aux_output_dir_name();
1649 let ProcArgs { mut prog, args }
= self.make_run_args();
1650 if let Ok(entries
) = aux_dir
.read_dir() {
1651 for entry
in entries
{
1652 let entry
= entry
.unwrap();
1653 if !entry
.path().is_file() {
1657 prog
.push_str(entry
.path().to_str().unwrap());
1660 let mut test_client
=
1661 Command
::new(self.config
.remote_test_client
.as_ref().unwrap());
1663 .args(&["run", &prog
])
1666 self.compose_and_run(
1668 self.config
.run_lib_path
.to_str().unwrap(),
1669 Some(aux_dir
.to_str().unwrap()),
1673 _
if self.config
.target
.contains("vxworks") => {
1674 let aux_dir
= self.aux_output_dir_name();
1675 let ProcArgs { prog, args }
= self.make_run_args();
1676 let mut wr_run
= Command
::new("wr-run");
1677 wr_run
.args(&[&prog
]).args(args
).envs(env
.clone());
1678 self.compose_and_run(
1680 self.config
.run_lib_path
.to_str().unwrap(),
1681 Some(aux_dir
.to_str().unwrap()),
1686 let aux_dir
= self.aux_output_dir_name();
1687 let ProcArgs { prog, args }
= self.make_run_args();
1688 let mut program
= Command
::new(&prog
);
1691 .current_dir(&self.output_base_dir())
1693 self.compose_and_run(
1695 self.config
.run_lib_path
.to_str().unwrap(),
1696 Some(aux_dir
.to_str().unwrap()),
1702 if proc_res
.status
.success() {
1703 // delete the executable after running it to save space.
1704 // it is ok if the deletion failed.
1705 let _
= fs
::remove_file(self.make_exe_name());
1711 /// For each `aux-build: foo/bar` annotation, we check to find the
1712 /// file in a `auxiliary` directory relative to the test itself.
1713 fn compute_aux_test_paths(&self, rel_ab
: &str) -> TestPaths
{
1718 .expect("test file path has no parent")
1721 if !test_ab
.exists() {
1722 self.fatal(&format
!(
1723 "aux-build `{}` source not found",
1733 .join(self.output_testname_unique())
1737 .expect("aux-build path has no parent")
1742 fn is_vxworks_pure_static(&self) -> bool
{
1743 if self.config
.target
.contains("vxworks") {
1744 match env
::var("RUST_VXWORKS_TEST_DYLINK") {
1753 fn is_vxworks_pure_dynamic(&self) -> bool
{
1754 self.config
.target
.contains("vxworks") && !self.is_vxworks_pure_static()
1757 fn compose_and_run_compiler(&self, mut rustc
: Command
, input
: Option
<String
>) -> ProcRes
{
1758 let aux_dir
= self.aux_output_dir_name();
1760 if !self.props
.aux_builds
.is_empty() {
1761 let _
= fs
::remove_dir_all(&aux_dir
);
1762 create_dir_all(&aux_dir
).unwrap();
1765 // Use a Vec instead of a HashMap to preserve original order
1766 let mut extern_priv
= self.props
.extern_private
.clone();
1768 let mut add_extern_priv
= |priv_dep
: &str, dylib
: bool
| {
1769 let lib_name
= get_lib_name(priv_dep
, dylib
);
1771 .arg("--extern-private")
1772 .arg(format
!("{}={}", priv_dep
, aux_dir
.join(lib_name
).to_str().unwrap()));
1775 for rel_ab
in &self.props
.aux_builds
{
1776 let aux_testpaths
= self.compute_aux_test_paths(rel_ab
);
1779 .from_aux_file(&aux_testpaths
.file
, self.revision
, self.config
);
1780 let aux_output
= TargetLocation
::ThisDirectory(self.aux_output_dir_name());
1781 let aux_cx
= TestCx
{
1782 config
: self.config
,
1784 testpaths
: &aux_testpaths
,
1785 revision
: self.revision
,
1787 // Create the directory for the stdout/stderr files.
1788 create_dir_all(aux_cx
.output_base_dir()).unwrap();
1789 let mut aux_rustc
= aux_cx
.make_compile_args(&aux_testpaths
.file
, aux_output
);
1791 let (dylib
, crate_type
) = if aux_props
.no_prefer_dynamic
{
1793 } else if self.config
.target
.contains("cloudabi")
1794 || self.config
.target
.contains("emscripten")
1795 || (self.config
.target
.contains("musl")
1796 && !aux_props
.force_host
1797 && !self.config
.host
.contains("musl"))
1798 || self.config
.target
.contains("wasm32")
1799 || self.config
.target
.contains("nvptx")
1800 || self.is_vxworks_pure_static()
1802 // We primarily compile all auxiliary libraries as dynamic libraries
1803 // to avoid code size bloat and large binaries as much as possible
1804 // for the test suite (otherwise including libstd statically in all
1805 // executables takes up quite a bit of space).
1807 // For targets like MUSL or Emscripten, however, there is no support for
1808 // dynamic libraries so we just go back to building a normal library. Note,
1809 // however, that for MUSL if the library is built with `force_host` then
1810 // it's ok to be a dylib as the host should always support dylibs.
1811 (false, Some("lib"))
1813 (true, Some("dylib"))
1816 let trimmed
= rel_ab
.trim_end_matches(".rs").to_string();
1818 // Normally, every 'extern-private' has a correspodning 'aux-build'
1819 // entry. If so, we remove it from our list of private crates,
1820 // and add an '--extern-private' flag to rustc
1821 if extern_priv
.remove_item(&trimmed
).is_some() {
1822 add_extern_priv(&trimmed
, dylib
);
1825 if let Some(crate_type
) = crate_type
{
1826 aux_rustc
.args(&["--crate-type", crate_type
]);
1829 aux_rustc
.arg("-L").arg(&aux_dir
);
1831 let auxres
= aux_cx
.compose_and_run(
1833 aux_cx
.config
.compile_lib_path
.to_str().unwrap(),
1834 Some(aux_dir
.to_str().unwrap()),
1837 if !auxres
.status
.success() {
1838 self.fatal_proc_rec(
1840 "auxiliary build of {:?} failed to compile: ",
1841 aux_testpaths
.file
.display()
1848 // Add any '--extern-private' entries without a matching
1850 for private_lib
in extern_priv
{
1851 add_extern_priv(&private_lib
, true);
1854 self.props
.unset_rustc_env
.clone()
1856 .fold(&mut rustc
, |rustc
, v
| rustc
.env_remove(v
));
1857 rustc
.envs(self.props
.rustc_env
.clone());
1858 self.compose_and_run(
1860 self.config
.compile_lib_path
.to_str().unwrap(),
1861 Some(aux_dir
.to_str().unwrap()),
1868 mut command
: Command
,
1870 aux_path
: Option
<&str>,
1871 input
: Option
<String
>,
1874 let cmdline
= self.make_cmdline(&command
, lib_path
);
1875 logv(self.config
, format
!("executing {}", cmdline
));
1880 .stdout(Stdio
::piped())
1881 .stderr(Stdio
::piped())
1882 .stdin(Stdio
::piped());
1884 // Need to be sure to put both the lib_path and the aux path in the dylib
1885 // search path for the child.
1886 let mut path
= env
::split_paths(&env
::var_os(dylib_env_var()).unwrap_or(OsString
::new()))
1887 .collect
::<Vec
<_
>>();
1888 if let Some(p
) = aux_path
{
1889 path
.insert(0, PathBuf
::from(p
))
1891 path
.insert(0, PathBuf
::from(lib_path
));
1893 // Add the new dylib search path var
1894 let newpath
= env
::join_paths(&path
).unwrap();
1895 command
.env(dylib_env_var(), newpath
);
1897 let mut child
= disable_error_reporting(|| command
.spawn())
1898 .expect(&format
!("failed to exec `{:?}`", &command
));
1899 if let Some(input
) = input
{
1904 .write_all(input
.as_bytes())
1912 } = read2_abbreviated(child
).expect("failed to read output");
1914 let result
= ProcRes
{
1916 stdout
: String
::from_utf8_lossy(&stdout
).into_owned(),
1917 stderr
: String
::from_utf8_lossy(&stderr
).into_owned(),
1921 self.dump_output(&result
.stdout
, &result
.stderr
);
1926 fn make_compile_args(
1929 output_file
: TargetLocation
,
1931 let is_rustdoc
= self.config
.src_base
.ends_with("rustdoc-ui") ||
1932 self.config
.src_base
.ends_with("rustdoc-js");
1933 let mut rustc
= if !is_rustdoc
{
1934 Command
::new(&self.config
.rustc_path
)
1941 .expect("no rustdoc built yet"),
1944 // FIXME Why is -L here?
1945 rustc
.arg(input_file
); //.arg("-L").arg(&self.config.build_base);
1947 // Use a single thread for efficiency and a deterministic error message order
1948 rustc
.arg("-Zthreads=1");
1950 // Optionally prevent default --target if specified in test compile-flags.
1951 let custom_target
= self
1955 .any(|x
| x
.starts_with("--target"));
1958 let target
= if self.props
.force_host
{
1961 &*self.config
.target
1964 rustc
.arg(&format
!("--target={}", target
));
1966 self.set_revision_flags(&mut rustc
);
1969 if let Some(ref incremental_dir
) = self.props
.incremental_dir
{
1970 rustc
.args(&["-C", &format
!("incremental={}", incremental_dir
.display())]);
1971 rustc
.args(&["-Z", "incremental-verify-ich"]);
1972 rustc
.args(&["-Z", "incremental-queries"]);
1975 if self.config
.mode
== CodegenUnits
{
1976 rustc
.args(&["-Z", "human_readable_cgu_names"]);
1980 match self.config
.mode
{
1981 CompileFail
| Incremental
=> {
1982 // If we are extracting and matching errors in the new
1983 // fashion, then you want JSON mode. Old-skool error
1984 // patterns still match the raw compiler output.
1985 if self.props
.error_patterns
.is_empty() {
1986 rustc
.args(&["--error-format", "json"]);
1988 if !self.props
.disable_ui_testing_normalization
{
1989 rustc
.arg("-Zui-testing");
1997 .any(|s
| s
.starts_with("--error-format"))
1999 rustc
.args(&["--error-format", "json"]);
2001 if !self.props
.disable_ui_testing_normalization
{
2002 rustc
.arg("-Zui-testing");
2008 "-Zmir-opt-level=3",
2009 "-Zdump-mir-exclude-pass-number",
2012 let mir_dump_dir
= self.get_mir_dump_dir();
2013 let _
= fs
::remove_dir_all(&mir_dump_dir
);
2014 create_dir_all(mir_dump_dir
.as_path()).unwrap();
2015 let mut dir_opt
= "-Zdump-mir-dir=".to_string();
2016 dir_opt
.push_str(mir_dump_dir
.to_str().unwrap());
2017 debug
!("dir_opt: {:?}", dir_opt
);
2021 RunFail
| RunPassValgrind
| Pretty
| DebugInfoCdb
| DebugInfoGdbLldb
| DebugInfoGdb
2022 | DebugInfoLldb
| Codegen
| Rustdoc
| RunMake
| CodegenUnits
| JsDocTest
| Assembly
=> {
2023 // do not use JSON output
2027 if let Some(PassMode
::Check
) = self.pass_mode() {
2028 rustc
.args(&["--emit", "metadata"]);
2032 if self.config
.target
== "wasm32-unknown-unknown"
2033 || self.is_vxworks_pure_static() {
2034 // rustc.arg("-g"); // get any backtrace at all on errors
2035 } else if !self.props
.no_prefer_dynamic
{
2036 rustc
.args(&["-C", "prefer-dynamic"]);
2041 TargetLocation
::ThisFile(path
) => {
2042 rustc
.arg("-o").arg(path
);
2044 TargetLocation
::ThisDirectory(path
) => {
2046 // `rustdoc` uses `-o` for the output directory.
2047 rustc
.arg("-o").arg(path
);
2049 rustc
.arg("--out-dir").arg(path
);
2054 match self.config
.compare_mode
{
2055 Some(CompareMode
::Nll
) => {
2056 rustc
.args(&["-Zborrowck=mir"]);
2058 Some(CompareMode
::Polonius
) => {
2059 rustc
.args(&["-Zpolonius", "-Zborrowck=mir"]);
2064 if self.props
.force_host
{
2065 self.maybe_add_external_args(&mut rustc
,
2066 self.split_maybe_args(&self.config
.host_rustcflags
));
2068 self.maybe_add_external_args(&mut rustc
,
2069 self.split_maybe_args(&self.config
.target_rustcflags
));
2071 if let Some(ref linker
) = self.config
.linker
{
2072 rustc
.arg(format
!("-Clinker={}", linker
));
2077 // Use dynamic musl for tests because static doesn't allow creating dylibs
2078 if self.config
.host
.contains("musl")
2079 || self.is_vxworks_pure_dynamic() {
2080 rustc
.arg("-Ctarget-feature=-crt-static");
2083 rustc
.args(&self.props
.compile_flags
);
2088 fn make_exe_name(&self) -> PathBuf
{
2089 // Using a single letter here to keep the path length down for
2090 // Windows. Some test names get very long. rustc creates `rcgu`
2091 // files with the module name appended to it which can more than
2092 // double the length.
2093 let mut f
= self.output_base_dir().join("a");
2094 // FIXME: This is using the host architecture exe suffix, not target!
2095 if self.config
.target
.contains("emscripten") {
2096 f
= f
.with_extra_extension("js");
2097 } else if self.config
.target
.contains("wasm32") {
2098 f
= f
.with_extra_extension("wasm");
2099 } else if !env
::consts
::EXE_SUFFIX
.is_empty() {
2100 f
= f
.with_extra_extension(env
::consts
::EXE_SUFFIX
);
2105 fn make_run_args(&self) -> ProcArgs
{
2106 // If we've got another tool to run under (valgrind),
2107 // then split apart its command
2108 let mut args
= self.split_maybe_args(&self.config
.runtool
);
2110 // If this is emscripten, then run tests under nodejs
2111 if self.config
.target
.contains("emscripten") {
2112 if let Some(ref p
) = self.config
.nodejs
{
2113 args
.push(p
.clone());
2115 self.fatal("no NodeJS binary found (--nodejs)");
2117 // If this is otherwise wasm, then run tests under nodejs with our
2119 } else if self.config
.target
.contains("wasm32") {
2120 if let Some(ref p
) = self.config
.nodejs
{
2121 args
.push(p
.clone());
2123 self.fatal("no NodeJS binary found (--nodejs)");
2126 let src
= self.config
.src_base
2127 .parent().unwrap() // chop off `ui`
2128 .parent().unwrap() // chop off `test`
2129 .parent().unwrap(); // chop off `src`
2130 args
.push(src
.join("src/etc/wasm32-shim.js").display().to_string());
2133 let exe_file
= self.make_exe_name();
2135 // FIXME (#9639): This needs to handle non-utf8 paths
2136 args
.push(exe_file
.to_str().unwrap().to_owned());
2138 // Add the arguments in the run_flags directive
2139 args
.extend(self.split_maybe_args(&self.props
.run_flags
));
2141 let prog
= args
.remove(0);
2142 ProcArgs { prog, args }
2145 fn split_maybe_args(&self, argstr
: &Option
<String
>) -> Vec
<String
> {
2150 if s
.chars().all(|c
| c
.is_whitespace()) {
2161 fn make_cmdline(&self, command
: &Command
, libpath
: &str) -> String
{
2164 // Linux and mac don't require adjusting the library search path
2166 format
!("{:?}", command
)
2168 // Build the LD_LIBRARY_PATH variable as it would be seen on the command line
2169 // for diagnostic purposes
2170 fn lib_path_cmd_prefix(path
: &str) -> String
{
2173 util
::lib_path_env_var(),
2174 util
::make_new_path(path
)
2178 format
!("{} {:?}", lib_path_cmd_prefix(libpath
), command
)
2182 fn dump_output(&self, out
: &str, err
: &str) {
2183 let revision
= if let Some(r
) = self.revision
{
2189 self.dump_output_file(out
, &format
!("{}out", revision
));
2190 self.dump_output_file(err
, &format
!("{}err", revision
));
2191 self.maybe_dump_to_stdout(out
, err
);
2194 fn dump_output_file(&self, out
: &str, extension
: &str) {
2195 let outfile
= self.make_out_name(extension
);
2196 fs
::write(&outfile
, out
).unwrap();
2199 /// Creates a filename for output with the given extension.
2200 /// E.g., `/.../testname.revision.mode/testname.extension`.
2201 fn make_out_name(&self, extension
: &str) -> PathBuf
{
2202 self.output_base_name().with_extension(extension
)
2205 /// Gets the directory where auxiliary files are written.
2206 /// E.g., `/.../testname.revision.mode/auxiliary/`.
2207 fn aux_output_dir_name(&self) -> PathBuf
{
2208 self.output_base_dir()
2210 .with_extra_extension(self.config
.mode
.disambiguator())
2213 /// Generates a unique name for the test, such as `testname.revision.mode`.
2214 fn output_testname_unique(&self) -> PathBuf
{
2215 output_testname_unique(self.config
, self.testpaths
, self.safe_revision())
2218 /// The revision, ignored for incremental compilation since it wants all revisions in
2219 /// the same directory.
2220 fn safe_revision(&self) -> Option
<&str> {
2221 if self.config
.mode
== Incremental
{
2228 /// Gets the absolute path to the directory where all output for the given
2229 /// test/revision should reside.
2230 /// E.g., `/path/to/build/host-triple/test/ui/relative/testname.revision.mode/`.
2231 fn output_base_dir(&self) -> PathBuf
{
2232 output_base_dir(self.config
, self.testpaths
, self.safe_revision())
2235 /// Gets the absolute path to the base filename used as output for the given
2237 /// E.g., `/.../relative/testname.revision.mode/testname`.
2238 fn output_base_name(&self) -> PathBuf
{
2239 output_base_name(self.config
, self.testpaths
, self.safe_revision())
2242 fn maybe_dump_to_stdout(&self, out
: &str, err
: &str) {
2243 if self.config
.verbose
{
2244 println
!("------{}------------------------------", "stdout");
2245 println
!("{}", out
);
2246 println
!("------{}------------------------------", "stderr");
2247 println
!("{}", err
);
2248 println
!("------------------------------------------");
2252 fn error(&self, err
: &str) {
2253 match self.revision
{
2254 Some(rev
) => println
!("\nerror in revision `{}`: {}", rev
, err
),
2255 None
=> println
!("\nerror: {}", err
),
2259 fn fatal(&self, err
: &str) -> ! {
2261 error
!("fatal error, panic: {:?}", err
);
2262 panic
!("fatal error");
2265 fn fatal_proc_rec(&self, err
: &str, proc_res
: &ProcRes
) -> ! {
2267 proc_res
.fatal(None
);
2270 // codegen tests (using FileCheck)
2272 fn compile_test_and_save_ir(&self) -> ProcRes
{
2273 let aux_dir
= self.aux_output_dir_name();
2275 let output_file
= TargetLocation
::ThisDirectory(self.output_base_dir());
2276 let mut rustc
= self.make_compile_args(&self.testpaths
.file
, output_file
);
2277 rustc
.arg("-L").arg(aux_dir
).arg("--emit=llvm-ir");
2279 self.compose_and_run_compiler(rustc
, None
)
2282 fn compile_test_and_save_assembly(&self) -> (ProcRes
, PathBuf
) {
2283 // This works with both `--emit asm` (as default output name for the assembly)
2284 // and `ptx-linker` because the latter can write output at requested location.
2285 let output_path
= self.output_base_name().with_extension("s");
2287 let output_file
= TargetLocation
::ThisFile(output_path
.clone());
2288 let mut rustc
= self.make_compile_args(&self.testpaths
.file
, output_file
);
2290 rustc
.arg("-L").arg(self.aux_output_dir_name());
2292 match self.props
.assembly_output
.as_ref().map(AsRef
::as_ref
) {
2293 Some("emit-asm") => {
2294 rustc
.arg("--emit=asm");
2297 Some("ptx-linker") => {
2298 // No extra flags needed.
2301 Some(_
) => self.fatal("unknown 'assembly-output' header"),
2302 None
=> self.fatal("missing 'assembly-output' header"),
2305 (self.compose_and_run_compiler(rustc
, None
), output_path
)
2308 fn verify_with_filecheck(&self, output
: &Path
) -> ProcRes
{
2309 let mut filecheck
= Command
::new(self.config
.llvm_filecheck
.as_ref().unwrap());
2311 .arg("--input-file")
2313 .arg(&self.testpaths
.file
);
2314 // It would be more appropriate to make most of the arguments configurable through
2315 // a comment-attribute similar to `compile-flags`. For example, --check-prefixes is a very
2318 // For now, though…
2319 if let Some(rev
) = self.revision
{
2320 let prefixes
= format
!("CHECK,{}", rev
);
2321 filecheck
.args(&["--check-prefixes", &prefixes
]);
2323 self.compose_and_run(filecheck
, "", None
, None
)
2326 fn run_codegen_test(&self) {
2327 if self.config
.llvm_filecheck
.is_none() {
2328 self.fatal("missing --llvm-filecheck");
2331 let proc_res
= self.compile_test_and_save_ir();
2332 if !proc_res
.status
.success() {
2333 self.fatal_proc_rec("compilation failed!", &proc_res
);
2336 let output_path
= self.output_base_name().with_extension("ll");
2337 let proc_res
= self.verify_with_filecheck(&output_path
);
2338 if !proc_res
.status
.success() {
2339 self.fatal_proc_rec("verification with 'FileCheck' failed", &proc_res
);
2343 fn run_assembly_test(&self) {
2344 if self.config
.llvm_filecheck
.is_none() {
2345 self.fatal("missing --llvm-filecheck");
2348 let (proc_res
, output_path
) = self.compile_test_and_save_assembly();
2349 if !proc_res
.status
.success() {
2350 self.fatal_proc_rec("compilation failed!", &proc_res
);
2353 let proc_res
= self.verify_with_filecheck(&output_path
);
2354 if !proc_res
.status
.success() {
2355 self.fatal_proc_rec("verification with 'FileCheck' failed", &proc_res
);
2359 fn charset() -> &'
static str {
2360 // FreeBSD 10.1 defaults to GDB 6.1.1 which doesn't support "auto" charset
2361 if cfg
!(target_os
= "freebsd") {
2368 fn run_rustdoc_test(&self) {
2369 assert
!(self.revision
.is_none(), "revisions not relevant here");
2371 let out_dir
= self.output_base_dir();
2372 let _
= fs
::remove_dir_all(&out_dir
);
2373 create_dir_all(&out_dir
).unwrap();
2375 let proc_res
= self.document(&out_dir
);
2376 if !proc_res
.status
.success() {
2377 self.fatal_proc_rec("rustdoc failed!", &proc_res
);
2380 if self.props
.check_test_line_numbers_match
{
2381 self.check_rustdoc_test_option(proc_res
);
2383 let root
= self.config
.find_rust_src_root().unwrap();
2384 let res
= self.cmd2procres(
2385 Command
::new(&self.config
.docck_python
)
2386 .arg(root
.join("src/etc/htmldocck.py"))
2388 .arg(&self.testpaths
.file
),
2390 if !res
.status
.success() {
2391 self.fatal_proc_rec("htmldocck failed!", &res
);
2396 fn get_lines
<P
: AsRef
<Path
>>(
2399 mut other_files
: Option
<&mut Vec
<String
>>,
2401 let content
= fs
::read_to_string(&path
).unwrap();
2402 let mut ignore
= false;
2406 .filter_map(|(line_nb
, line
)| {
2407 if (line
.trim_start().starts_with("pub mod ")
2408 || line
.trim_start().starts_with("mod "))
2409 && line
.ends_with('
;'
)
2411 if let Some(ref mut other_files
) = other_files
{
2412 other_files
.push(line
.rsplit("mod ").next().unwrap().replace(";", ""));
2416 let sline
= line
.split("///").last().unwrap_or("");
2417 let line
= sline
.trim_start();
2418 if line
.starts_with("```") {
2434 fn check_rustdoc_test_option(&self, res
: ProcRes
) {
2435 let mut other_files
= Vec
::new();
2436 let mut files
: HashMap
<String
, Vec
<usize>> = HashMap
::new();
2437 let cwd
= env
::current_dir().unwrap();
2442 .unwrap_or(&self.testpaths
.file
)
2445 .replace('
\\'
, "/"),
2446 self.get_lines(&self.testpaths
.file
, Some(&mut other_files
)),
2448 for other_file
in other_files
{
2449 let mut path
= self.testpaths
.file
.clone();
2450 path
.set_file_name(&format
!("{}.rs", other_file
));
2452 path
.strip_prefix(&cwd
)
2456 .replace('
\\'
, "/"),
2457 self.get_lines(&path
, None
),
2465 .filter(|s
| s
.starts_with("test "))
2467 let tmp
: Vec
<&str> = s
.split(" - ").collect();
2469 let path
= tmp
[0].rsplit("test ").next().unwrap();
2470 if let Some(ref mut v
) = files
.get_mut(&path
.replace('
\\'
, "/")) {
2472 let mut iter
= tmp
[1].split("(line ");
2482 if let Ok(pos
) = v
.binary_search(&line
) {
2485 self.fatal_proc_rec(
2486 &format
!("Not found doc test: \"{}\" in \"{}\":{:?}", s
, path
, v
),
2494 self.fatal_proc_rec(&format
!("No test has been found... {:?}", files
), &res
);
2496 for (entry
, v
) in &files
{
2498 self.fatal_proc_rec(
2500 "Not found test at line{} \"{}\":{:?}",
2501 if v
.len() > 1 { "s" }
else { "" }
,
2512 fn run_codegen_units_test(&self) {
2513 assert
!(self.revision
.is_none(), "revisions not relevant here");
2515 let proc_res
= self.compile_test();
2517 if !proc_res
.status
.success() {
2518 self.fatal_proc_rec("compilation failed!", &proc_res
);
2521 self.check_no_compiler_crash(&proc_res
);
2523 const PREFIX
: &'
static str = "MONO_ITEM ";
2524 const CGU_MARKER
: &'
static str = "@@";
2526 let actual
: Vec
<MonoItem
> = proc_res
2529 .filter(|line
| line
.starts_with(PREFIX
))
2530 .map(|line
| str_to_mono_item(line
, true))
2533 let expected
: Vec
<MonoItem
> = errors
::load_errors(&self.testpaths
.file
, None
)
2535 .map(|e
| str_to_mono_item(&e
.msg
[..], false))
2538 let mut missing
= Vec
::new();
2539 let mut wrong_cgus
= Vec
::new();
2541 for expected_item
in &expected
{
2542 let actual_item_with_same_name
= actual
.iter().find(|ti
| ti
.name
== expected_item
.name
);
2544 if let Some(actual_item
) = actual_item_with_same_name
{
2545 if !expected_item
.codegen_units
.is_empty() &&
2546 // Also check for codegen units
2547 expected_item
.codegen_units
!= actual_item
.codegen_units
2549 wrong_cgus
.push((expected_item
.clone(), actual_item
.clone()));
2552 missing
.push(expected_item
.string
.clone());
2556 let unexpected
: Vec
<_
> = actual
2558 .filter(|acgu
| !expected
.iter().any(|ecgu
| acgu
.name
== ecgu
.name
))
2559 .map(|acgu
| acgu
.string
.clone())
2562 if !missing
.is_empty() {
2565 println
!("\nThese items should have been contained but were not:\n");
2567 for item
in &missing
{
2568 println
!("{}", item
);
2574 if !unexpected
.is_empty() {
2576 let mut sorted
= unexpected
.clone();
2581 println
!("\nThese items were contained but should not have been:\n");
2583 for item
in sorted
{
2584 println
!("{}", item
);
2590 if !wrong_cgus
.is_empty() {
2591 wrong_cgus
.sort_by_key(|pair
| pair
.0.name
.clone());
2592 println
!("\nThe following items were assigned to wrong codegen units:\n");
2594 for &(ref expected_item
, ref actual_item
) in &wrong_cgus
{
2595 println
!("{}", expected_item
.name
);
2598 codegen_units_to_str(&expected_item
.codegen_units
)
2602 codegen_units_to_str(&actual_item
.codegen_units
)
2608 if !(missing
.is_empty() && unexpected
.is_empty() && wrong_cgus
.is_empty()) {
2612 #[derive(Clone, Eq, PartialEq)]
2615 codegen_units
: HashSet
<String
>,
2619 // [MONO_ITEM] name [@@ (cgu)+]
2620 fn str_to_mono_item(s
: &str, cgu_has_crate_disambiguator
: bool
) -> MonoItem
{
2621 let s
= if s
.starts_with(PREFIX
) {
2622 (&s
[PREFIX
.len()..]).trim()
2627 let full_string
= format
!("{}{}", PREFIX
, s
);
2629 let parts
: Vec
<&str> = s
2632 .filter(|s
| !s
.is_empty())
2635 let name
= parts
[0].trim();
2637 let cgus
= if parts
.len() > 1 {
2638 let cgus_str
= parts
[1];
2643 .filter(|s
| !s
.is_empty())
2645 if cgu_has_crate_disambiguator
{
2646 remove_crate_disambiguator_from_cgu(s
)
2657 name
: name
.to_owned(),
2658 codegen_units
: cgus
,
2659 string
: full_string
,
2663 fn codegen_units_to_str(cgus
: &HashSet
<String
>) -> String
{
2664 let mut cgus
: Vec
<_
> = cgus
.iter().collect();
2667 let mut string
= String
::new();
2669 string
.push_str(&cgu
[..]);
2670 string
.push_str(" ");
2676 // Given a cgu-name-prefix of the form <crate-name>.<crate-disambiguator> or
2677 // the form <crate-name1>.<crate-disambiguator1>-in-<crate-name2>.<crate-disambiguator2>,
2678 // remove all crate-disambiguators.
2679 fn remove_crate_disambiguator_from_cgu(cgu
: &str) -> String
{
2681 static ref RE
: Regex
= Regex
::new(
2682 r
"^[^\.]+(?P<d1>\.[[:alnum:]]+)(-in-[^\.]+(?P<d2>\.[[:alnum:]]+))?"
2686 let captures
= RE
.captures(cgu
).unwrap_or_else(|| {
2687 panic
!("invalid cgu name encountered: {}", cgu
)
2690 let mut new_name
= cgu
.to_owned();
2692 if let Some(d2
) = captures
.name("d2") {
2693 new_name
.replace_range(d2
.start() .. d2
.end(), "");
2696 let d1
= captures
.name("d1").unwrap();
2697 new_name
.replace_range(d1
.start() .. d1
.end(), "");
2703 fn init_incremental_test(&self) {
2704 // (See `run_incremental_test` for an overview of how incremental tests work.)
2706 // Before any of the revisions have executed, create the
2707 // incremental workproduct directory. Delete any old
2708 // incremental work products that may be there from prior
2710 let incremental_dir
= self.incremental_dir();
2711 if incremental_dir
.exists() {
2712 // Canonicalizing the path will convert it to the //?/ format
2713 // on Windows, which enables paths longer than 260 character
2714 let canonicalized
= incremental_dir
.canonicalize().unwrap();
2715 fs
::remove_dir_all(canonicalized
).unwrap();
2717 fs
::create_dir_all(&incremental_dir
).unwrap();
2719 if self.config
.verbose
{
2721 "init_incremental_test: incremental_dir={}",
2722 incremental_dir
.display()
2727 fn run_incremental_test(&self) {
2728 // Basic plan for a test incremental/foo/bar.rs:
2729 // - load list of revisions rpass1, cfail2, rpass3
2730 // - each should begin with `rpass`, `cfail`, or `rfail`
2731 // - if `rpass`, expect compile and execution to succeed
2732 // - if `cfail`, expect compilation to fail
2733 // - if `rfail`, expect execution to fail
2734 // - create a directory build/foo/bar.incremental
2735 // - compile foo/bar.rs with -Z incremental=.../foo/bar.incremental and -C rpass1
2736 // - because name of revision starts with "rpass", expect success
2737 // - compile foo/bar.rs with -Z incremental=.../foo/bar.incremental and -C cfail2
2738 // - because name of revision starts with "cfail", expect an error
2739 // - load expected errors as usual, but filter for those that end in `[rfail2]`
2740 // - compile foo/bar.rs with -Z incremental=.../foo/bar.incremental and -C rpass3
2741 // - because name of revision starts with "rpass", expect success
2742 // - execute build/foo/bar.exe and save output
2744 // FIXME -- use non-incremental mode as an oracle? That doesn't apply
2745 // to #[rustc_dirty] and clean tests I guess
2749 .expect("incremental tests require a list of revisions");
2751 // Incremental workproduct directory should have already been created.
2752 let incremental_dir
= self.incremental_dir();
2754 incremental_dir
.exists(),
2755 "init_incremental_test failed to create incremental dir"
2758 // Add an extra flag pointing at the incremental directory.
2759 let mut revision_props
= self.props
.clone();
2760 revision_props
.incremental_dir
= Some(incremental_dir
);
2762 let revision_cx
= TestCx
{
2763 config
: self.config
,
2764 props
: &revision_props
,
2765 testpaths
: self.testpaths
,
2766 revision
: self.revision
,
2769 if self.config
.verbose
{
2771 "revision={:?} revision_props={:#?}",
2772 revision
, revision_props
2776 if revision
.starts_with("rpass") {
2777 revision_cx
.run_rpass_test();
2778 } else if revision
.starts_with("rfail") {
2779 revision_cx
.run_rfail_test();
2780 } else if revision
.starts_with("cfail") {
2781 revision_cx
.run_cfail_test();
2783 revision_cx
.fatal("revision name must begin with rpass, rfail, or cfail");
2787 /// Directory where incremental work products are stored.
2788 fn incremental_dir(&self) -> PathBuf
{
2789 self.output_base_name().with_extension("inc")
2792 fn run_rmake_test(&self) {
2793 let cwd
= env
::current_dir().unwrap();
2803 let src_root
= cwd
.join(&src_root
);
2805 let tmpdir
= cwd
.join(self.output_base_name());
2806 if tmpdir
.exists() {
2807 self.aggressive_rm_rf(&tmpdir
).unwrap();
2809 create_dir_all(&tmpdir
).unwrap();
2811 let host
= &self.config
.host
;
2812 let make
= if host
.contains("dragonfly")
2813 || host
.contains("freebsd")
2814 || host
.contains("netbsd")
2815 || host
.contains("openbsd")
2822 let mut cmd
= Command
::new(make
);
2823 cmd
.current_dir(&self.testpaths
.file
)
2824 .stdout(Stdio
::piped())
2825 .stderr(Stdio
::piped())
2826 .env("TARGET", &self.config
.target
)
2827 .env("PYTHON", &self.config
.docck_python
)
2829 .env("RUST_BUILD_STAGE", &self.config
.stage_id
)
2830 .env("RUSTC", cwd
.join(&self.config
.rustc_path
))
2831 .env("TMPDIR", &tmpdir
)
2832 .env("LD_LIB_PATH_ENVVAR", dylib_env_var())
2833 .env("HOST_RPATH_DIR", cwd
.join(&self.config
.compile_lib_path
))
2834 .env("TARGET_RPATH_DIR", cwd
.join(&self.config
.run_lib_path
))
2835 .env("LLVM_COMPONENTS", &self.config
.llvm_components
)
2836 .env("LLVM_CXXFLAGS", &self.config
.llvm_cxxflags
)
2838 // We for sure don't want these tests to run in parallel, so make
2839 // sure they don't have access to these vars if we run via `make`
2841 .env_remove("MAKEFLAGS")
2842 .env_remove("MFLAGS")
2843 .env_remove("CARGO_MAKEFLAGS");
2845 if let Some(ref rustdoc
) = self.config
.rustdoc_path
{
2846 cmd
.env("RUSTDOC", cwd
.join(rustdoc
));
2849 if let Some(ref node
) = self.config
.nodejs
{
2850 cmd
.env("NODE", node
);
2853 if let Some(ref linker
) = self.config
.linker
{
2854 cmd
.env("RUSTC_LINKER", linker
);
2857 if let Some(ref clang
) = self.config
.run_clang_based_tests_with
{
2858 cmd
.env("CLANG", clang
);
2861 if let Some(ref filecheck
) = self.config
.llvm_filecheck
{
2862 cmd
.env("LLVM_FILECHECK", filecheck
);
2865 if let Some(ref llvm_bin_dir
) = self.config
.llvm_bin_dir
{
2866 cmd
.env("LLVM_BIN_DIR", llvm_bin_dir
);
2869 // We don't want RUSTFLAGS set from the outside to interfere with
2870 // compiler flags set in the test cases:
2871 cmd
.env_remove("RUSTFLAGS");
2873 // Use dynamic musl for tests because static doesn't allow creating dylibs
2874 if self.config
.host
.contains("musl") {
2875 cmd
.env("RUSTFLAGS", "-Ctarget-feature=-crt-static")
2876 .env("IS_MUSL_HOST", "1");
2879 if self.config
.target
.contains("msvc") && self.config
.cc
!= "" {
2880 // We need to pass a path to `lib.exe`, so assume that `cc` is `cl.exe`
2881 // and that `lib.exe` lives next to it.
2882 let lib
= Path
::new(&self.config
.cc
).parent().unwrap().join("lib.exe");
2884 // MSYS doesn't like passing flags of the form `/foo` as it thinks it's
2885 // a path and instead passes `C:\msys64\foo`, so convert all
2886 // `/`-arguments to MSVC here to `-` arguments.
2891 .map(|s
| s
.replace("/", "-"))
2892 .collect
::<Vec
<_
>>()
2895 cmd
.env("IS_MSVC", "1")
2896 .env("IS_WINDOWS", "1")
2897 .env("MSVC_LIB", format
!("'{}' -nologo", lib
.display()))
2898 .env("CC", format
!("'{}' {}", self.config
.cc
, cflags
))
2899 .env("CXX", format
!("'{}'", &self.config
.cxx
));
2901 cmd
.env("CC", format
!("{} {}", self.config
.cc
, self.config
.cflags
))
2902 .env("CXX", format
!("{} {}", self.config
.cxx
, self.config
.cflags
))
2903 .env("AR", &self.config
.ar
);
2905 if self.config
.target
.contains("windows") {
2906 cmd
.env("IS_WINDOWS", "1");
2912 .and_then(read2_abbreviated
)
2913 .expect("failed to spawn `make`");
2914 if !output
.status
.success() {
2916 status
: output
.status
,
2917 stdout
: String
::from_utf8_lossy(&output
.stdout
).into_owned(),
2918 stderr
: String
::from_utf8_lossy(&output
.stderr
).into_owned(),
2919 cmdline
: format
!("{:?}", cmd
),
2921 self.fatal_proc_rec("make failed", &res
);
2925 fn aggressive_rm_rf(&self, path
: &Path
) -> io
::Result
<()> {
2926 for e
in path
.read_dir()?
{
2928 let path
= entry
.path();
2929 if entry
.file_type()?
.is_dir() {
2930 self.aggressive_rm_rf(&path
)?
;
2932 // Remove readonly files as well on windows (by default we can't)
2933 fs
::remove_file(&path
).or_else(|e
| {
2934 if cfg
!(windows
) && e
.kind() == io
::ErrorKind
::PermissionDenied
{
2935 let mut meta
= entry
.metadata()?
.permissions();
2936 meta
.set_readonly(false);
2937 fs
::set_permissions(&path
, meta
)?
;
2938 fs
::remove_file(&path
)
2945 fs
::remove_dir(path
)
2948 fn run_js_doc_test(&self) {
2949 if let Some(nodejs
) = &self.config
.nodejs
{
2950 let out_dir
= self.output_base_dir();
2952 self.document(&out_dir
);
2954 let root
= self.config
.find_rust_src_root().unwrap();
2955 let res
= self.cmd2procres(
2956 Command
::new(&nodejs
)
2957 .arg(root
.join("src/tools/rustdoc-js/tester.js"))
2958 .arg(out_dir
.parent().expect("no parent"))
2959 .arg(&self.testpaths
.file
.file_stem().expect("couldn't get file stem")),
2961 if !res
.status
.success() {
2962 self.fatal_proc_rec("rustdoc-js test failed!", &res
);
2965 self.fatal("no nodeJS");
2969 fn load_compare_outputs(&self, proc_res
: &ProcRes
,
2970 output_kind
: TestOutput
, explicit_format
: bool
) -> usize {
2972 let (stderr_kind
, stdout_kind
) = match output_kind
{
2973 TestOutput
::Compile
=> (UI_STDERR
, UI_STDOUT
),
2974 TestOutput
::Run
=> (UI_RUN_STDERR
, UI_RUN_STDOUT
)
2977 let expected_stderr
= self.load_expected_output(stderr_kind
);
2978 let expected_stdout
= self.load_expected_output(stdout_kind
);
2980 let normalized_stdout
= match output_kind
{
2981 TestOutput
::Run
if self.config
.remote_test_client
.is_some() => {
2982 // When tests are run using the remote-test-client, the string
2983 // 'uploaded "$TEST_BUILD_DIR/<test_executable>, waiting for result"'
2984 // is printed to stdout by the client and then captured in the ProcRes,
2985 // so it needs to be removed when comparing the run-pass test execution output
2987 static ref REMOTE_TEST_RE
: Regex
= Regex
::new(
2988 "^uploaded \"\\$TEST_BUILD_DIR(/[[:alnum:]_\\-]+)+\", waiting for result\n"
2991 REMOTE_TEST_RE
.replace(
2992 &self.normalize_output(&proc_res
.stdout
, &self.props
.normalize_stdout
),
2996 _
=> self.normalize_output(&proc_res
.stdout
, &self.props
.normalize_stdout
)
2999 let stderr
= if explicit_format
{
3000 proc_res
.stderr
.clone()
3002 json
::extract_rendered(&proc_res
.stderr
)
3005 let normalized_stderr
= self.normalize_output(&stderr
, &self.props
.normalize_stderr
);
3008 TestOutput
::Compile
=> {
3009 if !self.props
.dont_check_compiler_stdout
{
3010 errors
+= self.compare_output("stdout", &normalized_stdout
, &expected_stdout
);
3012 if !self.props
.dont_check_compiler_stderr
{
3013 errors
+= self.compare_output("stderr", &normalized_stderr
, &expected_stderr
);
3016 TestOutput
::Run
=> {
3017 errors
+= self.compare_output(stdout_kind
, &normalized_stdout
, &expected_stdout
);
3018 errors
+= self.compare_output(stderr_kind
, &normalized_stderr
, &expected_stderr
);
3024 fn run_ui_test(&self) {
3025 // if the user specified a format in the ui test
3026 // print the output to the stderr file, otherwise extract
3027 // the rendered error messages from json and print them
3032 .any(|s
| s
.contains("--error-format"));
3033 let proc_res
= self.compile_test();
3034 self.check_if_test_should_compile(&proc_res
);
3036 let expected_fixed
= self.load_expected_output(UI_FIXED
);
3038 let modes_to_prune
= vec
![CompareMode
::Nll
];
3039 self.prune_duplicate_outputs(&modes_to_prune
);
3041 let mut errors
= self.load_compare_outputs(&proc_res
, TestOutput
::Compile
, explicit
);
3043 if self.config
.compare_mode
.is_some() {
3044 // don't test rustfix with nll right now
3045 } else if self.config
.rustfix_coverage
{
3046 // Find out which tests have `MachineApplicable` suggestions but are missing
3047 // `run-rustfix` or `run-rustfix-only-machine-applicable` headers.
3049 // This will return an empty `Vec` in case the executed test file has a
3050 // `compile-flags: --error-format=xxxx` header with a value other than `json`.
3051 let suggestions
= get_suggestions_from_json(
3054 Filter
::MachineApplicableOnly
3055 ).unwrap_or_default();
3056 if suggestions
.len() > 0
3057 && !self.props
.run_rustfix
3058 && !self.props
.rustfix_only_machine_applicable
{
3059 let mut coverage_file_path
= self.config
.build_base
.clone();
3060 coverage_file_path
.push("rustfix_missing_coverage.txt");
3061 debug
!("coverage_file_path: {}", coverage_file_path
.display());
3063 let mut file
= OpenOptions
::new()
3066 .open(coverage_file_path
.as_path())
3067 .expect("could not create or open file");
3069 if let Err(_
) = writeln
!(file
, "{}", self.testpaths
.file
.display()) {
3070 panic
!("couldn't write to {}", coverage_file_path
.display());
3073 } else if self.props
.run_rustfix
{
3074 // Apply suggestions from rustc to the code itself
3075 let unfixed_code
= self
3076 .load_expected_output_from_path(&self.testpaths
.file
)
3078 let suggestions
= get_suggestions_from_json(
3081 if self.props
.rustfix_only_machine_applicable
{
3082 Filter
::MachineApplicableOnly
3087 let fixed_code
= apply_suggestions(&unfixed_code
, &suggestions
).expect(&format
!(
3088 "failed to apply suggestions for {:?} with rustfix",
3092 errors
+= self.compare_output("fixed", &fixed_code
, &expected_fixed
);
3093 } else if !expected_fixed
.is_empty() {
3095 "the `// run-rustfix` directive wasn't found but a `*.fixed` \
3101 println
!("To update references, rerun the tests and pass the `--bless` flag");
3102 let relative_path_to_file
= self
3105 .join(self.testpaths
.file
.file_name().unwrap());
3107 "To only update this specific test, also pass `--test-args {}`",
3108 relative_path_to_file
.display(),
3110 self.fatal_proc_rec(
3111 &format
!("{} errors occurred comparing output.", errors
),
3116 let expected_errors
= errors
::load_errors(&self.testpaths
.file
, self.revision
);
3118 if self.should_run() {
3119 let proc_res
= self.exec_compiled_test();
3120 let run_output_errors
= if self.props
.check_run_results
{
3121 self.load_compare_outputs(&proc_res
, TestOutput
::Run
, explicit
)
3125 if run_output_errors
> 0 {
3126 self.fatal_proc_rec(
3127 &format
!("{} errors occured comparing run output.", run_output_errors
),
3131 if self.should_run_successfully() {
3132 if !proc_res
.status
.success() {
3133 self.fatal_proc_rec("test run failed!", &proc_res
);
3136 if proc_res
.status
.success() {
3137 self.fatal_proc_rec("test run succeeded!", &proc_res
);
3140 if !self.props
.error_patterns
.is_empty() {
3141 // "// error-pattern" comments
3142 self.check_error_patterns(&proc_res
.stderr
, &proc_res
);
3146 debug
!("run_ui_test: explicit={:?} config.compare_mode={:?} expected_errors={:?} \
3147 proc_res.status={:?} props.error_patterns={:?}",
3148 explicit
, self.config
.compare_mode
, expected_errors
, proc_res
.status
,
3149 self.props
.error_patterns
);
3150 if !explicit
&& self.config
.compare_mode
.is_none() {
3151 if !self.should_run() && !self.props
.error_patterns
.is_empty() {
3152 // "// error-pattern" comments
3153 self.check_error_patterns(&proc_res
.stderr
, &proc_res
);
3155 if !expected_errors
.is_empty() {
3156 // "//~ERROR comments"
3157 self.check_expected_errors(expected_errors
, &proc_res
);
3161 if self.props
.run_rustfix
&& self.config
.compare_mode
.is_none() {
3162 // And finally, compile the fixed code and make sure it both
3163 // succeeds and has no diagnostics.
3164 let mut rustc
= self.make_compile_args(
3165 &self.testpaths
.file
.with_extension(UI_FIXED
),
3166 TargetLocation
::ThisFile(self.make_exe_name()),
3168 rustc
.arg("-L").arg(&self.aux_output_dir_name());
3169 let res
= self.compose_and_run_compiler(rustc
, None
);
3170 if !res
.status
.success() {
3171 self.fatal_proc_rec("failed to compile fixed code", &res
);
3173 if !res
.stderr
.is_empty() && !self.props
.rustfix_only_machine_applicable
{
3174 self.fatal_proc_rec("fixed code is still producing diagnostics", &res
);
3179 fn run_mir_opt_test(&self) {
3180 let proc_res
= self.compile_test();
3182 if !proc_res
.status
.success() {
3183 self.fatal_proc_rec("compilation failed!", &proc_res
);
3186 let proc_res
= self.exec_compiled_test();
3188 if !proc_res
.status
.success() {
3189 self.fatal_proc_rec("test run failed!", &proc_res
);
3191 self.check_mir_dump();
3194 fn check_mir_dump(&self) {
3195 let test_file_contents
= fs
::read_to_string(&self.testpaths
.file
).unwrap();
3196 if let Some(idx
) = test_file_contents
.find("// END RUST SOURCE") {
3197 let (_
, tests_text
) = test_file_contents
.split_at(idx
+ "// END_RUST SOURCE".len());
3198 let tests_text_str
= String
::from(tests_text
);
3199 let mut curr_test
: Option
<&str> = None
;
3200 let mut curr_test_contents
= vec
![ExpectedLine
::Elision
];
3201 for l
in tests_text_str
.lines() {
3202 debug
!("line: {:?}", l
);
3203 if l
.starts_with("// START ") {
3204 let (_
, t
) = l
.split_at("// START ".len());
3205 curr_test
= Some(t
);
3206 } else if l
.starts_with("// END") {
3207 let (_
, t
) = l
.split_at("// END ".len());
3208 if Some(t
) != curr_test
{
3209 panic
!("mismatched START END test name");
3211 self.compare_mir_test_output(curr_test
.unwrap(), &curr_test_contents
);
3213 curr_test_contents
.clear();
3214 curr_test_contents
.push(ExpectedLine
::Elision
);
3215 } else if l
.is_empty() {
3217 } else if l
.starts_with("//") && l
.split_at("//".len()).1.trim() == "..." {
3218 curr_test_contents
.push(ExpectedLine
::Elision
)
3219 } else if l
.starts_with("// ") {
3220 let (_
, test_content
) = l
.split_at("// ".len());
3221 curr_test_contents
.push(ExpectedLine
::Text(test_content
));
3227 fn check_mir_test_timestamp(&self, test_name
: &str, output_file
: &Path
) {
3228 let t
= |file
| fs
::metadata(file
).unwrap().modified().unwrap();
3229 let source_file
= &self.testpaths
.file
;
3230 let output_time
= t(output_file
);
3231 let source_time
= t(source_file
);
3232 if source_time
> output_time
{
3234 "source file time: {:?} output file time: {:?}",
3235 source_time
, output_time
3238 "test source file `{}` is newer than potentially stale output file `{}`.",
3239 source_file
.display(),
3245 fn compare_mir_test_output(&self, test_name
: &str, expected_content
: &[ExpectedLine
<&str>]) {
3246 let mut output_file
= PathBuf
::new();
3247 output_file
.push(self.get_mir_dump_dir());
3248 output_file
.push(test_name
);
3249 debug
!("comparing the contests of: {:?}", output_file
);
3250 debug
!("with: {:?}", expected_content
);
3251 if !output_file
.exists() {
3253 "Output file `{}` from test does not exist",
3254 output_file
.into_os_string().to_string_lossy()
3257 self.check_mir_test_timestamp(test_name
, &output_file
);
3259 let dumped_string
= fs
::read_to_string(&output_file
).unwrap();
3260 let mut dumped_lines
= dumped_string
3262 .map(|l
| nocomment_mir_line(l
))
3263 .filter(|l
| !l
.is_empty());
3264 let mut expected_lines
= expected_content
3267 if let &ExpectedLine
::Text(l
) = l
{
3275 let compare
= |expected_line
, dumped_line
| {
3276 let e_norm
= normalize_mir_line(expected_line
);
3277 let d_norm
= normalize_mir_line(dumped_line
);
3278 debug
!("found: {:?}", d_norm
);
3279 debug
!("expected: {:?}", e_norm
);
3283 let error
= |expected_line
, extra_msg
| {
3284 let normalize_all
= dumped_string
3286 .map(nocomment_mir_line
)
3287 .filter(|l
| !l
.is_empty())
3288 .collect
::<Vec
<_
>>()
3290 let f
= |l
: &ExpectedLine
<_
>| match l
{
3291 &ExpectedLine
::Elision
=> "... (elided)".into(),
3292 &ExpectedLine
::Text(t
) => t
,
3294 let expected_content
= expected_content
3297 .collect
::<Vec
<_
>>()
3300 "Did not find expected line, error: {}\n\
3301 Expected Line: {:?}\n\
3305 extra_msg
, expected_line
, test_name
, expected_content
, normalize_all
3309 // We expect each non-empty line to appear consecutively, non-consecutive lines
3310 // must be separated by at least one Elision
3311 let mut start_block_line
= None
;
3312 while let Some(dumped_line
) = dumped_lines
.next() {
3313 match expected_lines
.next() {
3314 Some(&ExpectedLine
::Text(expected_line
)) => {
3315 let normalized_expected_line
= normalize_mir_line(expected_line
);
3316 if normalized_expected_line
.contains(":{") {
3317 start_block_line
= Some(expected_line
);
3320 if !compare(expected_line
, dumped_line
) {
3321 error
!("{:?}", start_block_line
);
3325 "Mismatch in lines\n\
3326 Current block: {}\n\
3328 start_block_line
.unwrap_or("None"),
3334 Some(&ExpectedLine
::Elision
) => {
3335 // skip any number of elisions in a row.
3336 while let Some(&&ExpectedLine
::Elision
) = expected_lines
.peek() {
3337 expected_lines
.next();
3339 if let Some(&ExpectedLine
::Text(expected_line
)) = expected_lines
.next() {
3340 let mut found
= compare(expected_line
, dumped_line
);
3344 while let Some(dumped_line
) = dumped_lines
.next() {
3345 found
= compare(expected_line
, dumped_line
);
3351 error(expected_line
, "ran out of mir dump to match against".into());
3360 fn get_mir_dump_dir(&self) -> PathBuf
{
3361 let mut mir_dump_dir
= PathBuf
::from(self.config
.build_base
.as_path());
3362 debug
!("input_file: {:?}", self.testpaths
.file
);
3363 mir_dump_dir
.push(&self.testpaths
.relative_dir
);
3364 mir_dump_dir
.push(self.testpaths
.file
.file_stem().unwrap());
3368 fn normalize_output(&self, output
: &str, custom_rules
: &[(String
, String
)]) -> String
{
3369 let cflags
= self.props
.compile_flags
.join(" ");
3370 let json
= cflags
.contains("--error-format json")
3371 || cflags
.contains("--error-format pretty-json")
3372 || cflags
.contains("--error-format=json")
3373 || cflags
.contains("--error-format=pretty-json");
3375 let mut normalized
= output
.to_string();
3377 let mut normalize_path
= |from
: &Path
, to
: &str| {
3378 let mut from
= from
.display().to_string();
3380 from
= from
.replace("\\", "\\\\");
3382 normalized
= normalized
.replace(&from
, to
);
3385 let parent_dir
= self.testpaths
.file
.parent().unwrap();
3386 normalize_path(parent_dir
, "$DIR");
3388 // Paths into the libstd/libcore
3389 let src_dir
= self.config
.src_base
.parent().unwrap().parent().unwrap();
3390 normalize_path(src_dir
, "$SRC_DIR");
3392 // Paths into the build directory
3393 let test_build_dir
= &self.config
.build_base
;
3394 let parent_build_dir
= test_build_dir
.parent().unwrap().parent().unwrap().parent().unwrap();
3396 // eg. /home/user/rust/build/x86_64-unknown-linux-gnu/test/ui
3397 normalize_path(test_build_dir
, "$TEST_BUILD_DIR");
3398 // eg. /home/user/rust/build
3399 normalize_path(parent_build_dir
, "$BUILD_DIR");
3401 // Paths into lib directory.
3402 normalize_path(&parent_build_dir
.parent().unwrap().join("lib"), "$LIB_DIR");
3405 // escaped newlines in json strings should be readable
3406 // in the stderr files. There's no point int being correct,
3407 // since only humans process the stderr files.
3408 // Thus we just turn escaped newlines back into newlines.
3409 normalized
= normalized
.replace("\\n", "\n");
3412 // If there are `$SRC_DIR` normalizations with line and column numbers, then replace them
3413 // with placeholders as we do not want tests needing updated when compiler source code
3415 // eg. $SRC_DIR/libcore/mem.rs:323:14 becomes $SRC_DIR/libcore/mem.rs:LL:COL
3416 normalized
= Regex
::new("SRC_DIR(.+):\\d+:\\d+").unwrap()
3417 .replace_all(&normalized
, "SRC_DIR$1:LL:COL").into_owned();
3419 normalized
= Self::normalize_platform_differences(&normalized
);
3420 normalized
= normalized
.replace("\t", "\\t"); // makes tabs visible
3422 // Remove test annotations like `//~ ERROR text` from the output,
3423 // since they duplicate actual errors and make the output hard to read.
3424 normalized
= Regex
::new("\\s*//(\\[.*\\])?~.*").unwrap()
3425 .replace_all(&normalized
, "").into_owned();
3427 for rule
in custom_rules
{
3428 let re
= Regex
::new(&rule
.0).expect("bad regex in custom normalization rule");
3429 normalized
= re
.replace_all(&normalized
, &rule
.1[..]).into_owned();
3434 /// Normalize output differences across platforms. Generally changes Windows output to be more
3437 /// Replaces backslashes in paths with forward slashes, and replaces CRLF line endings
3439 fn normalize_platform_differences(output
: &str) -> String
{
3441 /// Used to find Windows paths.
3443 /// It's not possible to detect paths in the error messages generally, but this is a
3444 /// decent enough heuristic.
3445 static ref PATH_BACKSLASH_RE
: Regex
= Regex
::new(r
#"(?x)
3447 # Match paths that don't include spaces.
3448 (?:\\[\pL\pN\.\-_']+)+\.\pL+
3450 # If the path starts with a well-known root, then allow spaces.
3451 \$(?:DIR|SRC_DIR|TEST_BUILD_DIR|BUILD_DIR|LIB_DIR)(?:\\[\pL\pN\.\-_' ]+)+
3456 let output
= output
.replace(r
"\\", r
"\");
3458 PATH_BACKSLASH_RE
.replace_all(&output
, |caps
: &Captures
<'_
>| {
3459 println
!("{}", &caps
[0]);
3460 caps
[0].replace(r
"\", "/")
3461 }).replace("\r\n", "\n")
3464 fn expected_output_path(&self, kind
: &str) -> PathBuf
{
3465 let mut path
= expected_output_path(
3468 &self.config
.compare_mode
,
3473 if let Some(CompareMode
::Polonius
) = self.config
.compare_mode
{
3474 path
= expected_output_path(
3477 &Some(CompareMode
::Nll
),
3484 path
= expected_output_path(&self.testpaths
, self.revision
, &None
, kind
);
3490 fn load_expected_output(&self, kind
: &str) -> String
{
3491 let path
= self.expected_output_path(kind
);
3493 match self.load_expected_output_from_path(&path
) {
3495 Err(x
) => self.fatal(&x
),
3502 fn load_expected_output_from_path(&self, path
: &Path
) -> Result
<String
, String
> {
3503 fs
::read_to_string(path
).map_err(|err
| {
3504 format
!("failed to load expected output from `{}`: {}", path
.display(), err
)
3508 fn delete_file(&self, file
: &PathBuf
) {
3509 if let Err(e
) = fs
::remove_file(file
) {
3510 self.fatal(&format
!(
3511 "failed to delete `{}`: {}",
3518 fn compare_output(&self, kind
: &str, actual
: &str, expected
: &str) -> usize {
3519 if actual
== expected
{
3523 if !self.config
.bless
{
3524 if expected
.is_empty() {
3525 println
!("normalized {}:\n{}\n", kind
, actual
);
3527 println
!("diff of {}:\n", kind
);
3528 let diff_results
= make_diff(expected
, actual
, 3);
3529 for result
in diff_results
{
3530 let mut line_number
= result
.line_number
;
3531 for line
in result
.lines
{
3533 DiffLine
::Expected(e
) => {
3534 println
!("-\t{}", e
);
3537 DiffLine
::Context(c
) => {
3538 println
!("{}\t{}", line_number
, c
);
3541 DiffLine
::Resulting(r
) => {
3542 println
!("+\t{}", r
);
3551 let mode
= self.config
.compare_mode
.as_ref().map_or("", |m
| m
.to_str());
3552 let output_file
= self
3554 .with_extra_extension(self.revision
.unwrap_or(""))
3555 .with_extra_extension(mode
)
3556 .with_extra_extension(kind
);
3558 let mut files
= vec
![output_file
];
3559 if self.config
.bless
{
3560 files
.push(expected_output_path(
3563 &self.config
.compare_mode
,
3568 for output_file
in &files
{
3569 if actual
.is_empty() {
3570 self.delete_file(output_file
);
3571 } else if let Err(err
) = fs
::write(&output_file
, &actual
) {
3572 self.fatal(&format
!(
3573 "failed to write {} to `{}`: {}",
3575 output_file
.display(),
3581 println
!("\nThe actual {0} differed from the expected {0}.", kind
);
3582 for output_file
in files
{
3583 println
!("Actual {} saved to {}", kind
, output_file
.display());
3585 if self.config
.bless
{
3592 fn prune_duplicate_output(&self, mode
: CompareMode
, kind
: &str, canon_content
: &str) {
3593 let examined_path
= expected_output_path(
3600 let examined_content
= self
3601 .load_expected_output_from_path(&examined_path
)
3602 .unwrap_or_else(|_
| String
::new());
3604 if examined_path
.exists() && canon_content
== &examined_content
{
3605 self.delete_file(&examined_path
);
3609 fn prune_duplicate_outputs(&self, modes
: &[CompareMode
]) {
3610 if self.config
.bless
{
3611 for kind
in UI_EXTENSIONS
{
3612 let canon_comparison_path
= expected_output_path(
3619 if let Ok(canon
) = self.load_expected_output_from_path(&canon_comparison_path
) {
3621 self.prune_duplicate_output(mode
.clone(), kind
, &canon
);
3628 fn create_stamp(&self) {
3629 let stamp
= crate::stamp(&self.config
, self.testpaths
, self.revision
);
3630 fs
::write(&stamp
, compute_stamp_hash(&self.config
)).unwrap();
3639 pub struct ProcRes
{
3647 pub fn fatal(&self, err
: Option
<&str>) -> ! {
3648 if let Some(e
) = err
{
3649 println
!("\nerror: {}", e
);
3656 ------------------------------------------\n\
3658 ------------------------------------------\n\
3660 ------------------------------------------\n\
3662 ------------------------------------------\n\
3664 self.status
, self.cmdline
,
3665 json
::extract_rendered(&self.stdout
),
3666 json
::extract_rendered(&self.stderr
),
3668 // Use resume_unwind instead of panic!() to prevent a panic message + backtrace from
3669 // compiletest, which is unnecessary noise.
3670 std
::panic
::resume_unwind(Box
::new(()));
3674 enum TargetLocation
{
3676 ThisDirectory(PathBuf
),
3679 #[derive(Clone, PartialEq, Eq)]
3680 enum ExpectedLine
<T
: AsRef
<str>> {
3685 impl<T
> fmt
::Debug
for ExpectedLine
<T
>
3687 T
: AsRef
<str> + fmt
::Debug
,
3689 fn fmt(&self, formatter
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
3690 if let &ExpectedLine
::Text(ref t
) = self {
3691 write
!(formatter
, "{:?}", t
)
3693 write
!(formatter
, "\"...\" (Elision)")
3698 fn normalize_mir_line(line
: &str) -> String
{
3699 nocomment_mir_line(line
).replace(char::is_whitespace
, "")
3702 fn nocomment_mir_line(line
: &str) -> &str {
3703 if let Some(idx
) = line
.find("//") {
3704 let (l
, _
) = line
.split_at(idx
);
3711 fn read2_abbreviated(mut child
: Child
) -> io
::Result
<Output
> {
3712 use crate::read2
::read2
;
3713 use std
::mem
::replace
;
3715 const HEAD_LEN
: usize = 160 * 1024;
3716 const TAIL_LEN
: usize = 256 * 1024;
3728 fn extend(&mut self, data
: &[u8]) {
3729 let new_self
= match *self {
3730 ProcOutput
::Full(ref mut bytes
) => {
3731 bytes
.extend_from_slice(data
);
3732 let new_len
= bytes
.len();
3733 if new_len
<= HEAD_LEN
+ TAIL_LEN
{
3736 let tail
= bytes
.split_off(new_len
- TAIL_LEN
).into_boxed_slice();
3737 let head
= replace(bytes
, Vec
::new());
3738 let skipped
= new_len
- HEAD_LEN
- TAIL_LEN
;
3739 ProcOutput
::Abbreviated
{
3745 ProcOutput
::Abbreviated
{
3750 *skipped
+= data
.len();
3751 if data
.len() <= TAIL_LEN
{
3752 tail
[..data
.len()].copy_from_slice(data
);
3753 tail
.rotate_left(data
.len());
3755 tail
.copy_from_slice(&data
[(data
.len() - TAIL_LEN
)..]);
3763 fn into_bytes(self) -> Vec
<u8> {
3765 ProcOutput
::Full(bytes
) => bytes
,
3766 ProcOutput
::Abbreviated
{
3771 write
!(&mut head
, "\n\n<<<<<< SKIPPED {} BYTES >>>>>>\n\n", skipped
).unwrap();
3772 head
.extend_from_slice(&tail
);
3779 let mut stdout
= ProcOutput
::Full(Vec
::new());
3780 let mut stderr
= ProcOutput
::Full(Vec
::new());
3782 drop(child
.stdin
.take());
3784 child
.stdout
.take().unwrap(),
3785 child
.stderr
.take().unwrap(),
3786 &mut |is_stdout
, data
, _
| {
3787 if is_stdout { &mut stdout }
else { &mut stderr }
.extend(data
);
3791 let status
= child
.wait()?
;
3795 stdout
: stdout
.into_bytes(),
3796 stderr
: stderr
.into_bytes(),