]> git.proxmox.com Git - rustc.git/blob - src/tools/compiletest/src/runtest.rs
New upstream version 1.40.0+dfsg1
[rustc.git] / src / tools / compiletest / src / runtest.rs
1 // ignore-tidy-filelength
2
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};
12 use diff;
13 use crate::errors::{self, Error, ErrorKind};
14 use crate::header::TestProps;
15 use crate::json;
16 use regex::{Captures, Regex};
17 use rustfix::{apply_suggestions, get_suggestions_from_json, Filter};
18 use crate::util::{logv, PathBufExt};
19
20 use std::collections::hash_map::DefaultHasher;
21 use std::collections::{HashMap, HashSet, VecDeque};
22 use std::env;
23 use std::ffi::{OsStr, OsString};
24 use std::fmt;
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};
31 use std::str;
32
33 use lazy_static::lazy_static;
34 use log::*;
35
36 use crate::extract_gdb_version;
37 use crate::is_android_gdb_target;
38
39 #[cfg(test)]
40 mod tests;
41
42 #[cfg(windows)]
43 fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
44 use std::sync::Mutex;
45 const SEM_NOGPFAULTERRORBOX: u32 = 0x0002;
46 extern "system" {
47 fn SetErrorMode(mode: u32) -> u32;
48 }
49
50 lazy_static! {
51 static ref LOCK: Mutex<()> = { Mutex::new(()) };
52 }
53 // Error mode is a global variable, so lock it so only one thread will change it
54 let _lock = LOCK.lock().unwrap();
55
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.
59 unsafe {
60 let old_mode = SetErrorMode(SEM_NOGPFAULTERRORBOX); // read inherited flags
61 SetErrorMode(old_mode | SEM_NOGPFAULTERRORBOX);
62 let r = f();
63 SetErrorMode(old_mode);
64 r
65 }
66 }
67
68 #[cfg(not(windows))]
69 fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
70 f()
71 }
72
73 /// The name of the environment variable that holds dynamic library locations.
74 pub fn dylib_env_var() -> &'static str {
75 if cfg!(windows) {
76 "PATH"
77 } else if cfg!(target_os = "macos") {
78 "DYLD_LIBRARY_PATH"
79 } else if cfg!(target_os = "haiku") {
80 "LIBRARY_PATH"
81 } else {
82 "LD_LIBRARY_PATH"
83 }
84 }
85
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
92 if !dylib {
93 return format!("lib{}.rlib", lib);
94 }
95
96 if cfg!(windows) {
97 format!("{}.dll", lib)
98 } else if cfg!(target_os = "macos") {
99 format!("lib{}.dylib", lib)
100 } else {
101 format!("lib{}.so", lib)
102 }
103 }
104
105 #[derive(Debug, PartialEq)]
106 pub enum DiffLine {
107 Context(String),
108 Expected(String),
109 Resulting(String),
110 }
111
112 #[derive(Debug, PartialEq)]
113 pub struct Mismatch {
114 pub line_number: u32,
115 pub lines: Vec<DiffLine>,
116 }
117
118 impl Mismatch {
119 fn new(line_number: u32) -> Mismatch {
120 Mismatch {
121 line_number: line_number,
122 lines: Vec::new(),
123 }
124 }
125 }
126
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);
134
135 for result in diff::lines(expected, actual) {
136 match result {
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);
141 }
142
143 while let Some(line) = context_queue.pop_front() {
144 mismatch.lines.push(DiffLine::Context(line.to_owned()));
145 }
146
147 mismatch.lines.push(DiffLine::Expected(str.to_owned()));
148 line_number += 1;
149 lines_since_mismatch = 0;
150 }
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);
155 }
156
157 while let Some(line) = context_queue.pop_front() {
158 mismatch.lines.push(DiffLine::Context(line.to_owned()));
159 }
160
161 mismatch.lines.push(DiffLine::Resulting(str.to_owned()));
162 lines_since_mismatch = 0;
163 }
164 diff::Result::Both(str, _) => {
165 if context_queue.len() >= context_size {
166 let _ = context_queue.pop_front();
167 }
168
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);
173 }
174
175 line_number += 1;
176 lines_since_mismatch += 1;
177 }
178 }
179 }
180
181 results.push(mismatch);
182 results.remove(0);
183
184 results
185 }
186
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");
195 }
196 }
197
198 _ => {
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");
202 }
203 }
204 }
205
206 if config.verbose {
207 // We're going to be dumping a lot of info. Start on a new line.
208 print!("\n\n");
209 }
210 debug!("running {:?}", testpaths.file.display());
211 let props = TestProps::from_file(&testpaths.file, revision, &config);
212
213 let cx = TestCx {
214 config: &config,
215 props: &props,
216 testpaths,
217 revision: revision,
218 };
219 create_dir_all(&cx.output_base_dir()).unwrap();
220
221 if config.mode == Incremental {
222 // Incremental tests are special because they cannot be run in
223 // parallel.
224 assert!(
225 !props.revisions.is_empty(),
226 "Incremental tests require revisions."
227 );
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 {
232 config: &config,
233 props: &revision_props,
234 testpaths,
235 revision: Some(revision),
236 };
237 rev_cx.run_revision();
238 }
239 } else {
240 cx.run_revision();
241 }
242
243 cx.create_stamp();
244 }
245
246 pub fn compute_stamp_hash(config: &Config) -> String {
247 let mut hash = DefaultHasher::new();
248 config.stage_id.hash(&mut hash);
249
250 if config.mode == DebugInfoCdb {
251 config.cdb.hash(&mut hash);
252 }
253
254 if config.mode == DebugInfoGdb || config.mode == DebugInfoGdbLldb {
255 match config.gdb {
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),
259 };
260 }
261
262 if config.mode == DebugInfoLldb || config.mode == DebugInfoGdbLldb {
263 env::var_os("PATH").hash(&mut hash);
264 env::var_os("PYTHONPATH").hash(&mut hash);
265 }
266
267 if let Ui | Incremental | Pretty = config.mode {
268 config.force_pass_mode.hash(&mut hash);
269 }
270
271 format!("{:x}", hash.finish())
272 }
273
274 struct TestCx<'test> {
275 config: &'test Config,
276 props: &'test TestProps,
277 testpaths: &'test TestPaths,
278 revision: Option<&'test str>,
279 }
280
281 struct DebuggerCommands {
282 commands: Vec<String>,
283 check_lines: Vec<String>,
284 breakpoint_lines: Vec<usize>,
285 }
286
287 enum ReadFrom {
288 Path,
289 Stdin(String),
290 }
291
292 enum TestOutput {
293 Compile,
294 Run,
295 }
296
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();
309 },
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(),
322 }
323 }
324
325 fn pass_mode(&self) -> Option<PassMode> {
326 self.props.pass_mode(self.config)
327 }
328
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),
334 }
335 }
336
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),
342 }
343 }
344
345 fn should_compile_successfully(&self) -> bool {
346 match self.config.mode {
347 CompileFail => false,
348 JsDocTest => true,
349 Ui => self.pass_mode().is_some(),
350 Incremental => {
351 let revision = self.revision
352 .expect("incremental tests require a list of revisions");
353 if revision.starts_with("rpass") || revision.starts_with("rfail") {
354 true
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()
358 } else {
359 panic!("revision name must begin with rpass, rfail, or cfail");
360 }
361 }
362 mode => panic!("unimplemented for mode {:?}", mode),
363 }
364 }
365
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);
370 }
371 } else {
372 if proc_res.status.success() {
373 self.fatal_proc_rec(
374 &format!("{} test compiled successfully!", self.config.mode)[..],
375 proc_res,
376 );
377 }
378
379 self.check_correct_failure_status(proc_res);
380 }
381 }
382
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);
387
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");
393 }
394 self.check_expected_errors(expected_errors, &proc_res);
395 } else {
396 self.check_error_patterns(&output_to_check, &proc_res);
397 }
398
399 self.check_forbid_output(&output_to_check, &proc_res);
400 }
401
402 fn run_rfail_test(&self) {
403 let proc_res = self.compile_test();
404
405 if !proc_res.status.success() {
406 self.fatal_proc_rec("compilation failed!", &proc_res);
407 }
408
409 let proc_res = self.exec_compiled_test();
410
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);
415 }
416
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);
420 }
421
422 fn get_output(&self, proc_res: &ProcRes) -> String {
423 if self.props.check_stdout {
424 format!("{}{}", proc_res.stdout, proc_res.stderr)
425 } else {
426 proc_res.stderr.clone()
427 }
428 }
429
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();
433
434 if expected_status != received_status {
435 self.fatal_proc_rec(
436 &format!(
437 "Error: expected failure status ({:?}) but received status {:?}.",
438 expected_status, received_status
439 ),
440 proc_res,
441 );
442 }
443 }
444
445 fn run_rpass_test(&self) {
446 let proc_res = self.compile_test();
447
448 if !proc_res.status.success() {
449 self.fatal_proc_rec("compilation failed!", &proc_res);
450 }
451
452 // FIXME(#41968): Move this check to tidy?
453 let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
454 assert!(
455 expected_errors.is_empty(),
456 "run-pass tests with expected warnings should be moved to ui/"
457 );
458
459 let proc_res = self.exec_compiled_test();
460 if !proc_res.status.success() {
461 self.fatal_proc_rec("test run failed!", &proc_res);
462 }
463 }
464
465 fn run_valgrind_test(&self) {
466 assert!(self.revision.is_none(), "revisions not relevant here");
467
468 if self.config.valgrind_path.is_none() {
469 assert!(!self.config.force_valgrind);
470 return self.run_rpass_test();
471 }
472
473 let mut proc_res = self.compile_test();
474
475 if !proc_res.status.success() {
476 self.fatal_proc_rec("compilation failed!", &proc_res);
477 }
478
479 let mut new_config = self.config.clone();
480 new_config.runtool = new_config.valgrind_path.clone();
481 let new_cx = TestCx {
482 config: &new_config,
483 ..*self
484 };
485 proc_res = new_cx.exec_compiled_test();
486
487 if !proc_res.status.success() {
488 self.fatal_proc_rec("test run failed!", &proc_res);
489 }
490 }
491
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());
495 } else {
496 logv(
497 self.config,
498 "testing for converging pretty-printing".to_owned(),
499 );
500 }
501
502 let rounds = match self.props.pp_exact {
503 Some(_) => 1,
504 None => 2,
505 };
506
507 let src = fs::read_to_string(&self.testpaths.file).unwrap();
508 let mut srcs = vec![src];
509
510 let mut round = 0;
511 while round < rounds {
512 logv(
513 self.config,
514 format!(
515 "pretty-printing round {} revision {:?}",
516 round, self.revision
517 ),
518 );
519 let read_from = if round == 0 {
520 ReadFrom::Path
521 } else {
522 ReadFrom::Stdin(srcs[round].to_owned())
523 };
524
525 let proc_res = self.print_source(read_from,
526 &self.props.pretty_mode);
527 if !proc_res.status.success() {
528 self.fatal_proc_rec(
529 &format!(
530 "pretty-printing failed in round {} revision {:?}",
531 round, self.revision
532 ),
533 &proc_res,
534 );
535 }
536
537 let ProcRes { stdout, .. } = proc_res;
538 srcs.push(stdout);
539 round += 1;
540 }
541
542 let mut expected = match self.props.pp_exact {
543 Some(ref file) => {
544 let filepath = self.testpaths.file.parent().unwrap().join(file);
545 fs::read_to_string(&filepath).unwrap()
546 }
547 None => srcs[srcs.len() - 2].clone(),
548 };
549 let mut actual = srcs[srcs.len() - 1].clone();
550
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();
556 }
557
558 self.compare_source(&expected, &actual);
559
560 // If we're only making sure that the output matches then just stop here
561 if self.props.pretty_compare_only {
562 return;
563 }
564
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);
569 }
570
571 if !self.props.pretty_expanded {
572 return;
573 }
574
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);
579 }
580
581 let ProcRes {
582 stdout: expanded_src,
583 ..
584 } = proc_res;
585 let proc_res = self.typecheck_source(expanded_src);
586 if !proc_res.status.success() {
587 self.fatal_proc_rec(
588 "pretty-printed source (expanded) does not typecheck",
589 &proc_res,
590 );
591 }
592 }
593
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(),
599 };
600
601 let mut rustc = Command::new(&self.config.rustc_path);
602 rustc
603 .arg(input)
604 .args(&["-Z", &format!("unpretty={}", pretty_type)])
605 .args(&["--target", &self.config.target])
606 .arg("-L")
607 .arg(&aux_dir)
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));
612
613 let src = match read_from {
614 ReadFrom::Stdin(src) => Some(src),
615 ReadFrom::Path => None
616 };
617
618 self.compose_and_run(
619 rustc,
620 self.config.compile_lib_path.to_str().unwrap(),
621 Some(aux_dir.to_str().unwrap()),
622 src,
623 )
624 }
625
626 fn compare_source(&self, expected: &str, actual: &str) {
627 if expected != actual {
628 self.fatal(&format!(
629 "pretty-printed source does not match expected source\n\
630 expected:\n\
631 ------------------------------------------\n\
632 {}\n\
633 ------------------------------------------\n\
634 actual:\n\
635 ------------------------------------------\n\
636 {}\n\
637 ------------------------------------------\n\
638 \n",
639 expected, actual)
640 );
641 }
642 }
643
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]);
650 }
651 }
652
653 fn typecheck_source(&self, src: String) -> ProcRes {
654 let mut rustc = Command::new(&self.config.rustc_path);
655
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();
659
660 let target = if self.props.force_host {
661 &*self.config.host
662 } else {
663 &*self.config.target
664 };
665
666 let aux_dir = self.aux_output_dir_name();
667
668 rustc
669 .arg("-")
670 .arg("-Zno-codegen")
671 .arg("--out-dir")
672 .arg(&out_dir)
673 .arg(&format!("--target={}", target))
674 .arg("-L")
675 .arg(&self.config.build_base)
676 .arg("-L")
677 .arg(aux_dir);
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);
682
683 self.compose_and_run_compiler(rustc, Some(src))
684 }
685
686 fn run_debuginfo_cdb_test(&self) {
687 assert!(self.revision.is_none(), "revisions not relevant here");
688
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),
692 mode: DebugInfoCdb,
693 ..self.config.clone()
694 };
695
696 let test_cx = TestCx {
697 config: &config,
698 ..*self
699 };
700
701 test_cx.run_debuginfo_cdb_test_no_opt();
702 }
703
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);
709 }
710
711 let exe_file = self.make_exe_name();
712
713 let prefixes = {
714 static PREFIXES: &'static [&'static str] = &["cdb", "cdbg"];
715 // No "native rust support" variation for CDB yet.
716 PREFIXES
717 };
718
719 // Parse debugger commands etc from test files
720 let DebuggerCommands {
721 commands,
722 check_lines,
723 breakpoint_lines,
724 ..
725 } = self.parse_debugger_commands(prefixes);
726
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
731
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!(
736 "bp `{}:{}`\n",
737 source_file_name, line
738 ));
739 }
740
741 // Append the other `cdb-command:`s
742 for line in &commands {
743 script_str.push_str(line);
744 script_str.push_str("\n");
745 }
746
747 script_str.push_str("\nqq\n"); // Quit the debugger (including remote debugger, if any)
748
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");
753
754 let cdb_path = &self.config.cdb.as_ref().unwrap();
755 let mut cdb = Command::new(cdb_path);
756 cdb
757 .arg("-lines") // Enable source line debugging.
758 .arg("-cf").arg(&debugger_script)
759 .arg(&exe_file);
760
761 let debugger_run_result = self.compose_and_run(
762 cdb,
763 self.config.run_lib_path.to_str().unwrap(),
764 None, // aux_path
765 None // input
766 );
767
768 if !debugger_run_result.status.success() {
769 self.fatal_proc_rec("Error while running CDB", &debugger_run_result);
770 }
771
772 self.check_debugger_output(&debugger_run_result, &check_lines);
773 }
774
775 fn run_debuginfo_gdb_test(&self) {
776 assert!(self.revision.is_none(), "revisions not relevant here");
777
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),
781 mode: DebugInfoGdb,
782 ..self.config.clone()
783 };
784
785 let test_cx = TestCx {
786 config: &config,
787 ..*self
788 };
789
790 test_cx.run_debuginfo_gdb_test_no_opt();
791 }
792
793 fn run_debuginfo_gdb_test_no_opt(&self) {
794 let prefixes = if self.config.gdb_native_rust {
795 // GDB with Rust
796 static PREFIXES: &'static [&'static str] = &["gdb", "gdbr"];
797 println!("NOTE: compiletest thinks it is using GDB with native rust support");
798 PREFIXES
799 } else {
800 // Generic GDB
801 static PREFIXES: &'static [&'static str] = &["gdb", "gdbg"];
802 println!("NOTE: compiletest thinks it is using GDB without native rust support");
803 PREFIXES
804 };
805
806 let DebuggerCommands {
807 commands,
808 check_lines,
809 breakpoint_lines,
810 } = self.parse_debugger_commands(prefixes);
811 let mut cmds = commands.join("\n");
812
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);
817 }
818
819 let exe_file = self.make_exe_name();
820
821 let debugger_run_result;
822 if is_android_gdb_target(&self.config.target) {
823 cmds = cmds.replace("run", "continue");
824
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"),
828 };
829
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
840 ));
841 for line in &breakpoint_lines {
842 script_str.push_str(
843 &format!(
844 "break {:?}:{}\n",
845 self.testpaths.file.file_name().unwrap().to_string_lossy(),
846 *line
847 )[..],
848 );
849 }
850 script_str.push_str(&cmds);
851 script_str.push_str("\nquit\n");
852
853 debug!("script_str = {}", script_str);
854 self.dump_output_file(&script_str, "debugger.script");
855
856 let adb_path = &self.config.adb_path;
857
858 Command::new(adb_path)
859 .arg("push")
860 .arg(&exe_file)
861 .arg(&self.config.adb_test_dir)
862 .status()
863 .expect(&format!("failed to exec `{:?}`", adb_path));
864
865 Command::new(adb_path)
866 .args(&["forward", "tcp:5039", "tcp:5039"])
867 .status()
868 .expect(&format!("failed to exec `{:?}`", adb_path));
869
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") {
875 "64"
876 } else {
877 ""
878 },
879 self.config.adb_test_dir.clone(),
880 exe_file.file_name().unwrap().to_str().unwrap()
881 );
882
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())
888 .spawn()
889 .expect(&format!("failed to exec `{:?}`", adb_path));
890
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();
896 loop {
897 line.truncate(0);
898 stdout.read_line(&mut line).unwrap();
899 if line.starts_with("Listening on port 5039") {
900 break;
901 }
902 }
903 drop(stdout);
904
905 let mut debugger_script = OsString::from("-command=");
906 debugger_script.push(self.make_out_name("debugger.script"));
907 let debugger_opts: &[&OsStr] = &[
908 "-quiet".as_ref(),
909 "-batch".as_ref(),
910 "-nx".as_ref(),
911 &debugger_script,
912 ];
913
914 let gdb_path = self.config.gdb.as_ref().unwrap();
915 let Output {
916 status,
917 stdout,
918 stderr,
919 } = Command::new(&gdb_path)
920 .args(debugger_opts)
921 .output()
922 .expect(&format!("failed to exec `{:?}`", gdb_path));
923 let cmdline = {
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));
928 cmdline
929 };
930
931 debugger_run_result = ProcRes {
932 status,
933 stdout: String::from_utf8(stdout).unwrap(),
934 stderr: String::from_utf8(stderr).unwrap(),
935 cmdline,
936 };
937 if adb.kill().is_err() {
938 println!("Adb process is already finished.");
939 }
940 } else {
941 let rust_src_root = self
942 .config
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)
948 .to_str()
949 .unwrap()
950 .to_owned();
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");
955
956 match self.config.gdb_version {
957 Some(version) => {
958 println!(
959 "NOTE: compiletest thinks it is using GDB version {}",
960 version
961 );
962
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"\\")
969 ));
970 }
971 }
972 _ => {
973 println!(
974 "NOTE: compiletest does not know which version of \
975 GDB it is using"
976 );
977 }
978 }
979
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");
983
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));
986
987 // Load the target executable
988 script_str.push_str(&format!(
989 "file {}\n",
990 exe_file.to_str().unwrap().replace(r"\", r"\\")
991 ));
992
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");
996 }
997
998 // Add line breakpoints
999 for line in &breakpoint_lines {
1000 script_str.push_str(&format!(
1001 "break '{}':{}\n",
1002 self.testpaths.file.file_name().unwrap().to_string_lossy(),
1003 *line
1004 ));
1005 }
1006
1007 script_str.push_str(&cmds);
1008 script_str.push_str("\nquit\n");
1009
1010 debug!("script_str = {}", script_str);
1011 self.dump_output_file(&script_str, "debugger.script");
1012
1013 let mut debugger_script = OsString::from("-command=");
1014 debugger_script.push(self.make_out_name("debugger.script"));
1015
1016 let debugger_opts: &[&OsStr] = &[
1017 "-quiet".as_ref(),
1018 "-batch".as_ref(),
1019 "-nx".as_ref(),
1020 &debugger_script,
1021 ];
1022
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);
1026
1027 debugger_run_result = self.compose_and_run(
1028 gdb,
1029 self.config.run_lib_path.to_str().unwrap(),
1030 None,
1031 None,
1032 );
1033 }
1034
1035 if !debugger_run_result.status.success() {
1036 self.fatal_proc_rec("gdb failed to execute", &debugger_run_result);
1037 }
1038
1039 self.check_debugger_output(&debugger_run_result, &check_lines);
1040 }
1041
1042 fn run_debuginfo_lldb_test(&self) {
1043 assert!(self.revision.is_none(), "revisions not relevant here");
1044
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.");
1047 }
1048
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()
1054 };
1055
1056 let test_cx = TestCx {
1057 config: &config,
1058 ..*self
1059 };
1060
1061 test_cx.run_debuginfo_lldb_test_no_opt();
1062 }
1063
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);
1069 }
1070
1071 let exe_file = self.make_exe_name();
1072
1073 match self.config.lldb_version {
1074 Some(ref version) => {
1075 println!(
1076 "NOTE: compiletest thinks it is using LLDB version {}",
1077 version
1078 );
1079 }
1080 _ => {
1081 println!(
1082 "NOTE: compiletest does not know which version of \
1083 LLDB it is using"
1084 );
1085 }
1086 }
1087
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");
1091 PREFIXES
1092 } else {
1093 static PREFIXES: &'static [&'static str] = &["lldb", "lldbg"];
1094 println!("NOTE: compiletest thinks it is using LLDB without native rust support");
1095 PREFIXES
1096 };
1097
1098 // Parse debugger commands etc from test files
1099 let DebuggerCommands {
1100 commands,
1101 check_lines,
1102 breakpoint_lines,
1103 ..
1104 } = self.parse_debugger_commands(prefixes);
1105
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");
1109
1110 // Make LLDB emit its version, so we have it documented in the test output
1111 script_str.push_str("version\n");
1112
1113 // Switch LLDB into "Rust mode"
1114 let rust_src_root = self
1115 .config
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)
1121 .to_str()
1122 .unwrap()
1123 .to_owned();
1124
1125 script_str
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");
1131
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
1138 ));
1139 }
1140
1141 // Append the other commands
1142 for line in &commands {
1143 script_str.push_str(line);
1144 script_str.push_str("\n");
1145 }
1146
1147 // Finally, quit the debugger
1148 script_str.push_str("\nquit\n");
1149
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");
1154
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);
1157
1158 if !debugger_run_result.status.success() {
1159 self.fatal_proc_rec("Error while running LLDB", &debugger_run_result);
1160 }
1161
1162 self.check_debugger_output(&debugger_run_result, &check_lines);
1163 }
1164
1165 fn run_lldb(
1166 &self,
1167 test_executable: &Path,
1168 debugger_script: &Path,
1169 rust_src_root: &Path,
1170 ) -> ProcRes {
1171 // Prepare the lldb_batchmode which executes the debugger script
1172 let lldb_script_path = rust_src_root.join("src/etc/lldb_batchmode.py");
1173 self.cmd2procres(
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()),
1179 )
1180 }
1181
1182 fn cmd2procres(&self, cmd: &mut Command) -> ProcRes {
1183 let (status, out, err) = match cmd.output() {
1184 Ok(Output {
1185 status,
1186 stdout,
1187 stderr,
1188 }) => (
1189 status,
1190 String::from_utf8(stdout).unwrap(),
1191 String::from_utf8(stderr).unwrap(),
1192 ),
1193 Err(e) => self.fatal(&format!(
1194 "Failed to setup Python process for \
1195 LLDB script: {}",
1196 e
1197 )),
1198 };
1199
1200 self.dump_output(&out, &err);
1201 ProcRes {
1202 status,
1203 stdout: out,
1204 stderr: err,
1205 cmdline: format!("{:?}", cmd),
1206 }
1207 }
1208
1209 fn parse_debugger_commands(&self, debugger_prefixes: &[&str]) -> DebuggerCommands {
1210 let directives = debugger_prefixes
1211 .iter()
1212 .map(|prefix| (format!("{}-command", prefix), format!("{}-check", prefix)))
1213 .collect::<Vec<_>>();
1214
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() {
1221 match line {
1222 Ok(line) => {
1223 let line = if line.starts_with("//") {
1224 line[2..].trim_start()
1225 } else {
1226 line.as_str()
1227 };
1228
1229 if line.contains("#break") {
1230 breakpoint_lines.push(counter);
1231 }
1232
1233 for &(ref command_directive, ref check_directive) in &directives {
1234 self.config
1235 .parse_name_value_directive(&line, command_directive)
1236 .map(|cmd| commands.push(cmd));
1237
1238 self.config
1239 .parse_name_value_directive(&line, check_directive)
1240 .map(|cmd| check_lines.push(cmd));
1241 }
1242 }
1243 Err(e) => self.fatal(&format!("Error while parsing debugger commands: {}", e)),
1244 }
1245 counter += 1;
1246 }
1247
1248 DebuggerCommands {
1249 commands,
1250 check_lines,
1251 breakpoint_lines,
1252 }
1253 }
1254
1255 fn cleanup_debug_info_options(&self, options: &Option<String>) -> Option<String> {
1256 if options.is_none() {
1257 return None;
1258 }
1259
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)
1264 .into_iter()
1265 .filter(|x| !options_to_remove.contains(x))
1266 .collect::<Vec<String>>();
1267
1268 Some(new_options.join(" "))
1269 }
1270
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.
1273 //
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="];
1278
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))
1284 });
1285 let have_debug_flag = self.props.compile_flags.iter().any(|arg| {
1286 DEBUG_FLAGS.iter().any(|f| arg.starts_with(f))
1287 });
1288
1289 for arg in args {
1290 if OPT_FLAGS.iter().any(|f| arg.starts_with(f)) && have_opt_flag {
1291 continue;
1292 }
1293 if DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)) && have_debug_flag {
1294 continue;
1295 }
1296 cmd.arg(arg);
1297 }
1298 }
1299
1300 fn check_debugger_output(&self, debugger_run_result: &ProcRes, check_lines: &[String]) {
1301 let num_check_lines = check_lines.len();
1302
1303 let mut check_line_index = 0;
1304 for line in debugger_run_result.stdout.lines() {
1305 if check_line_index >= num_check_lines {
1306 break;
1307 }
1308
1309 if check_single_line(line, &(check_lines[check_line_index])[..]) {
1310 check_line_index += 1;
1311 }
1312 }
1313 if check_line_index != num_check_lines && num_check_lines > 0 {
1314 self.fatal_proc_rec(
1315 &format!(
1316 "line not found in debugger output: {}",
1317 check_lines[check_line_index]
1318 ),
1319 debugger_run_result,
1320 );
1321 }
1322
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("[...]");
1330
1331 let check_fragments: Vec<&str> = check_line
1332 .split("[...]")
1333 .filter(|frag| !frag.is_empty())
1334 .collect();
1335 if check_fragments.is_empty() {
1336 return true;
1337 }
1338
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,
1343 }
1344 } else {
1345 (line, 0)
1346 };
1347
1348 for current_fragment in &check_fragments[first_fragment..] {
1349 match rest.find(current_fragment) {
1350 Some(pos) => {
1351 rest = &rest[pos + current_fragment.len()..];
1352 }
1353 None => return false,
1354 }
1355 }
1356
1357 if !can_end_anywhere && !rest.is_empty() {
1358 return false;
1359 }
1360
1361 true
1362 }
1363 }
1364
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() {
1369 return;
1370 } else {
1371 self.fatal(&format!(
1372 "no error pattern specified in {:?}",
1373 self.testpaths.file.display()
1374 ));
1375 }
1376 }
1377
1378 let mut missing_patterns: Vec<String> = Vec::new();
1379
1380 for pattern in &self.props.error_patterns {
1381 if output_to_check.contains(pattern.trim()) {
1382 debug!("found error pattern {}", pattern);
1383 } else {
1384 missing_patterns.push(pattern.to_string());
1385 }
1386 }
1387
1388 if missing_patterns.is_empty() {
1389 return;
1390 }
1391
1392 if missing_patterns.len() == 1 {
1393 self.fatal_proc_rec(
1394 &format!("error pattern '{}' not found!", missing_patterns[0]),
1395 proc_res,
1396 );
1397 } else {
1398 for pattern in missing_patterns {
1399 self.error(&format!("error pattern '{}' not found!", pattern));
1400 }
1401 self.fatal_proc_rec("multiple error patterns not found", proc_res);
1402 }
1403 }
1404
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),
1409 _ => (),
1410 }
1411 }
1412
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);
1417 }
1418 }
1419 }
1420
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()
1425 && expected_errors
1426 .iter()
1427 .any(|x| x.kind == Some(ErrorKind::Error))
1428 {
1429 self.fatal_proc_rec("process did not return an error status", proc_res);
1430 }
1431
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();
1435
1436 // on windows, translate all '\' path separators to '/'
1437 let file_name = format!("{}", self.testpaths.file.display()).replace(r"\", "/");
1438
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
1444 .iter()
1445 .any(|ee| ee.kind == Some(ErrorKind::Help));
1446 let expect_note = expected_errors
1447 .iter()
1448 .any(|ee| ee.kind == Some(ErrorKind::Note));
1449
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)
1461 },
1462 );
1463
1464 match opt_index {
1465 Some(index) => {
1466 // found a match, everybody is happy
1467 assert!(!found[index]);
1468 found[index] = true;
1469 }
1470
1471 None => {
1472 if self.is_unexpected_compiler_message(actual_error, expect_help, expect_note) {
1473 self.error(&format!(
1474 "{}:{}: unexpected {}: '{}'",
1475 file_name,
1476 actual_error.line_num,
1477 actual_error
1478 .kind
1479 .as_ref()
1480 .map_or(String::from("message"), |k| k.to_string()),
1481 actual_error.msg
1482 ));
1483 unexpected.push(actual_error);
1484 }
1485 }
1486 }
1487 }
1488
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() {
1492 if !found[index] {
1493 self.error(&format!(
1494 "{}:{}: expected {} not found: {}",
1495 file_name,
1496 expected_error.line_num,
1497 expected_error
1498 .kind
1499 .as_ref()
1500 .map_or("message".into(), |k| k.to_string()),
1501 expected_error.msg
1502 ));
1503 not_found.push(expected_error);
1504 }
1505 }
1506
1507 if !unexpected.is_empty() || !not_found.is_empty() {
1508 self.error(&format!(
1509 "{} unexpected errors found, {} expected errors not found",
1510 unexpected.len(),
1511 not_found.len()
1512 ));
1513 println!("status: {}\ncommand: {}", proc_res.status, proc_res.cmdline);
1514 if !unexpected.is_empty() {
1515 println!("unexpected errors (from JSON output): {:#?}\n", unexpected);
1516 }
1517 if !not_found.is_empty() {
1518 println!("not found errors (from test file): {:#?}\n", not_found);
1519 }
1520 panic!();
1521 }
1522 }
1523
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(
1529 &self,
1530 actual_error: &Error,
1531 expect_help: bool,
1532 expect_note: bool,
1533 ) -> bool {
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,
1539 }
1540 }
1541
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,
1549 _ => false,
1550 };
1551 let output_file = if will_execute {
1552 TargetLocation::ThisFile(self.make_exe_name())
1553 } else {
1554 TargetLocation::ThisDirectory(self.output_base_dir())
1555 };
1556
1557 let mut rustc = self.make_compile_args(&self.testpaths.file, output_file);
1558
1559 rustc.arg("-L").arg(&self.aux_output_dir_name());
1560
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"]);
1574 }
1575 }
1576 _ => {}
1577 }
1578
1579 self.compose_and_run_compiler(rustc, None)
1580 }
1581
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);
1586 let aux_props =
1587 self.props
1588 .from_aux_file(&aux_testpaths.file, self.revision, self.config);
1589 let aux_cx = TestCx {
1590 config: self.config,
1591 props: &aux_props,
1592 testpaths: &aux_testpaths,
1593 revision: self.revision,
1594 };
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() {
1599 return auxres;
1600 }
1601 }
1602 }
1603
1604 let aux_dir = self.aux_output_dir_name();
1605
1606 let rustdoc_path = self
1607 .config
1608 .rustdoc_path
1609 .as_ref()
1610 .expect("--rustdoc-path passed");
1611 let mut rustdoc = Command::new(rustdoc_path);
1612
1613 rustdoc
1614 .arg("-L")
1615 .arg(self.config.run_lib_path.to_str().unwrap())
1616 .arg("-L")
1617 .arg(aux_dir)
1618 .arg("-o")
1619 .arg(out_dir)
1620 .arg(&self.testpaths.file)
1621 .args(&self.props.compile_flags);
1622
1623 if let Some(ref linker) = self.config.linker {
1624 rustdoc.arg(format!("-Clinker={}", linker));
1625 }
1626
1627 self.compose_and_run_compiler(rustdoc, None)
1628 }
1629
1630 fn exec_compiled_test(&self) -> ProcRes {
1631 let env = &self.props.exec_env;
1632
1633 let proc_res = match &*self.config.target {
1634 // This is pretty similar to below, we're transforming:
1635 //
1636 // program arg1 arg2
1637 //
1638 // into
1639 //
1640 // remote-test-client run program:support-lib.so arg1 arg2
1641 //
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() {
1654 continue;
1655 }
1656 prog.push_str(":");
1657 prog.push_str(entry.path().to_str().unwrap());
1658 }
1659 }
1660 let mut test_client =
1661 Command::new(self.config.remote_test_client.as_ref().unwrap());
1662 test_client
1663 .args(&["run", &prog])
1664 .args(args)
1665 .envs(env.clone());
1666 self.compose_and_run(
1667 test_client,
1668 self.config.run_lib_path.to_str().unwrap(),
1669 Some(aux_dir.to_str().unwrap()),
1670 None,
1671 )
1672 }
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(
1679 wr_run,
1680 self.config.run_lib_path.to_str().unwrap(),
1681 Some(aux_dir.to_str().unwrap()),
1682 None,
1683 )
1684 }
1685 _ => {
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);
1689 program
1690 .args(args)
1691 .current_dir(&self.output_base_dir())
1692 .envs(env.clone());
1693 self.compose_and_run(
1694 program,
1695 self.config.run_lib_path.to_str().unwrap(),
1696 Some(aux_dir.to_str().unwrap()),
1697 None,
1698 )
1699 }
1700 };
1701
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());
1706 }
1707
1708 proc_res
1709 }
1710
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 {
1714 let test_ab = self
1715 .testpaths
1716 .file
1717 .parent()
1718 .expect("test file path has no parent")
1719 .join("auxiliary")
1720 .join(rel_ab);
1721 if !test_ab.exists() {
1722 self.fatal(&format!(
1723 "aux-build `{}` source not found",
1724 test_ab.display()
1725 ))
1726 }
1727
1728 TestPaths {
1729 file: test_ab,
1730 relative_dir: self
1731 .testpaths
1732 .relative_dir
1733 .join(self.output_testname_unique())
1734 .join("auxiliary")
1735 .join(rel_ab)
1736 .parent()
1737 .expect("aux-build path has no parent")
1738 .to_path_buf(),
1739 }
1740 }
1741
1742 fn is_vxworks_pure_static(&self) -> bool {
1743 if self.config.target.contains("vxworks") {
1744 match env::var("RUST_VXWORKS_TEST_DYLINK") {
1745 Ok(s) => s != "1",
1746 _ => true
1747 }
1748 } else {
1749 false
1750 }
1751 }
1752
1753 fn is_vxworks_pure_dynamic(&self) -> bool {
1754 self.config.target.contains("vxworks") && !self.is_vxworks_pure_static()
1755 }
1756
1757 fn compose_and_run_compiler(&self, mut rustc: Command, input: Option<String>) -> ProcRes {
1758 let aux_dir = self.aux_output_dir_name();
1759
1760 if !self.props.aux_builds.is_empty() {
1761 let _ = fs::remove_dir_all(&aux_dir);
1762 create_dir_all(&aux_dir).unwrap();
1763 }
1764
1765 // Use a Vec instead of a HashMap to preserve original order
1766 let mut extern_priv = self.props.extern_private.clone();
1767
1768 let mut add_extern_priv = |priv_dep: &str, dylib: bool| {
1769 let lib_name = get_lib_name(priv_dep, dylib);
1770 rustc
1771 .arg("--extern-private")
1772 .arg(format!("{}={}", priv_dep, aux_dir.join(lib_name).to_str().unwrap()));
1773 };
1774
1775 for rel_ab in &self.props.aux_builds {
1776 let aux_testpaths = self.compute_aux_test_paths(rel_ab);
1777 let aux_props =
1778 self.props
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,
1783 props: &aux_props,
1784 testpaths: &aux_testpaths,
1785 revision: self.revision,
1786 };
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);
1790
1791 let (dylib, crate_type) = if aux_props.no_prefer_dynamic {
1792 (true, None)
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()
1801 {
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).
1806 //
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"))
1812 } else {
1813 (true, Some("dylib"))
1814 };
1815
1816 let trimmed = rel_ab.trim_end_matches(".rs").to_string();
1817
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);
1823 }
1824
1825 if let Some(crate_type) = crate_type {
1826 aux_rustc.args(&["--crate-type", crate_type]);
1827 }
1828
1829 aux_rustc.arg("-L").arg(&aux_dir);
1830
1831 let auxres = aux_cx.compose_and_run(
1832 aux_rustc,
1833 aux_cx.config.compile_lib_path.to_str().unwrap(),
1834 Some(aux_dir.to_str().unwrap()),
1835 None,
1836 );
1837 if !auxres.status.success() {
1838 self.fatal_proc_rec(
1839 &format!(
1840 "auxiliary build of {:?} failed to compile: ",
1841 aux_testpaths.file.display()
1842 ),
1843 &auxres,
1844 );
1845 }
1846 }
1847
1848 // Add any '--extern-private' entries without a matching
1849 // 'aux-build'
1850 for private_lib in extern_priv {
1851 add_extern_priv(&private_lib, true);
1852 }
1853
1854 self.props.unset_rustc_env.clone()
1855 .iter()
1856 .fold(&mut rustc, |rustc, v| rustc.env_remove(v));
1857 rustc.envs(self.props.rustc_env.clone());
1858 self.compose_and_run(
1859 rustc,
1860 self.config.compile_lib_path.to_str().unwrap(),
1861 Some(aux_dir.to_str().unwrap()),
1862 input,
1863 )
1864 }
1865
1866 fn compose_and_run(
1867 &self,
1868 mut command: Command,
1869 lib_path: &str,
1870 aux_path: Option<&str>,
1871 input: Option<String>,
1872 ) -> ProcRes {
1873 let cmdline = {
1874 let cmdline = self.make_cmdline(&command, lib_path);
1875 logv(self.config, format!("executing {}", cmdline));
1876 cmdline
1877 };
1878
1879 command
1880 .stdout(Stdio::piped())
1881 .stderr(Stdio::piped())
1882 .stdin(Stdio::piped());
1883
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))
1890 }
1891 path.insert(0, PathBuf::from(lib_path));
1892
1893 // Add the new dylib search path var
1894 let newpath = env::join_paths(&path).unwrap();
1895 command.env(dylib_env_var(), newpath);
1896
1897 let mut child = disable_error_reporting(|| command.spawn())
1898 .expect(&format!("failed to exec `{:?}`", &command));
1899 if let Some(input) = input {
1900 child
1901 .stdin
1902 .as_mut()
1903 .unwrap()
1904 .write_all(input.as_bytes())
1905 .unwrap();
1906 }
1907
1908 let Output {
1909 status,
1910 stdout,
1911 stderr,
1912 } = read2_abbreviated(child).expect("failed to read output");
1913
1914 let result = ProcRes {
1915 status,
1916 stdout: String::from_utf8_lossy(&stdout).into_owned(),
1917 stderr: String::from_utf8_lossy(&stderr).into_owned(),
1918 cmdline,
1919 };
1920
1921 self.dump_output(&result.stdout, &result.stderr);
1922
1923 result
1924 }
1925
1926 fn make_compile_args(
1927 &self,
1928 input_file: &Path,
1929 output_file: TargetLocation,
1930 ) -> Command {
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)
1935 } else {
1936 Command::new(
1937 &self
1938 .config
1939 .rustdoc_path
1940 .clone()
1941 .expect("no rustdoc built yet"),
1942 )
1943 };
1944 // FIXME Why is -L here?
1945 rustc.arg(input_file); //.arg("-L").arg(&self.config.build_base);
1946
1947 // Use a single thread for efficiency and a deterministic error message order
1948 rustc.arg("-Zthreads=1");
1949
1950 // Optionally prevent default --target if specified in test compile-flags.
1951 let custom_target = self
1952 .props
1953 .compile_flags
1954 .iter()
1955 .any(|x| x.starts_with("--target"));
1956
1957 if !custom_target {
1958 let target = if self.props.force_host {
1959 &*self.config.host
1960 } else {
1961 &*self.config.target
1962 };
1963
1964 rustc.arg(&format!("--target={}", target));
1965 }
1966 self.set_revision_flags(&mut rustc);
1967
1968 if !is_rustdoc {
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"]);
1973 }
1974
1975 if self.config.mode == CodegenUnits {
1976 rustc.args(&["-Z", "human_readable_cgu_names"]);
1977 }
1978 }
1979
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"]);
1987 }
1988 if !self.props.disable_ui_testing_normalization {
1989 rustc.arg("-Zui-testing");
1990 }
1991 }
1992 Ui => {
1993 if !self
1994 .props
1995 .compile_flags
1996 .iter()
1997 .any(|s| s.starts_with("--error-format"))
1998 {
1999 rustc.args(&["--error-format", "json"]);
2000 }
2001 if !self.props.disable_ui_testing_normalization {
2002 rustc.arg("-Zui-testing");
2003 }
2004 }
2005 MirOpt => {
2006 rustc.args(&[
2007 "-Zdump-mir=all",
2008 "-Zmir-opt-level=3",
2009 "-Zdump-mir-exclude-pass-number",
2010 ]);
2011
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);
2018
2019 rustc.arg(dir_opt);
2020 }
2021 RunFail | RunPassValgrind | Pretty | DebugInfoCdb | DebugInfoGdbLldb | DebugInfoGdb
2022 | DebugInfoLldb | Codegen | Rustdoc | RunMake | CodegenUnits | JsDocTest | Assembly => {
2023 // do not use JSON output
2024 }
2025 }
2026
2027 if let Some(PassMode::Check) = self.pass_mode() {
2028 rustc.args(&["--emit", "metadata"]);
2029 }
2030
2031 if !is_rustdoc {
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"]);
2037 }
2038 }
2039
2040 match output_file {
2041 TargetLocation::ThisFile(path) => {
2042 rustc.arg("-o").arg(path);
2043 }
2044 TargetLocation::ThisDirectory(path) => {
2045 if is_rustdoc {
2046 // `rustdoc` uses `-o` for the output directory.
2047 rustc.arg("-o").arg(path);
2048 } else {
2049 rustc.arg("--out-dir").arg(path);
2050 }
2051 }
2052 }
2053
2054 match self.config.compare_mode {
2055 Some(CompareMode::Nll) => {
2056 rustc.args(&["-Zborrowck=mir"]);
2057 }
2058 Some(CompareMode::Polonius) => {
2059 rustc.args(&["-Zpolonius", "-Zborrowck=mir"]);
2060 }
2061 None => {}
2062 }
2063
2064 if self.props.force_host {
2065 self.maybe_add_external_args(&mut rustc,
2066 self.split_maybe_args(&self.config.host_rustcflags));
2067 } else {
2068 self.maybe_add_external_args(&mut rustc,
2069 self.split_maybe_args(&self.config.target_rustcflags));
2070 if !is_rustdoc {
2071 if let Some(ref linker) = self.config.linker {
2072 rustc.arg(format!("-Clinker={}", linker));
2073 }
2074 }
2075 }
2076
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");
2081 }
2082
2083 rustc.args(&self.props.compile_flags);
2084
2085 rustc
2086 }
2087
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);
2101 }
2102 f
2103 }
2104
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);
2109
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());
2114 } else {
2115 self.fatal("no NodeJS binary found (--nodejs)");
2116 }
2117 // If this is otherwise wasm, then run tests under nodejs with our
2118 // shim
2119 } else if self.config.target.contains("wasm32") {
2120 if let Some(ref p) = self.config.nodejs {
2121 args.push(p.clone());
2122 } else {
2123 self.fatal("no NodeJS binary found (--nodejs)");
2124 }
2125
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());
2131 }
2132
2133 let exe_file = self.make_exe_name();
2134
2135 // FIXME (#9639): This needs to handle non-utf8 paths
2136 args.push(exe_file.to_str().unwrap().to_owned());
2137
2138 // Add the arguments in the run_flags directive
2139 args.extend(self.split_maybe_args(&self.props.run_flags));
2140
2141 let prog = args.remove(0);
2142 ProcArgs { prog, args }
2143 }
2144
2145 fn split_maybe_args(&self, argstr: &Option<String>) -> Vec<String> {
2146 match *argstr {
2147 Some(ref s) => s
2148 .split(' ')
2149 .filter_map(|s| {
2150 if s.chars().all(|c| c.is_whitespace()) {
2151 None
2152 } else {
2153 Some(s.to_owned())
2154 }
2155 })
2156 .collect(),
2157 None => Vec::new(),
2158 }
2159 }
2160
2161 fn make_cmdline(&self, command: &Command, libpath: &str) -> String {
2162 use crate::util;
2163
2164 // Linux and mac don't require adjusting the library search path
2165 if cfg!(unix) {
2166 format!("{:?}", command)
2167 } else {
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 {
2171 format!(
2172 "{}=\"{}\"",
2173 util::lib_path_env_var(),
2174 util::make_new_path(path)
2175 )
2176 }
2177
2178 format!("{} {:?}", lib_path_cmd_prefix(libpath), command)
2179 }
2180 }
2181
2182 fn dump_output(&self, out: &str, err: &str) {
2183 let revision = if let Some(r) = self.revision {
2184 format!("{}.", r)
2185 } else {
2186 String::new()
2187 };
2188
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);
2192 }
2193
2194 fn dump_output_file(&self, out: &str, extension: &str) {
2195 let outfile = self.make_out_name(extension);
2196 fs::write(&outfile, out).unwrap();
2197 }
2198
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)
2203 }
2204
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()
2209 .join("auxiliary")
2210 .with_extra_extension(self.config.mode.disambiguator())
2211 }
2212
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())
2216 }
2217
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 {
2222 None
2223 } else {
2224 self.revision
2225 }
2226 }
2227
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())
2233 }
2234
2235 /// Gets the absolute path to the base filename used as output for the given
2236 /// test/revision.
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())
2240 }
2241
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!("------------------------------------------");
2249 }
2250 }
2251
2252 fn error(&self, err: &str) {
2253 match self.revision {
2254 Some(rev) => println!("\nerror in revision `{}`: {}", rev, err),
2255 None => println!("\nerror: {}", err),
2256 }
2257 }
2258
2259 fn fatal(&self, err: &str) -> ! {
2260 self.error(err);
2261 error!("fatal error, panic: {:?}", err);
2262 panic!("fatal error");
2263 }
2264
2265 fn fatal_proc_rec(&self, err: &str, proc_res: &ProcRes) -> ! {
2266 self.error(err);
2267 proc_res.fatal(None);
2268 }
2269
2270 // codegen tests (using FileCheck)
2271
2272 fn compile_test_and_save_ir(&self) -> ProcRes {
2273 let aux_dir = self.aux_output_dir_name();
2274
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");
2278
2279 self.compose_and_run_compiler(rustc, None)
2280 }
2281
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");
2286
2287 let output_file = TargetLocation::ThisFile(output_path.clone());
2288 let mut rustc = self.make_compile_args(&self.testpaths.file, output_file);
2289
2290 rustc.arg("-L").arg(self.aux_output_dir_name());
2291
2292 match self.props.assembly_output.as_ref().map(AsRef::as_ref) {
2293 Some("emit-asm") => {
2294 rustc.arg("--emit=asm");
2295 }
2296
2297 Some("ptx-linker") => {
2298 // No extra flags needed.
2299 }
2300
2301 Some(_) => self.fatal("unknown 'assembly-output' header"),
2302 None => self.fatal("missing 'assembly-output' header"),
2303 }
2304
2305 (self.compose_and_run_compiler(rustc, None), output_path)
2306 }
2307
2308 fn verify_with_filecheck(&self, output: &Path) -> ProcRes {
2309 let mut filecheck = Command::new(self.config.llvm_filecheck.as_ref().unwrap());
2310 filecheck
2311 .arg("--input-file")
2312 .arg(output)
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
2316 // useful flag.
2317 //
2318 // For now, though…
2319 if let Some(rev) = self.revision {
2320 let prefixes = format!("CHECK,{}", rev);
2321 filecheck.args(&["--check-prefixes", &prefixes]);
2322 }
2323 self.compose_and_run(filecheck, "", None, None)
2324 }
2325
2326 fn run_codegen_test(&self) {
2327 if self.config.llvm_filecheck.is_none() {
2328 self.fatal("missing --llvm-filecheck");
2329 }
2330
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);
2334 }
2335
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);
2340 }
2341 }
2342
2343 fn run_assembly_test(&self) {
2344 if self.config.llvm_filecheck.is_none() {
2345 self.fatal("missing --llvm-filecheck");
2346 }
2347
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);
2351 }
2352
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);
2356 }
2357 }
2358
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") {
2362 "ISO-8859-1"
2363 } else {
2364 "UTF-8"
2365 }
2366 }
2367
2368 fn run_rustdoc_test(&self) {
2369 assert!(self.revision.is_none(), "revisions not relevant here");
2370
2371 let out_dir = self.output_base_dir();
2372 let _ = fs::remove_dir_all(&out_dir);
2373 create_dir_all(&out_dir).unwrap();
2374
2375 let proc_res = self.document(&out_dir);
2376 if !proc_res.status.success() {
2377 self.fatal_proc_rec("rustdoc failed!", &proc_res);
2378 }
2379
2380 if self.props.check_test_line_numbers_match {
2381 self.check_rustdoc_test_option(proc_res);
2382 } else {
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"))
2387 .arg(out_dir)
2388 .arg(&self.testpaths.file),
2389 );
2390 if !res.status.success() {
2391 self.fatal_proc_rec("htmldocck failed!", &res);
2392 }
2393 }
2394 }
2395
2396 fn get_lines<P: AsRef<Path>>(
2397 &self,
2398 path: &P,
2399 mut other_files: Option<&mut Vec<String>>,
2400 ) -> Vec<usize> {
2401 let content = fs::read_to_string(&path).unwrap();
2402 let mut ignore = false;
2403 content
2404 .lines()
2405 .enumerate()
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(';')
2410 {
2411 if let Some(ref mut other_files) = other_files {
2412 other_files.push(line.rsplit("mod ").next().unwrap().replace(";", ""));
2413 }
2414 None
2415 } else {
2416 let sline = line.split("///").last().unwrap_or("");
2417 let line = sline.trim_start();
2418 if line.starts_with("```") {
2419 if ignore {
2420 ignore = false;
2421 None
2422 } else {
2423 ignore = true;
2424 Some(line_nb + 1)
2425 }
2426 } else {
2427 None
2428 }
2429 }
2430 })
2431 .collect()
2432 }
2433
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();
2438 files.insert(
2439 self.testpaths
2440 .file
2441 .strip_prefix(&cwd)
2442 .unwrap_or(&self.testpaths.file)
2443 .to_str()
2444 .unwrap()
2445 .replace('\\', "/"),
2446 self.get_lines(&self.testpaths.file, Some(&mut other_files)),
2447 );
2448 for other_file in other_files {
2449 let mut path = self.testpaths.file.clone();
2450 path.set_file_name(&format!("{}.rs", other_file));
2451 files.insert(
2452 path.strip_prefix(&cwd)
2453 .unwrap_or(&path)
2454 .to_str()
2455 .unwrap()
2456 .replace('\\', "/"),
2457 self.get_lines(&path, None),
2458 );
2459 }
2460
2461 let mut tested = 0;
2462 for _ in res
2463 .stdout
2464 .split('\n')
2465 .filter(|s| s.starts_with("test "))
2466 .inspect(|s| {
2467 let tmp: Vec<&str> = s.split(" - ").collect();
2468 if tmp.len() == 2 {
2469 let path = tmp[0].rsplit("test ").next().unwrap();
2470 if let Some(ref mut v) = files.get_mut(&path.replace('\\', "/")) {
2471 tested += 1;
2472 let mut iter = tmp[1].split("(line ");
2473 iter.next();
2474 let line = iter
2475 .next()
2476 .unwrap_or(")")
2477 .split(')')
2478 .next()
2479 .unwrap_or("0")
2480 .parse()
2481 .unwrap_or(0);
2482 if let Ok(pos) = v.binary_search(&line) {
2483 v.remove(pos);
2484 } else {
2485 self.fatal_proc_rec(
2486 &format!("Not found doc test: \"{}\" in \"{}\":{:?}", s, path, v),
2487 &res,
2488 );
2489 }
2490 }
2491 }
2492 }) {}
2493 if tested == 0 {
2494 self.fatal_proc_rec(&format!("No test has been found... {:?}", files), &res);
2495 } else {
2496 for (entry, v) in &files {
2497 if !v.is_empty() {
2498 self.fatal_proc_rec(
2499 &format!(
2500 "Not found test at line{} \"{}\":{:?}",
2501 if v.len() > 1 { "s" } else { "" },
2502 entry,
2503 v
2504 ),
2505 &res,
2506 );
2507 }
2508 }
2509 }
2510 }
2511
2512 fn run_codegen_units_test(&self) {
2513 assert!(self.revision.is_none(), "revisions not relevant here");
2514
2515 let proc_res = self.compile_test();
2516
2517 if !proc_res.status.success() {
2518 self.fatal_proc_rec("compilation failed!", &proc_res);
2519 }
2520
2521 self.check_no_compiler_crash(&proc_res);
2522
2523 const PREFIX: &'static str = "MONO_ITEM ";
2524 const CGU_MARKER: &'static str = "@@";
2525
2526 let actual: Vec<MonoItem> = proc_res
2527 .stdout
2528 .lines()
2529 .filter(|line| line.starts_with(PREFIX))
2530 .map(|line| str_to_mono_item(line, true))
2531 .collect();
2532
2533 let expected: Vec<MonoItem> = errors::load_errors(&self.testpaths.file, None)
2534 .iter()
2535 .map(|e| str_to_mono_item(&e.msg[..], false))
2536 .collect();
2537
2538 let mut missing = Vec::new();
2539 let mut wrong_cgus = Vec::new();
2540
2541 for expected_item in &expected {
2542 let actual_item_with_same_name = actual.iter().find(|ti| ti.name == expected_item.name);
2543
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
2548 {
2549 wrong_cgus.push((expected_item.clone(), actual_item.clone()));
2550 }
2551 } else {
2552 missing.push(expected_item.string.clone());
2553 }
2554 }
2555
2556 let unexpected: Vec<_> = actual
2557 .iter()
2558 .filter(|acgu| !expected.iter().any(|ecgu| acgu.name == ecgu.name))
2559 .map(|acgu| acgu.string.clone())
2560 .collect();
2561
2562 if !missing.is_empty() {
2563 missing.sort();
2564
2565 println!("\nThese items should have been contained but were not:\n");
2566
2567 for item in &missing {
2568 println!("{}", item);
2569 }
2570
2571 println!("\n");
2572 }
2573
2574 if !unexpected.is_empty() {
2575 let sorted = {
2576 let mut sorted = unexpected.clone();
2577 sorted.sort();
2578 sorted
2579 };
2580
2581 println!("\nThese items were contained but should not have been:\n");
2582
2583 for item in sorted {
2584 println!("{}", item);
2585 }
2586
2587 println!("\n");
2588 }
2589
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");
2593
2594 for &(ref expected_item, ref actual_item) in &wrong_cgus {
2595 println!("{}", expected_item.name);
2596 println!(
2597 " expected: {}",
2598 codegen_units_to_str(&expected_item.codegen_units)
2599 );
2600 println!(
2601 " actual: {}",
2602 codegen_units_to_str(&actual_item.codegen_units)
2603 );
2604 println!();
2605 }
2606 }
2607
2608 if !(missing.is_empty() && unexpected.is_empty() && wrong_cgus.is_empty()) {
2609 panic!();
2610 }
2611
2612 #[derive(Clone, Eq, PartialEq)]
2613 struct MonoItem {
2614 name: String,
2615 codegen_units: HashSet<String>,
2616 string: String,
2617 }
2618
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()
2623 } else {
2624 s.trim()
2625 };
2626
2627 let full_string = format!("{}{}", PREFIX, s);
2628
2629 let parts: Vec<&str> = s
2630 .split(CGU_MARKER)
2631 .map(str::trim)
2632 .filter(|s| !s.is_empty())
2633 .collect();
2634
2635 let name = parts[0].trim();
2636
2637 let cgus = if parts.len() > 1 {
2638 let cgus_str = parts[1];
2639
2640 cgus_str
2641 .split(' ')
2642 .map(str::trim)
2643 .filter(|s| !s.is_empty())
2644 .map(|s| {
2645 if cgu_has_crate_disambiguator {
2646 remove_crate_disambiguator_from_cgu(s)
2647 } else {
2648 s.to_string()
2649 }
2650 })
2651 .collect()
2652 } else {
2653 HashSet::new()
2654 };
2655
2656 MonoItem {
2657 name: name.to_owned(),
2658 codegen_units: cgus,
2659 string: full_string,
2660 }
2661 }
2662
2663 fn codegen_units_to_str(cgus: &HashSet<String>) -> String {
2664 let mut cgus: Vec<_> = cgus.iter().collect();
2665 cgus.sort();
2666
2667 let mut string = String::new();
2668 for cgu in cgus {
2669 string.push_str(&cgu[..]);
2670 string.push_str(" ");
2671 }
2672
2673 string
2674 }
2675
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 {
2680 lazy_static! {
2681 static ref RE: Regex = Regex::new(
2682 r"^[^\.]+(?P<d1>\.[[:alnum:]]+)(-in-[^\.]+(?P<d2>\.[[:alnum:]]+))?"
2683 ).unwrap();
2684 }
2685
2686 let captures = RE.captures(cgu).unwrap_or_else(|| {
2687 panic!("invalid cgu name encountered: {}", cgu)
2688 });
2689
2690 let mut new_name = cgu.to_owned();
2691
2692 if let Some(d2) = captures.name("d2") {
2693 new_name.replace_range(d2.start() .. d2.end(), "");
2694 }
2695
2696 let d1 = captures.name("d1").unwrap();
2697 new_name.replace_range(d1.start() .. d1.end(), "");
2698
2699 new_name
2700 }
2701 }
2702
2703 fn init_incremental_test(&self) {
2704 // (See `run_incremental_test` for an overview of how incremental tests work.)
2705
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
2709 // runs.
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();
2716 }
2717 fs::create_dir_all(&incremental_dir).unwrap();
2718
2719 if self.config.verbose {
2720 print!(
2721 "init_incremental_test: incremental_dir={}",
2722 incremental_dir.display()
2723 );
2724 }
2725 }
2726
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
2743 //
2744 // FIXME -- use non-incremental mode as an oracle? That doesn't apply
2745 // to #[rustc_dirty] and clean tests I guess
2746
2747 let revision = self
2748 .revision
2749 .expect("incremental tests require a list of revisions");
2750
2751 // Incremental workproduct directory should have already been created.
2752 let incremental_dir = self.incremental_dir();
2753 assert!(
2754 incremental_dir.exists(),
2755 "init_incremental_test failed to create incremental dir"
2756 );
2757
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);
2761
2762 let revision_cx = TestCx {
2763 config: self.config,
2764 props: &revision_props,
2765 testpaths: self.testpaths,
2766 revision: self.revision,
2767 };
2768
2769 if self.config.verbose {
2770 print!(
2771 "revision={:?} revision_props={:#?}",
2772 revision, revision_props
2773 );
2774 }
2775
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();
2782 } else {
2783 revision_cx.fatal("revision name must begin with rpass, rfail, or cfail");
2784 }
2785 }
2786
2787 /// Directory where incremental work products are stored.
2788 fn incremental_dir(&self) -> PathBuf {
2789 self.output_base_name().with_extension("inc")
2790 }
2791
2792 fn run_rmake_test(&self) {
2793 let cwd = env::current_dir().unwrap();
2794 let src_root = self
2795 .config
2796 .src_base
2797 .parent()
2798 .unwrap()
2799 .parent()
2800 .unwrap()
2801 .parent()
2802 .unwrap();
2803 let src_root = cwd.join(&src_root);
2804
2805 let tmpdir = cwd.join(self.output_base_name());
2806 if tmpdir.exists() {
2807 self.aggressive_rm_rf(&tmpdir).unwrap();
2808 }
2809 create_dir_all(&tmpdir).unwrap();
2810
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")
2816 {
2817 "gmake"
2818 } else {
2819 "make"
2820 };
2821
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)
2828 .env("S", src_root)
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)
2837
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`
2840 // at the top level
2841 .env_remove("MAKEFLAGS")
2842 .env_remove("MFLAGS")
2843 .env_remove("CARGO_MAKEFLAGS");
2844
2845 if let Some(ref rustdoc) = self.config.rustdoc_path {
2846 cmd.env("RUSTDOC", cwd.join(rustdoc));
2847 }
2848
2849 if let Some(ref node) = self.config.nodejs {
2850 cmd.env("NODE", node);
2851 }
2852
2853 if let Some(ref linker) = self.config.linker {
2854 cmd.env("RUSTC_LINKER", linker);
2855 }
2856
2857 if let Some(ref clang) = self.config.run_clang_based_tests_with {
2858 cmd.env("CLANG", clang);
2859 }
2860
2861 if let Some(ref filecheck) = self.config.llvm_filecheck {
2862 cmd.env("LLVM_FILECHECK", filecheck);
2863 }
2864
2865 if let Some(ref llvm_bin_dir) = self.config.llvm_bin_dir {
2866 cmd.env("LLVM_BIN_DIR", llvm_bin_dir);
2867 }
2868
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");
2872
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");
2877 }
2878
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");
2883
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.
2887 let cflags = self
2888 .config
2889 .cflags
2890 .split(' ')
2891 .map(|s| s.replace("/", "-"))
2892 .collect::<Vec<_>>()
2893 .join(" ");
2894
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));
2900 } else {
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);
2904
2905 if self.config.target.contains("windows") {
2906 cmd.env("IS_WINDOWS", "1");
2907 }
2908 }
2909
2910 let output = cmd
2911 .spawn()
2912 .and_then(read2_abbreviated)
2913 .expect("failed to spawn `make`");
2914 if !output.status.success() {
2915 let res = ProcRes {
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),
2920 };
2921 self.fatal_proc_rec("make failed", &res);
2922 }
2923 }
2924
2925 fn aggressive_rm_rf(&self, path: &Path) -> io::Result<()> {
2926 for e in path.read_dir()? {
2927 let entry = e?;
2928 let path = entry.path();
2929 if entry.file_type()?.is_dir() {
2930 self.aggressive_rm_rf(&path)?;
2931 } else {
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)
2939 } else {
2940 Err(e)
2941 }
2942 })?;
2943 }
2944 }
2945 fs::remove_dir(path)
2946 }
2947
2948 fn run_js_doc_test(&self) {
2949 if let Some(nodejs) = &self.config.nodejs {
2950 let out_dir = self.output_base_dir();
2951
2952 self.document(&out_dir);
2953
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")),
2960 );
2961 if !res.status.success() {
2962 self.fatal_proc_rec("rustdoc-js test failed!", &res);
2963 }
2964 } else {
2965 self.fatal("no nodeJS");
2966 }
2967 }
2968
2969 fn load_compare_outputs(&self, proc_res: &ProcRes,
2970 output_kind: TestOutput, explicit_format: bool) -> usize {
2971
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)
2975 };
2976
2977 let expected_stderr = self.load_expected_output(stderr_kind);
2978 let expected_stdout = self.load_expected_output(stdout_kind);
2979
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
2986 lazy_static! {
2987 static ref REMOTE_TEST_RE: Regex = Regex::new(
2988 "^uploaded \"\\$TEST_BUILD_DIR(/[[:alnum:]_\\-]+)+\", waiting for result\n"
2989 ).unwrap();
2990 }
2991 REMOTE_TEST_RE.replace(
2992 &self.normalize_output(&proc_res.stdout, &self.props.normalize_stdout),
2993 ""
2994 ).to_string()
2995 }
2996 _ => self.normalize_output(&proc_res.stdout, &self.props.normalize_stdout)
2997 };
2998
2999 let stderr = if explicit_format {
3000 proc_res.stderr.clone()
3001 } else {
3002 json::extract_rendered(&proc_res.stderr)
3003 };
3004
3005 let normalized_stderr = self.normalize_output(&stderr, &self.props.normalize_stderr);
3006 let mut errors = 0;
3007 match output_kind {
3008 TestOutput::Compile => {
3009 if !self.props.dont_check_compiler_stdout {
3010 errors += self.compare_output("stdout", &normalized_stdout, &expected_stdout);
3011 }
3012 if !self.props.dont_check_compiler_stderr {
3013 errors += self.compare_output("stderr", &normalized_stderr, &expected_stderr);
3014 }
3015 }
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);
3019 }
3020 }
3021 errors
3022 }
3023
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
3028 let explicit = self
3029 .props
3030 .compile_flags
3031 .iter()
3032 .any(|s| s.contains("--error-format"));
3033 let proc_res = self.compile_test();
3034 self.check_if_test_should_compile(&proc_res);
3035
3036 let expected_fixed = self.load_expected_output(UI_FIXED);
3037
3038 let modes_to_prune = vec![CompareMode::Nll];
3039 self.prune_duplicate_outputs(&modes_to_prune);
3040
3041 let mut errors = self.load_compare_outputs(&proc_res, TestOutput::Compile, explicit);
3042
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.
3048 //
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(
3052 &proc_res.stderr,
3053 &HashSet::new(),
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());
3062
3063 let mut file = OpenOptions::new()
3064 .create(true)
3065 .append(true)
3066 .open(coverage_file_path.as_path())
3067 .expect("could not create or open file");
3068
3069 if let Err(_) = writeln!(file, "{}", self.testpaths.file.display()) {
3070 panic!("couldn't write to {}", coverage_file_path.display());
3071 }
3072 }
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)
3077 .unwrap();
3078 let suggestions = get_suggestions_from_json(
3079 &proc_res.stderr,
3080 &HashSet::new(),
3081 if self.props.rustfix_only_machine_applicable {
3082 Filter::MachineApplicableOnly
3083 } else {
3084 Filter::Everything
3085 },
3086 ).unwrap();
3087 let fixed_code = apply_suggestions(&unfixed_code, &suggestions).expect(&format!(
3088 "failed to apply suggestions for {:?} with rustfix",
3089 self.testpaths.file
3090 ));
3091
3092 errors += self.compare_output("fixed", &fixed_code, &expected_fixed);
3093 } else if !expected_fixed.is_empty() {
3094 panic!(
3095 "the `// run-rustfix` directive wasn't found but a `*.fixed` \
3096 file was found"
3097 );
3098 }
3099
3100 if errors > 0 {
3101 println!("To update references, rerun the tests and pass the `--bless` flag");
3102 let relative_path_to_file = self
3103 .testpaths
3104 .relative_dir
3105 .join(self.testpaths.file.file_name().unwrap());
3106 println!(
3107 "To only update this specific test, also pass `--test-args {}`",
3108 relative_path_to_file.display(),
3109 );
3110 self.fatal_proc_rec(
3111 &format!("{} errors occurred comparing output.", errors),
3112 &proc_res,
3113 );
3114 }
3115
3116 let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
3117
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)
3122 } else {
3123 0
3124 };
3125 if run_output_errors > 0 {
3126 self.fatal_proc_rec(
3127 &format!("{} errors occured comparing run output.", run_output_errors),
3128 &proc_res,
3129 );
3130 }
3131 if self.should_run_successfully() {
3132 if !proc_res.status.success() {
3133 self.fatal_proc_rec("test run failed!", &proc_res);
3134 }
3135 } else {
3136 if proc_res.status.success() {
3137 self.fatal_proc_rec("test run succeeded!", &proc_res);
3138 }
3139 }
3140 if !self.props.error_patterns.is_empty() {
3141 // "// error-pattern" comments
3142 self.check_error_patterns(&proc_res.stderr, &proc_res);
3143 }
3144 }
3145
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);
3154 }
3155 if !expected_errors.is_empty() {
3156 // "//~ERROR comments"
3157 self.check_expected_errors(expected_errors, &proc_res);
3158 }
3159 }
3160
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()),
3167 );
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);
3172 }
3173 if !res.stderr.is_empty() && !self.props.rustfix_only_machine_applicable {
3174 self.fatal_proc_rec("fixed code is still producing diagnostics", &res);
3175 }
3176 }
3177 }
3178
3179 fn run_mir_opt_test(&self) {
3180 let proc_res = self.compile_test();
3181
3182 if !proc_res.status.success() {
3183 self.fatal_proc_rec("compilation failed!", &proc_res);
3184 }
3185
3186 let proc_res = self.exec_compiled_test();
3187
3188 if !proc_res.status.success() {
3189 self.fatal_proc_rec("test run failed!", &proc_res);
3190 }
3191 self.check_mir_dump();
3192 }
3193
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");
3210 }
3211 self.compare_mir_test_output(curr_test.unwrap(), &curr_test_contents);
3212 curr_test = None;
3213 curr_test_contents.clear();
3214 curr_test_contents.push(ExpectedLine::Elision);
3215 } else if l.is_empty() {
3216 // ignore
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));
3222 }
3223 }
3224 }
3225 }
3226
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 {
3233 debug!(
3234 "source file time: {:?} output file time: {:?}",
3235 source_time, output_time
3236 );
3237 panic!(
3238 "test source file `{}` is newer than potentially stale output file `{}`.",
3239 source_file.display(),
3240 test_name
3241 );
3242 }
3243 }
3244
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() {
3252 panic!(
3253 "Output file `{}` from test does not exist",
3254 output_file.into_os_string().to_string_lossy()
3255 );
3256 }
3257 self.check_mir_test_timestamp(test_name, &output_file);
3258
3259 let dumped_string = fs::read_to_string(&output_file).unwrap();
3260 let mut dumped_lines = dumped_string
3261 .lines()
3262 .map(|l| nocomment_mir_line(l))
3263 .filter(|l| !l.is_empty());
3264 let mut expected_lines = expected_content
3265 .iter()
3266 .filter(|&l| {
3267 if let &ExpectedLine::Text(l) = l {
3268 !l.is_empty()
3269 } else {
3270 true
3271 }
3272 })
3273 .peekable();
3274
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);
3280 e_norm == d_norm
3281 };
3282
3283 let error = |expected_line, extra_msg| {
3284 let normalize_all = dumped_string
3285 .lines()
3286 .map(nocomment_mir_line)
3287 .filter(|l| !l.is_empty())
3288 .collect::<Vec<_>>()
3289 .join("\n");
3290 let f = |l: &ExpectedLine<_>| match l {
3291 &ExpectedLine::Elision => "... (elided)".into(),
3292 &ExpectedLine::Text(t) => t,
3293 };
3294 let expected_content = expected_content
3295 .iter()
3296 .map(|l| f(l))
3297 .collect::<Vec<_>>()
3298 .join("\n");
3299 panic!(
3300 "Did not find expected line, error: {}\n\
3301 Expected Line: {:?}\n\
3302 Test Name: {}\n\
3303 Expected:\n{}\n\
3304 Actual:\n{}",
3305 extra_msg, expected_line, test_name, expected_content, normalize_all
3306 );
3307 };
3308
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);
3318 }
3319
3320 if !compare(expected_line, dumped_line) {
3321 error!("{:?}", start_block_line);
3322 error(
3323 expected_line,
3324 format!(
3325 "Mismatch in lines\n\
3326 Current block: {}\n\
3327 Actual Line: {:?}",
3328 start_block_line.unwrap_or("None"),
3329 dumped_line
3330 ),
3331 );
3332 }
3333 }
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();
3338 }
3339 if let Some(&ExpectedLine::Text(expected_line)) = expected_lines.next() {
3340 let mut found = compare(expected_line, dumped_line);
3341 if found {
3342 continue;
3343 }
3344 while let Some(dumped_line) = dumped_lines.next() {
3345 found = compare(expected_line, dumped_line);
3346 if found {
3347 break;
3348 }
3349 }
3350 if !found {
3351 error(expected_line, "ran out of mir dump to match against".into());
3352 }
3353 }
3354 }
3355 None => {}
3356 }
3357 }
3358 }
3359
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());
3365 mir_dump_dir
3366 }
3367
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");
3374
3375 let mut normalized = output.to_string();
3376
3377 let mut normalize_path = |from: &Path, to: &str| {
3378 let mut from = from.display().to_string();
3379 if json {
3380 from = from.replace("\\", "\\\\");
3381 }
3382 normalized = normalized.replace(&from, to);
3383 };
3384
3385 let parent_dir = self.testpaths.file.parent().unwrap();
3386 normalize_path(parent_dir, "$DIR");
3387
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");
3391
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();
3395
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");
3400
3401 // Paths into lib directory.
3402 normalize_path(&parent_build_dir.parent().unwrap().join("lib"), "$LIB_DIR");
3403
3404 if json {
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");
3410 }
3411
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
3414 // changes.
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();
3418
3419 normalized = Self::normalize_platform_differences(&normalized);
3420 normalized = normalized.replace("\t", "\\t"); // makes tabs visible
3421
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();
3426
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();
3430 }
3431 normalized
3432 }
3433
3434 /// Normalize output differences across platforms. Generally changes Windows output to be more
3435 /// Unix-like.
3436 ///
3437 /// Replaces backslashes in paths with forward slashes, and replaces CRLF line endings
3438 /// with LF.
3439 fn normalize_platform_differences(output: &str) -> String {
3440 lazy_static! {
3441 /// Used to find Windows paths.
3442 ///
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)
3446 (?:
3447 # Match paths that don't include spaces.
3448 (?:\\[\pL\pN\.\-_']+)+\.\pL+
3449 |
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\.\-_' ]+)+
3452 )"#
3453 ).unwrap();
3454 }
3455
3456 let output = output.replace(r"\\", r"\");
3457
3458 PATH_BACKSLASH_RE.replace_all(&output, |caps: &Captures<'_>| {
3459 println!("{}", &caps[0]);
3460 caps[0].replace(r"\", "/")
3461 }).replace("\r\n", "\n")
3462 }
3463
3464 fn expected_output_path(&self, kind: &str) -> PathBuf {
3465 let mut path = expected_output_path(
3466 &self.testpaths,
3467 self.revision,
3468 &self.config.compare_mode,
3469 kind,
3470 );
3471
3472 if !path.exists() {
3473 if let Some(CompareMode::Polonius) = self.config.compare_mode {
3474 path = expected_output_path(
3475 &self.testpaths,
3476 self.revision,
3477 &Some(CompareMode::Nll),
3478 kind,
3479 );
3480 }
3481 }
3482
3483 if !path.exists() {
3484 path = expected_output_path(&self.testpaths, self.revision, &None, kind);
3485 }
3486
3487 path
3488 }
3489
3490 fn load_expected_output(&self, kind: &str) -> String {
3491 let path = self.expected_output_path(kind);
3492 if path.exists() {
3493 match self.load_expected_output_from_path(&path) {
3494 Ok(x) => x,
3495 Err(x) => self.fatal(&x),
3496 }
3497 } else {
3498 String::new()
3499 }
3500 }
3501
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)
3505 })
3506 }
3507
3508 fn delete_file(&self, file: &PathBuf) {
3509 if let Err(e) = fs::remove_file(file) {
3510 self.fatal(&format!(
3511 "failed to delete `{}`: {}",
3512 file.display(),
3513 e,
3514 ));
3515 }
3516 }
3517
3518 fn compare_output(&self, kind: &str, actual: &str, expected: &str) -> usize {
3519 if actual == expected {
3520 return 0;
3521 }
3522
3523 if !self.config.bless {
3524 if expected.is_empty() {
3525 println!("normalized {}:\n{}\n", kind, actual);
3526 } else {
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 {
3532 match line {
3533 DiffLine::Expected(e) => {
3534 println!("-\t{}", e);
3535 line_number += 1;
3536 }
3537 DiffLine::Context(c) => {
3538 println!("{}\t{}", line_number, c);
3539 line_number += 1;
3540 }
3541 DiffLine::Resulting(r) => {
3542 println!("+\t{}", r);
3543 }
3544 }
3545 }
3546 println!();
3547 }
3548 }
3549 }
3550
3551 let mode = self.config.compare_mode.as_ref().map_or("", |m| m.to_str());
3552 let output_file = self
3553 .output_base_name()
3554 .with_extra_extension(self.revision.unwrap_or(""))
3555 .with_extra_extension(mode)
3556 .with_extra_extension(kind);
3557
3558 let mut files = vec![output_file];
3559 if self.config.bless {
3560 files.push(expected_output_path(
3561 self.testpaths,
3562 self.revision,
3563 &self.config.compare_mode,
3564 kind,
3565 ));
3566 }
3567
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 `{}`: {}",
3574 kind,
3575 output_file.display(),
3576 err,
3577 ));
3578 }
3579 }
3580
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());
3584 }
3585 if self.config.bless {
3586 0
3587 } else {
3588 1
3589 }
3590 }
3591
3592 fn prune_duplicate_output(&self, mode: CompareMode, kind: &str, canon_content: &str) {
3593 let examined_path = expected_output_path(
3594 &self.testpaths,
3595 self.revision,
3596 &Some(mode),
3597 kind,
3598 );
3599
3600 let examined_content = self
3601 .load_expected_output_from_path(&examined_path)
3602 .unwrap_or_else(|_| String::new());
3603
3604 if examined_path.exists() && canon_content == &examined_content {
3605 self.delete_file(&examined_path);
3606 }
3607 }
3608
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(
3613 &self.testpaths,
3614 self.revision,
3615 &None,
3616 kind,
3617 );
3618
3619 if let Ok(canon) = self.load_expected_output_from_path(&canon_comparison_path) {
3620 for mode in modes {
3621 self.prune_duplicate_output(mode.clone(), kind, &canon);
3622 }
3623 }
3624 }
3625 }
3626 }
3627
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();
3631 }
3632 }
3633
3634 struct ProcArgs {
3635 prog: String,
3636 args: Vec<String>,
3637 }
3638
3639 pub struct ProcRes {
3640 status: ExitStatus,
3641 stdout: String,
3642 stderr: String,
3643 cmdline: String,
3644 }
3645
3646 impl ProcRes {
3647 pub fn fatal(&self, err: Option<&str>) -> ! {
3648 if let Some(e) = err {
3649 println!("\nerror: {}", e);
3650 }
3651 print!(
3652 "\
3653 status: {}\n\
3654 command: {}\n\
3655 stdout:\n\
3656 ------------------------------------------\n\
3657 {}\n\
3658 ------------------------------------------\n\
3659 stderr:\n\
3660 ------------------------------------------\n\
3661 {}\n\
3662 ------------------------------------------\n\
3663 \n",
3664 self.status, self.cmdline,
3665 json::extract_rendered(&self.stdout),
3666 json::extract_rendered(&self.stderr),
3667 );
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(()));
3671 }
3672 }
3673
3674 enum TargetLocation {
3675 ThisFile(PathBuf),
3676 ThisDirectory(PathBuf),
3677 }
3678
3679 #[derive(Clone, PartialEq, Eq)]
3680 enum ExpectedLine<T: AsRef<str>> {
3681 Elision,
3682 Text(T),
3683 }
3684
3685 impl<T> fmt::Debug for ExpectedLine<T>
3686 where
3687 T: AsRef<str> + fmt::Debug,
3688 {
3689 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3690 if let &ExpectedLine::Text(ref t) = self {
3691 write!(formatter, "{:?}", t)
3692 } else {
3693 write!(formatter, "\"...\" (Elision)")
3694 }
3695 }
3696 }
3697
3698 fn normalize_mir_line(line: &str) -> String {
3699 nocomment_mir_line(line).replace(char::is_whitespace, "")
3700 }
3701
3702 fn nocomment_mir_line(line: &str) -> &str {
3703 if let Some(idx) = line.find("//") {
3704 let (l, _) = line.split_at(idx);
3705 l.trim_end()
3706 } else {
3707 line
3708 }
3709 }
3710
3711 fn read2_abbreviated(mut child: Child) -> io::Result<Output> {
3712 use crate::read2::read2;
3713 use std::mem::replace;
3714
3715 const HEAD_LEN: usize = 160 * 1024;
3716 const TAIL_LEN: usize = 256 * 1024;
3717
3718 enum ProcOutput {
3719 Full(Vec<u8>),
3720 Abbreviated {
3721 head: Vec<u8>,
3722 skipped: usize,
3723 tail: Box<[u8]>,
3724 },
3725 }
3726
3727 impl ProcOutput {
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 {
3734 return;
3735 }
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 {
3740 head,
3741 skipped,
3742 tail,
3743 }
3744 }
3745 ProcOutput::Abbreviated {
3746 ref mut skipped,
3747 ref mut tail,
3748 ..
3749 } => {
3750 *skipped += data.len();
3751 if data.len() <= TAIL_LEN {
3752 tail[..data.len()].copy_from_slice(data);
3753 tail.rotate_left(data.len());
3754 } else {
3755 tail.copy_from_slice(&data[(data.len() - TAIL_LEN)..]);
3756 }
3757 return;
3758 }
3759 };
3760 *self = new_self;
3761 }
3762
3763 fn into_bytes(self) -> Vec<u8> {
3764 match self {
3765 ProcOutput::Full(bytes) => bytes,
3766 ProcOutput::Abbreviated {
3767 mut head,
3768 skipped,
3769 tail,
3770 } => {
3771 write!(&mut head, "\n\n<<<<<< SKIPPED {} BYTES >>>>>>\n\n", skipped).unwrap();
3772 head.extend_from_slice(&tail);
3773 head
3774 }
3775 }
3776 }
3777 }
3778
3779 let mut stdout = ProcOutput::Full(Vec::new());
3780 let mut stderr = ProcOutput::Full(Vec::new());
3781
3782 drop(child.stdin.take());
3783 read2(
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);
3788 data.clear();
3789 },
3790 )?;
3791 let status = child.wait()?;
3792
3793 Ok(Output {
3794 status,
3795 stdout: stdout.into_bytes(),
3796 stderr: stderr.into_bytes(),
3797 })
3798 }