]> git.proxmox.com Git - rustc.git/blob - src/tools/compiletest/src/runtest.rs
New upstream version 1.51.0+dfsg1
[rustc.git] / src / tools / compiletest / src / runtest.rs
1 // ignore-tidy-filelength
2
3 use crate::common::{expected_output_path, UI_EXTENSIONS, UI_FIXED, UI_STDERR, UI_STDOUT};
4 use crate::common::{output_base_dir, output_base_name, output_testname_unique};
5 use crate::common::{Assembly, Incremental, JsDocTest, MirOpt, RunMake, RustdocJson, Ui};
6 use crate::common::{Codegen, CodegenUnits, DebugInfo, Debugger, Rustdoc};
7 use crate::common::{CompareMode, FailMode, PassMode};
8 use crate::common::{Config, TestPaths};
9 use crate::common::{Pretty, RunPassValgrind};
10 use crate::common::{UI_RUN_STDERR, UI_RUN_STDOUT};
11 use crate::errors::{self, Error, ErrorKind};
12 use crate::header::TestProps;
13 use crate::json;
14 use crate::util::get_pointer_width;
15 use crate::util::{logv, PathBufExt};
16 use regex::{Captures, Regex};
17 use rustfix::{apply_suggestions, get_suggestions_from_json, Filter};
18
19 use std::collections::hash_map::DefaultHasher;
20 use std::collections::{HashMap, HashSet, VecDeque};
21 use std::env;
22 use std::ffi::{OsStr, OsString};
23 use std::fs::{self, create_dir_all, File, OpenOptions};
24 use std::hash::{Hash, Hasher};
25 use std::io::prelude::*;
26 use std::io::{self, BufReader};
27 use std::path::{Path, PathBuf};
28 use std::process::{Child, Command, ExitStatus, Output, Stdio};
29 use std::str;
30
31 use glob::glob;
32 use lazy_static::lazy_static;
33 use tracing::*;
34
35 use crate::extract_gdb_version;
36 use crate::is_android_gdb_target;
37
38 #[cfg(test)]
39 mod tests;
40
41 #[cfg(windows)]
42 fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
43 use std::sync::Mutex;
44 use winapi::um::errhandlingapi::SetErrorMode;
45 use winapi::um::winbase::SEM_NOGPFAULTERRORBOX;
46
47 lazy_static! {
48 static ref LOCK: Mutex<()> = Mutex::new(());
49 }
50 // Error mode is a global variable, so lock it so only one thread will change it
51 let _lock = LOCK.lock().unwrap();
52
53 // Tell Windows to not show any UI on errors (such as terminating abnormally).
54 // This is important for running tests, since some of them use abnormal
55 // termination by design. This mode is inherited by all child processes.
56 unsafe {
57 let old_mode = SetErrorMode(SEM_NOGPFAULTERRORBOX); // read inherited flags
58 SetErrorMode(old_mode | SEM_NOGPFAULTERRORBOX);
59 let r = f();
60 SetErrorMode(old_mode);
61 r
62 }
63 }
64
65 #[cfg(not(windows))]
66 fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
67 f()
68 }
69
70 /// The name of the environment variable that holds dynamic library locations.
71 pub fn dylib_env_var() -> &'static str {
72 if cfg!(windows) {
73 "PATH"
74 } else if cfg!(target_os = "macos") {
75 "DYLD_LIBRARY_PATH"
76 } else if cfg!(target_os = "haiku") {
77 "LIBRARY_PATH"
78 } else {
79 "LD_LIBRARY_PATH"
80 }
81 }
82
83 /// The platform-specific library name
84 pub fn get_lib_name(lib: &str, dylib: bool) -> String {
85 // In some casess (e.g. MUSL), we build a static
86 // library, rather than a dynamic library.
87 // In this case, the only path we can pass
88 // with '--extern-meta' is the '.lib' file
89 if !dylib {
90 return format!("lib{}.rlib", lib);
91 }
92
93 if cfg!(windows) {
94 format!("{}.dll", lib)
95 } else if cfg!(target_os = "macos") {
96 format!("lib{}.dylib", lib)
97 } else {
98 format!("lib{}.so", lib)
99 }
100 }
101
102 #[derive(Debug, PartialEq)]
103 pub enum DiffLine {
104 Context(String),
105 Expected(String),
106 Resulting(String),
107 }
108
109 #[derive(Debug, PartialEq)]
110 pub struct Mismatch {
111 pub line_number: u32,
112 pub lines: Vec<DiffLine>,
113 }
114
115 impl Mismatch {
116 fn new(line_number: u32) -> Mismatch {
117 Mismatch { line_number, lines: Vec::new() }
118 }
119 }
120
121 // Produces a diff between the expected output and actual output.
122 pub fn make_diff(expected: &str, actual: &str, context_size: usize) -> Vec<Mismatch> {
123 let mut line_number = 1;
124 let mut context_queue: VecDeque<&str> = VecDeque::with_capacity(context_size);
125 let mut lines_since_mismatch = context_size + 1;
126 let mut results = Vec::new();
127 let mut mismatch = Mismatch::new(0);
128
129 for result in diff::lines(expected, actual) {
130 match result {
131 diff::Result::Left(str) => {
132 if lines_since_mismatch >= context_size && lines_since_mismatch > 0 {
133 results.push(mismatch);
134 mismatch = Mismatch::new(line_number - context_queue.len() as u32);
135 }
136
137 while let Some(line) = context_queue.pop_front() {
138 mismatch.lines.push(DiffLine::Context(line.to_owned()));
139 }
140
141 mismatch.lines.push(DiffLine::Expected(str.to_owned()));
142 line_number += 1;
143 lines_since_mismatch = 0;
144 }
145 diff::Result::Right(str) => {
146 if lines_since_mismatch >= context_size && lines_since_mismatch > 0 {
147 results.push(mismatch);
148 mismatch = Mismatch::new(line_number - context_queue.len() as u32);
149 }
150
151 while let Some(line) = context_queue.pop_front() {
152 mismatch.lines.push(DiffLine::Context(line.to_owned()));
153 }
154
155 mismatch.lines.push(DiffLine::Resulting(str.to_owned()));
156 lines_since_mismatch = 0;
157 }
158 diff::Result::Both(str, _) => {
159 if context_queue.len() >= context_size {
160 let _ = context_queue.pop_front();
161 }
162
163 if lines_since_mismatch < context_size {
164 mismatch.lines.push(DiffLine::Context(str.to_owned()));
165 } else if context_size > 0 {
166 context_queue.push_back(str);
167 }
168
169 line_number += 1;
170 lines_since_mismatch += 1;
171 }
172 }
173 }
174
175 results.push(mismatch);
176 results.remove(0);
177
178 results
179 }
180
181 fn write_diff(expected: &str, actual: &str, context_size: usize) -> String {
182 use std::fmt::Write;
183 let mut output = String::new();
184 let diff_results = make_diff(expected, actual, context_size);
185 for result in diff_results {
186 let mut line_number = result.line_number;
187 for line in result.lines {
188 match line {
189 DiffLine::Expected(e) => {
190 writeln!(output, "-\t{}", e).unwrap();
191 line_number += 1;
192 }
193 DiffLine::Context(c) => {
194 writeln!(output, "{}\t{}", line_number, c).unwrap();
195 line_number += 1;
196 }
197 DiffLine::Resulting(r) => {
198 writeln!(output, "+\t{}", r).unwrap();
199 }
200 }
201 }
202 writeln!(output).unwrap();
203 }
204 output
205 }
206
207 pub fn run(config: Config, testpaths: &TestPaths, revision: Option<&str>) {
208 match &*config.target {
209 "arm-linux-androideabi"
210 | "armv7-linux-androideabi"
211 | "thumbv7neon-linux-androideabi"
212 | "aarch64-linux-android" => {
213 if !config.adb_device_status {
214 panic!("android device not available");
215 }
216 }
217
218 _ => {
219 // android has its own gdb handling
220 if config.debugger == Some(Debugger::Gdb) && config.gdb.is_none() {
221 panic!("gdb not available but debuginfo gdb debuginfo test requested");
222 }
223 }
224 }
225
226 if config.verbose {
227 // We're going to be dumping a lot of info. Start on a new line.
228 print!("\n\n");
229 }
230 debug!("running {:?}", testpaths.file.display());
231 let props = TestProps::from_file(&testpaths.file, revision, &config);
232
233 let cx = TestCx { config: &config, props: &props, testpaths, revision };
234 create_dir_all(&cx.output_base_dir()).unwrap();
235
236 if config.mode == Incremental {
237 // Incremental tests are special because they cannot be run in
238 // parallel.
239 assert!(!props.revisions.is_empty(), "Incremental tests require revisions.");
240 cx.init_incremental_test();
241 for revision in &props.revisions {
242 let revision_props = TestProps::from_file(&testpaths.file, Some(revision), &config);
243 let rev_cx = TestCx {
244 config: &config,
245 props: &revision_props,
246 testpaths,
247 revision: Some(revision),
248 };
249 rev_cx.run_revision();
250 }
251 } else {
252 cx.run_revision();
253 }
254
255 cx.create_stamp();
256 }
257
258 pub fn compute_stamp_hash(config: &Config) -> String {
259 let mut hash = DefaultHasher::new();
260 config.stage_id.hash(&mut hash);
261
262 match config.debugger {
263 Some(Debugger::Cdb) => {
264 config.cdb.hash(&mut hash);
265 }
266
267 Some(Debugger::Gdb) => {
268 config.gdb.hash(&mut hash);
269 env::var_os("PATH").hash(&mut hash);
270 env::var_os("PYTHONPATH").hash(&mut hash);
271 }
272
273 Some(Debugger::Lldb) => {
274 config.lldb_python.hash(&mut hash);
275 config.lldb_python_dir.hash(&mut hash);
276 env::var_os("PATH").hash(&mut hash);
277 env::var_os("PYTHONPATH").hash(&mut hash);
278 }
279
280 None => {}
281 }
282
283 if let Ui = config.mode {
284 config.force_pass_mode.hash(&mut hash);
285 }
286
287 format!("{:x}", hash.finish())
288 }
289
290 #[derive(Copy, Clone)]
291 struct TestCx<'test> {
292 config: &'test Config,
293 props: &'test TestProps,
294 testpaths: &'test TestPaths,
295 revision: Option<&'test str>,
296 }
297
298 struct DebuggerCommands {
299 commands: Vec<String>,
300 check_lines: Vec<String>,
301 breakpoint_lines: Vec<usize>,
302 }
303
304 enum ReadFrom {
305 Path,
306 Stdin(String),
307 }
308
309 enum TestOutput {
310 Compile,
311 Run,
312 }
313
314 /// Will this test be executed? Should we use `make_exe_name`?
315 #[derive(Copy, Clone, PartialEq)]
316 enum WillExecute {
317 Yes,
318 No,
319 }
320
321 /// Should `--emit metadata` be used?
322 #[derive(Copy, Clone)]
323 enum EmitMetadata {
324 Yes,
325 No,
326 }
327
328 impl<'test> TestCx<'test> {
329 /// Code executed for each revision in turn (or, if there are no
330 /// revisions, exactly once, with revision == None).
331 fn run_revision(&self) {
332 if self.props.should_ice {
333 if self.config.mode != Incremental {
334 self.fatal("cannot use should-ice in a test that is not cfail");
335 }
336 }
337 match self.config.mode {
338 RunPassValgrind => self.run_valgrind_test(),
339 Pretty => self.run_pretty_test(),
340 DebugInfo => self.run_debuginfo_test(),
341 Codegen => self.run_codegen_test(),
342 Rustdoc => self.run_rustdoc_test(),
343 RustdocJson => self.run_rustdoc_json_test(),
344 CodegenUnits => self.run_codegen_units_test(),
345 Incremental => self.run_incremental_test(),
346 RunMake => self.run_rmake_test(),
347 Ui => self.run_ui_test(),
348 MirOpt => self.run_mir_opt_test(),
349 Assembly => self.run_assembly_test(),
350 JsDocTest => self.run_js_doc_test(),
351 }
352 }
353
354 fn pass_mode(&self) -> Option<PassMode> {
355 self.props.pass_mode(self.config)
356 }
357
358 fn should_run(&self, pm: Option<PassMode>) -> WillExecute {
359 match self.config.mode {
360 Ui if pm == Some(PassMode::Run) || self.props.fail_mode == Some(FailMode::Run) => {
361 WillExecute::Yes
362 }
363 MirOpt if pm == Some(PassMode::Run) => WillExecute::Yes,
364 Ui | MirOpt => WillExecute::No,
365 mode => panic!("unimplemented for mode {:?}", mode),
366 }
367 }
368
369 fn should_run_successfully(&self, pm: Option<PassMode>) -> bool {
370 match self.config.mode {
371 Ui | MirOpt => pm == Some(PassMode::Run),
372 mode => panic!("unimplemented for mode {:?}", mode),
373 }
374 }
375
376 fn should_compile_successfully(&self, pm: Option<PassMode>) -> bool {
377 match self.config.mode {
378 JsDocTest => true,
379 Ui => pm.is_some() || self.props.fail_mode > Some(FailMode::Build),
380 Incremental => {
381 let revision =
382 self.revision.expect("incremental tests require a list of revisions");
383 if revision.starts_with("rpass") || revision.starts_with("rfail") {
384 true
385 } else if revision.starts_with("cfail") {
386 // FIXME: would be nice if incremental revs could start with "cpass"
387 pm.is_some()
388 } else {
389 panic!("revision name must begin with rpass, rfail, or cfail");
390 }
391 }
392 mode => panic!("unimplemented for mode {:?}", mode),
393 }
394 }
395
396 fn check_if_test_should_compile(&self, proc_res: &ProcRes, pm: Option<PassMode>) {
397 if self.should_compile_successfully(pm) {
398 if !proc_res.status.success() {
399 self.fatal_proc_rec("test compilation failed although it shouldn't!", proc_res);
400 }
401 } else {
402 if proc_res.status.success() {
403 self.fatal_proc_rec(
404 &format!("{} test compiled successfully!", self.config.mode)[..],
405 proc_res,
406 );
407 }
408
409 self.check_correct_failure_status(proc_res);
410 }
411 }
412
413 fn run_cfail_test(&self) {
414 let pm = self.pass_mode();
415 let proc_res = self.compile_test(WillExecute::No, self.should_emit_metadata(pm));
416 self.check_if_test_should_compile(&proc_res, pm);
417 self.check_no_compiler_crash(&proc_res, self.props.should_ice);
418
419 let output_to_check = self.get_output(&proc_res);
420 let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
421 if !expected_errors.is_empty() {
422 if !self.props.error_patterns.is_empty() {
423 self.fatal("both error pattern and expected errors specified");
424 }
425 self.check_expected_errors(expected_errors, &proc_res);
426 } else {
427 self.check_error_patterns(&output_to_check, &proc_res, pm);
428 }
429 if self.props.should_ice {
430 match proc_res.status.code() {
431 Some(101) => (),
432 _ => self.fatal("expected ICE"),
433 }
434 }
435
436 self.check_forbid_output(&output_to_check, &proc_res);
437 }
438
439 fn run_rfail_test(&self) {
440 let pm = self.pass_mode();
441 let proc_res = self.compile_test(WillExecute::Yes, self.should_emit_metadata(pm));
442
443 if !proc_res.status.success() {
444 self.fatal_proc_rec("compilation failed!", &proc_res);
445 }
446
447 let proc_res = self.exec_compiled_test();
448
449 // The value our Makefile configures valgrind to return on failure
450 const VALGRIND_ERR: i32 = 100;
451 if proc_res.status.code() == Some(VALGRIND_ERR) {
452 self.fatal_proc_rec("run-fail test isn't valgrind-clean!", &proc_res);
453 }
454
455 let output_to_check = self.get_output(&proc_res);
456 self.check_correct_failure_status(&proc_res);
457 self.check_error_patterns(&output_to_check, &proc_res, pm);
458 }
459
460 fn get_output(&self, proc_res: &ProcRes) -> String {
461 if self.props.check_stdout {
462 format!("{}{}", proc_res.stdout, proc_res.stderr)
463 } else {
464 proc_res.stderr.clone()
465 }
466 }
467
468 fn check_correct_failure_status(&self, proc_res: &ProcRes) {
469 let expected_status = Some(self.props.failure_status);
470 let received_status = proc_res.status.code();
471
472 if expected_status != received_status {
473 self.fatal_proc_rec(
474 &format!(
475 "Error: expected failure status ({:?}) but received status {:?}.",
476 expected_status, received_status
477 ),
478 proc_res,
479 );
480 }
481 }
482
483 fn run_rpass_test(&self) {
484 let emit_metadata = self.should_emit_metadata(self.pass_mode());
485 let proc_res = self.compile_test(WillExecute::Yes, emit_metadata);
486
487 if !proc_res.status.success() {
488 self.fatal_proc_rec("compilation failed!", &proc_res);
489 }
490
491 // FIXME(#41968): Move this check to tidy?
492 let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
493 assert!(
494 expected_errors.is_empty(),
495 "run-pass tests with expected warnings should be moved to ui/"
496 );
497
498 let proc_res = self.exec_compiled_test();
499 if !proc_res.status.success() {
500 self.fatal_proc_rec("test run failed!", &proc_res);
501 }
502 }
503
504 fn run_valgrind_test(&self) {
505 assert!(self.revision.is_none(), "revisions not relevant here");
506
507 if self.config.valgrind_path.is_none() {
508 assert!(!self.config.force_valgrind);
509 return self.run_rpass_test();
510 }
511
512 let mut proc_res = self.compile_test(WillExecute::Yes, EmitMetadata::No);
513
514 if !proc_res.status.success() {
515 self.fatal_proc_rec("compilation failed!", &proc_res);
516 }
517
518 let mut new_config = self.config.clone();
519 new_config.runtool = new_config.valgrind_path.clone();
520 let new_cx = TestCx { config: &new_config, ..*self };
521 proc_res = new_cx.exec_compiled_test();
522
523 if !proc_res.status.success() {
524 self.fatal_proc_rec("test run failed!", &proc_res);
525 }
526 }
527
528 fn run_pretty_test(&self) {
529 if self.props.pp_exact.is_some() {
530 logv(self.config, "testing for exact pretty-printing".to_owned());
531 } else {
532 logv(self.config, "testing for converging pretty-printing".to_owned());
533 }
534
535 let rounds = match self.props.pp_exact {
536 Some(_) => 1,
537 None => 2,
538 };
539
540 let src = fs::read_to_string(&self.testpaths.file).unwrap();
541 let mut srcs = vec![src];
542
543 let mut round = 0;
544 while round < rounds {
545 logv(
546 self.config,
547 format!("pretty-printing round {} revision {:?}", round, self.revision),
548 );
549 let read_from =
550 if round == 0 { ReadFrom::Path } else { ReadFrom::Stdin(srcs[round].to_owned()) };
551
552 let proc_res = self.print_source(read_from, &self.props.pretty_mode);
553 if !proc_res.status.success() {
554 self.fatal_proc_rec(
555 &format!(
556 "pretty-printing failed in round {} revision {:?}",
557 round, self.revision
558 ),
559 &proc_res,
560 );
561 }
562
563 let ProcRes { stdout, .. } = proc_res;
564 srcs.push(stdout);
565 round += 1;
566 }
567
568 let mut expected = match self.props.pp_exact {
569 Some(ref file) => {
570 let filepath = self.testpaths.file.parent().unwrap().join(file);
571 fs::read_to_string(&filepath).unwrap()
572 }
573 None => srcs[srcs.len() - 2].clone(),
574 };
575 let mut actual = srcs[srcs.len() - 1].clone();
576
577 if self.props.pp_exact.is_some() {
578 // Now we have to care about line endings
579 let cr = "\r".to_owned();
580 actual = actual.replace(&cr, "");
581 expected = expected.replace(&cr, "");
582 }
583
584 self.compare_source(&expected, &actual);
585
586 // If we're only making sure that the output matches then just stop here
587 if self.props.pretty_compare_only {
588 return;
589 }
590
591 // Finally, let's make sure it actually appears to remain valid code
592 let proc_res = self.typecheck_source(actual);
593 if !proc_res.status.success() {
594 self.fatal_proc_rec("pretty-printed source does not typecheck", &proc_res);
595 }
596
597 if !self.props.pretty_expanded {
598 return;
599 }
600
601 // additionally, run `--pretty expanded` and try to build it.
602 let proc_res = self.print_source(ReadFrom::Path, "expanded");
603 if !proc_res.status.success() {
604 self.fatal_proc_rec("pretty-printing (expanded) failed", &proc_res);
605 }
606
607 let ProcRes { stdout: expanded_src, .. } = proc_res;
608 let proc_res = self.typecheck_source(expanded_src);
609 if !proc_res.status.success() {
610 self.fatal_proc_rec("pretty-printed source (expanded) does not typecheck", &proc_res);
611 }
612 }
613
614 fn print_source(&self, read_from: ReadFrom, pretty_type: &str) -> ProcRes {
615 let aux_dir = self.aux_output_dir_name();
616 let input: &str = match read_from {
617 ReadFrom::Stdin(_) => "-",
618 ReadFrom::Path => self.testpaths.file.to_str().unwrap(),
619 };
620
621 let mut rustc = Command::new(&self.config.rustc_path);
622 rustc
623 .arg(input)
624 .args(&["-Z", &format!("unpretty={}", pretty_type)])
625 .args(&["--target", &self.config.target])
626 .arg("-L")
627 .arg(&aux_dir)
628 .args(&self.props.compile_flags)
629 .envs(self.props.rustc_env.clone());
630 self.maybe_add_external_args(
631 &mut rustc,
632 self.split_maybe_args(&self.config.target_rustcflags),
633 );
634
635 let src = match read_from {
636 ReadFrom::Stdin(src) => Some(src),
637 ReadFrom::Path => None,
638 };
639
640 self.compose_and_run(
641 rustc,
642 self.config.compile_lib_path.to_str().unwrap(),
643 Some(aux_dir.to_str().unwrap()),
644 src,
645 )
646 }
647
648 fn compare_source(&self, expected: &str, actual: &str) {
649 if expected != actual {
650 self.fatal(&format!(
651 "pretty-printed source does not match expected source\n\
652 expected:\n\
653 ------------------------------------------\n\
654 {}\n\
655 ------------------------------------------\n\
656 actual:\n\
657 ------------------------------------------\n\
658 {}\n\
659 ------------------------------------------\n\
660 diff:\n\
661 ------------------------------------------\n\
662 {}\n",
663 expected,
664 actual,
665 write_diff(expected, actual, 3),
666 ));
667 }
668 }
669
670 fn set_revision_flags(&self, cmd: &mut Command) {
671 if let Some(revision) = self.revision {
672 // Normalize revisions to be lowercase and replace `-`s with `_`s.
673 // Otherwise the `--cfg` flag is not valid.
674 let normalized_revision = revision.to_lowercase().replace("-", "_");
675 cmd.args(&["--cfg", &normalized_revision]);
676 }
677 }
678
679 fn typecheck_source(&self, src: String) -> ProcRes {
680 let mut rustc = Command::new(&self.config.rustc_path);
681
682 let out_dir = self.output_base_name().with_extension("pretty-out");
683 let _ = fs::remove_dir_all(&out_dir);
684 create_dir_all(&out_dir).unwrap();
685
686 let target = if self.props.force_host { &*self.config.host } else { &*self.config.target };
687
688 let aux_dir = self.aux_output_dir_name();
689
690 rustc
691 .arg("-")
692 .arg("-Zno-codegen")
693 .arg("--out-dir")
694 .arg(&out_dir)
695 .arg(&format!("--target={}", target))
696 .arg("-L")
697 .arg(&self.config.build_base)
698 .arg("-L")
699 .arg(aux_dir);
700 self.set_revision_flags(&mut rustc);
701 self.maybe_add_external_args(
702 &mut rustc,
703 self.split_maybe_args(&self.config.target_rustcflags),
704 );
705 rustc.args(&self.props.compile_flags);
706
707 self.compose_and_run_compiler(rustc, Some(src))
708 }
709
710 fn run_debuginfo_test(&self) {
711 match self.config.debugger.unwrap() {
712 Debugger::Cdb => self.run_debuginfo_cdb_test(),
713 Debugger::Gdb => self.run_debuginfo_gdb_test(),
714 Debugger::Lldb => self.run_debuginfo_lldb_test(),
715 }
716 }
717
718 fn run_debuginfo_cdb_test(&self) {
719 assert!(self.revision.is_none(), "revisions not relevant here");
720
721 let config = Config {
722 target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
723 host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
724 ..self.config.clone()
725 };
726
727 let test_cx = TestCx { config: &config, ..*self };
728
729 test_cx.run_debuginfo_cdb_test_no_opt();
730 }
731
732 fn run_debuginfo_cdb_test_no_opt(&self) {
733 // compile test file (it should have 'compile-flags:-g' in the header)
734 let compile_result = self.compile_test(WillExecute::Yes, EmitMetadata::No);
735 if !compile_result.status.success() {
736 self.fatal_proc_rec("compilation failed!", &compile_result);
737 }
738
739 let exe_file = self.make_exe_name();
740
741 let prefixes = {
742 static PREFIXES: &[&str] = &["cdb", "cdbg"];
743 // No "native rust support" variation for CDB yet.
744 PREFIXES
745 };
746
747 // Parse debugger commands etc from test files
748 let DebuggerCommands { commands, check_lines, breakpoint_lines, .. } =
749 self.parse_debugger_commands(prefixes);
750
751 // https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-commands
752 let mut script_str = String::with_capacity(2048);
753 script_str.push_str("version\n"); // List CDB (and more) version info in test output
754 script_str.push_str(".nvlist\n"); // List loaded `*.natvis` files, bulk of custom MSVC debug
755
756 // Set breakpoints on every line that contains the string "#break"
757 let source_file_name = self.testpaths.file.file_name().unwrap().to_string_lossy();
758 for line in &breakpoint_lines {
759 script_str.push_str(&format!("bp `{}:{}`\n", source_file_name, line));
760 }
761
762 // Append the other `cdb-command:`s
763 for line in &commands {
764 script_str.push_str(line);
765 script_str.push_str("\n");
766 }
767
768 script_str.push_str("\nqq\n"); // Quit the debugger (including remote debugger, if any)
769
770 // Write the script into a file
771 debug!("script_str = {}", script_str);
772 self.dump_output_file(&script_str, "debugger.script");
773 let debugger_script = self.make_out_name("debugger.script");
774
775 let cdb_path = &self.config.cdb.as_ref().unwrap();
776 let mut cdb = Command::new(cdb_path);
777 cdb.arg("-lines") // Enable source line debugging.
778 .arg("-cf")
779 .arg(&debugger_script)
780 .arg(&exe_file);
781
782 let debugger_run_result = self.compose_and_run(
783 cdb,
784 self.config.run_lib_path.to_str().unwrap(),
785 None, // aux_path
786 None, // input
787 );
788
789 if !debugger_run_result.status.success() {
790 self.fatal_proc_rec("Error while running CDB", &debugger_run_result);
791 }
792
793 self.check_debugger_output(&debugger_run_result, &check_lines);
794 }
795
796 fn run_debuginfo_gdb_test(&self) {
797 assert!(self.revision.is_none(), "revisions not relevant here");
798
799 let config = Config {
800 target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
801 host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
802 ..self.config.clone()
803 };
804
805 let test_cx = TestCx { config: &config, ..*self };
806
807 test_cx.run_debuginfo_gdb_test_no_opt();
808 }
809
810 fn run_debuginfo_gdb_test_no_opt(&self) {
811 let prefixes = if self.config.gdb_native_rust {
812 // GDB with Rust
813 static PREFIXES: &[&str] = &["gdb", "gdbr"];
814 println!("NOTE: compiletest thinks it is using GDB with native rust support");
815 PREFIXES
816 } else {
817 // Generic GDB
818 static PREFIXES: &[&str] = &["gdb", "gdbg"];
819 println!("NOTE: compiletest thinks it is using GDB without native rust support");
820 PREFIXES
821 };
822
823 let DebuggerCommands { commands, check_lines, breakpoint_lines } =
824 self.parse_debugger_commands(prefixes);
825 let mut cmds = commands.join("\n");
826
827 // compile test file (it should have 'compile-flags:-g' in the header)
828 let compiler_run_result = self.compile_test(WillExecute::Yes, EmitMetadata::No);
829 if !compiler_run_result.status.success() {
830 self.fatal_proc_rec("compilation failed!", &compiler_run_result);
831 }
832
833 let exe_file = self.make_exe_name();
834
835 let debugger_run_result;
836 if is_android_gdb_target(&self.config.target) {
837 cmds = cmds.replace("run", "continue");
838
839 let tool_path = match self.config.android_cross_path.to_str() {
840 Some(x) => x.to_owned(),
841 None => self.fatal("cannot find android cross path"),
842 };
843
844 // write debugger script
845 let mut script_str = String::with_capacity(2048);
846 script_str.push_str(&format!("set charset {}\n", Self::charset()));
847 script_str.push_str(&format!("set sysroot {}\n", tool_path));
848 script_str.push_str(&format!("file {}\n", exe_file.to_str().unwrap()));
849 script_str.push_str("target remote :5039\n");
850 script_str.push_str(&format!(
851 "set solib-search-path \
852 ./{}/stage2/lib/rustlib/{}/lib/\n",
853 self.config.host, self.config.target
854 ));
855 for line in &breakpoint_lines {
856 script_str.push_str(
857 &format!(
858 "break {:?}:{}\n",
859 self.testpaths.file.file_name().unwrap().to_string_lossy(),
860 *line
861 )[..],
862 );
863 }
864 script_str.push_str(&cmds);
865 script_str.push_str("\nquit\n");
866
867 debug!("script_str = {}", script_str);
868 self.dump_output_file(&script_str, "debugger.script");
869
870 let adb_path = &self.config.adb_path;
871
872 Command::new(adb_path)
873 .arg("push")
874 .arg(&exe_file)
875 .arg(&self.config.adb_test_dir)
876 .status()
877 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path));
878
879 Command::new(adb_path)
880 .args(&["forward", "tcp:5039", "tcp:5039"])
881 .status()
882 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path));
883
884 let adb_arg = format!(
885 "export LD_LIBRARY_PATH={}; \
886 gdbserver{} :5039 {}/{}",
887 self.config.adb_test_dir.clone(),
888 if self.config.target.contains("aarch64") { "64" } else { "" },
889 self.config.adb_test_dir.clone(),
890 exe_file.file_name().unwrap().to_str().unwrap()
891 );
892
893 debug!("adb arg: {}", adb_arg);
894 let mut adb = Command::new(adb_path)
895 .args(&["shell", &adb_arg])
896 .stdout(Stdio::piped())
897 .stderr(Stdio::inherit())
898 .spawn()
899 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path));
900
901 // Wait for the gdbserver to print out "Listening on port ..."
902 // at which point we know that it's started and then we can
903 // execute the debugger below.
904 let mut stdout = BufReader::new(adb.stdout.take().unwrap());
905 let mut line = String::new();
906 loop {
907 line.truncate(0);
908 stdout.read_line(&mut line).unwrap();
909 if line.starts_with("Listening on port 5039") {
910 break;
911 }
912 }
913 drop(stdout);
914
915 let mut debugger_script = OsString::from("-command=");
916 debugger_script.push(self.make_out_name("debugger.script"));
917 let debugger_opts: &[&OsStr] =
918 &["-quiet".as_ref(), "-batch".as_ref(), "-nx".as_ref(), &debugger_script];
919
920 let gdb_path = self.config.gdb.as_ref().unwrap();
921 let Output { status, stdout, stderr } = Command::new(&gdb_path)
922 .args(debugger_opts)
923 .output()
924 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", gdb_path));
925 let cmdline = {
926 let mut gdb = Command::new(&format!("{}-gdb", self.config.target));
927 gdb.args(debugger_opts);
928 let cmdline = self.make_cmdline(&gdb, "");
929 logv(self.config, format!("executing {}", cmdline));
930 cmdline
931 };
932
933 debugger_run_result = ProcRes {
934 status,
935 stdout: String::from_utf8(stdout).unwrap(),
936 stderr: String::from_utf8(stderr).unwrap(),
937 cmdline,
938 };
939 if adb.kill().is_err() {
940 println!("Adb process is already finished.");
941 }
942 } else {
943 let rust_src_root =
944 self.config.find_rust_src_root().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 =
947 rust_src_root.join(rust_pp_module_rel_path).to_str().unwrap().to_owned();
948 // write debugger script
949 let mut script_str = String::with_capacity(2048);
950 script_str.push_str(&format!("set charset {}\n", Self::charset()));
951 script_str.push_str("show version\n");
952
953 match self.config.gdb_version {
954 Some(version) => {
955 println!("NOTE: compiletest thinks it is using GDB version {}", version);
956
957 if version > extract_gdb_version("7.4").unwrap() {
958 // Add the directory containing the pretty printers to
959 // GDB's script auto loading safe path
960 script_str.push_str(&format!(
961 "add-auto-load-safe-path {}\n",
962 rust_pp_module_abs_path.replace(r"\", r"\\")
963 ));
964 }
965 }
966 _ => {
967 println!(
968 "NOTE: compiletest does not know which version of \
969 GDB it is using"
970 );
971 }
972 }
973
974 // The following line actually doesn't have to do anything with
975 // pretty printing, it just tells GDB to print values on one line:
976 script_str.push_str("set print pretty off\n");
977
978 // Add the pretty printer directory to GDB's source-file search path
979 script_str
980 .push_str(&format!("directory {}\n", rust_pp_module_abs_path.replace(r"\", r"\\")));
981
982 // Load the target executable
983 script_str
984 .push_str(&format!("file {}\n", exe_file.to_str().unwrap().replace(r"\", r"\\")));
985
986 // Force GDB to print values in the Rust format.
987 if self.config.gdb_native_rust {
988 script_str.push_str("set language rust\n");
989 }
990
991 // Add line breakpoints
992 for line in &breakpoint_lines {
993 script_str.push_str(&format!(
994 "break '{}':{}\n",
995 self.testpaths.file.file_name().unwrap().to_string_lossy(),
996 *line
997 ));
998 }
999
1000 script_str.push_str(&cmds);
1001 script_str.push_str("\nquit\n");
1002
1003 debug!("script_str = {}", script_str);
1004 self.dump_output_file(&script_str, "debugger.script");
1005
1006 let mut debugger_script = OsString::from("-command=");
1007 debugger_script.push(self.make_out_name("debugger.script"));
1008
1009 let debugger_opts: &[&OsStr] =
1010 &["-quiet".as_ref(), "-batch".as_ref(), "-nx".as_ref(), &debugger_script];
1011
1012 let mut gdb = Command::new(self.config.gdb.as_ref().unwrap());
1013 gdb.args(debugger_opts).env("PYTHONPATH", rust_pp_module_abs_path);
1014
1015 debugger_run_result =
1016 self.compose_and_run(gdb, self.config.run_lib_path.to_str().unwrap(), None, None);
1017 }
1018
1019 if !debugger_run_result.status.success() {
1020 self.fatal_proc_rec("gdb failed to execute", &debugger_run_result);
1021 }
1022
1023 self.check_debugger_output(&debugger_run_result, &check_lines);
1024 }
1025
1026 fn run_debuginfo_lldb_test(&self) {
1027 assert!(self.revision.is_none(), "revisions not relevant here");
1028
1029 if self.config.lldb_python_dir.is_none() {
1030 self.fatal("Can't run LLDB test because LLDB's python path is not set.");
1031 }
1032
1033 let config = Config {
1034 target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
1035 host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
1036 ..self.config.clone()
1037 };
1038
1039 let test_cx = TestCx { config: &config, ..*self };
1040
1041 test_cx.run_debuginfo_lldb_test_no_opt();
1042 }
1043
1044 fn run_debuginfo_lldb_test_no_opt(&self) {
1045 // compile test file (it should have 'compile-flags:-g' in the header)
1046 let compile_result = self.compile_test(WillExecute::Yes, EmitMetadata::No);
1047 if !compile_result.status.success() {
1048 self.fatal_proc_rec("compilation failed!", &compile_result);
1049 }
1050
1051 let exe_file = self.make_exe_name();
1052
1053 match self.config.lldb_version {
1054 Some(ref version) => {
1055 println!("NOTE: compiletest thinks it is using LLDB version {}", version);
1056 }
1057 _ => {
1058 println!(
1059 "NOTE: compiletest does not know which version of \
1060 LLDB it is using"
1061 );
1062 }
1063 }
1064
1065 let prefixes = if self.config.lldb_native_rust {
1066 static PREFIXES: &[&str] = &["lldb", "lldbr"];
1067 println!("NOTE: compiletest thinks it is using LLDB with native rust support");
1068 PREFIXES
1069 } else {
1070 static PREFIXES: &[&str] = &["lldb", "lldbg"];
1071 println!("NOTE: compiletest thinks it is using LLDB without native rust support");
1072 PREFIXES
1073 };
1074
1075 // Parse debugger commands etc from test files
1076 let DebuggerCommands { commands, check_lines, breakpoint_lines, .. } =
1077 self.parse_debugger_commands(prefixes);
1078
1079 // Write debugger script:
1080 // We don't want to hang when calling `quit` while the process is still running
1081 let mut script_str = String::from("settings set auto-confirm true\n");
1082
1083 // Make LLDB emit its version, so we have it documented in the test output
1084 script_str.push_str("version\n");
1085
1086 // Switch LLDB into "Rust mode"
1087 let rust_src_root =
1088 self.config.find_rust_src_root().expect("Could not find Rust source root");
1089 let rust_pp_module_rel_path = Path::new("./src/etc/lldb_lookup.py");
1090 let rust_pp_module_abs_path =
1091 rust_src_root.join(rust_pp_module_rel_path).to_str().unwrap().to_owned();
1092
1093 let rust_type_regexes = vec![
1094 "^(alloc::([a-z_]+::)+)String$",
1095 "^&str$",
1096 "^&\\[.+\\]$",
1097 "^(std::ffi::([a-z_]+::)+)OsString$",
1098 "^(alloc::([a-z_]+::)+)Vec<.+>$",
1099 "^(alloc::([a-z_]+::)+)VecDeque<.+>$",
1100 "^(alloc::([a-z_]+::)+)BTreeSet<.+>$",
1101 "^(alloc::([a-z_]+::)+)BTreeMap<.+>$",
1102 "^(std::collections::([a-z_]+::)+)HashMap<.+>$",
1103 "^(std::collections::([a-z_]+::)+)HashSet<.+>$",
1104 "^(alloc::([a-z_]+::)+)Rc<.+>$",
1105 "^(alloc::([a-z_]+::)+)Arc<.+>$",
1106 "^(core::([a-z_]+::)+)Cell<.+>$",
1107 "^(core::([a-z_]+::)+)Ref<.+>$",
1108 "^(core::([a-z_]+::)+)RefMut<.+>$",
1109 "^(core::([a-z_]+::)+)RefCell<.+>$",
1110 ];
1111
1112 script_str
1113 .push_str(&format!("command script import {}\n", &rust_pp_module_abs_path[..])[..]);
1114 script_str.push_str("type synthetic add -l lldb_lookup.synthetic_lookup -x '.*' ");
1115 script_str.push_str("--category Rust\n");
1116 for type_regex in rust_type_regexes {
1117 script_str.push_str("type summary add -F lldb_lookup.summary_lookup -e -x -h ");
1118 script_str.push_str(&format!("'{}' ", type_regex));
1119 script_str.push_str("--category Rust\n");
1120 }
1121 script_str.push_str("type category enable Rust\n");
1122
1123 // Set breakpoints on every line that contains the string "#break"
1124 let source_file_name = self.testpaths.file.file_name().unwrap().to_string_lossy();
1125 for line in &breakpoint_lines {
1126 script_str.push_str(&format!(
1127 "breakpoint set --file '{}' --line {}\n",
1128 source_file_name, line
1129 ));
1130 }
1131
1132 // Append the other commands
1133 for line in &commands {
1134 script_str.push_str(line);
1135 script_str.push_str("\n");
1136 }
1137
1138 // Finally, quit the debugger
1139 script_str.push_str("\nquit\n");
1140
1141 // Write the script into a file
1142 debug!("script_str = {}", script_str);
1143 self.dump_output_file(&script_str, "debugger.script");
1144 let debugger_script = self.make_out_name("debugger.script");
1145
1146 // Let LLDB execute the script via lldb_batchmode.py
1147 let debugger_run_result = self.run_lldb(&exe_file, &debugger_script, &rust_src_root);
1148
1149 if !debugger_run_result.status.success() {
1150 self.fatal_proc_rec("Error while running LLDB", &debugger_run_result);
1151 }
1152
1153 self.check_debugger_output(&debugger_run_result, &check_lines);
1154 }
1155
1156 fn run_lldb(
1157 &self,
1158 test_executable: &Path,
1159 debugger_script: &Path,
1160 rust_src_root: &Path,
1161 ) -> ProcRes {
1162 // Prepare the lldb_batchmode which executes the debugger script
1163 let lldb_script_path = rust_src_root.join("src/etc/lldb_batchmode.py");
1164 self.cmd2procres(
1165 Command::new(&self.config.lldb_python)
1166 .arg(&lldb_script_path)
1167 .arg(test_executable)
1168 .arg(debugger_script)
1169 .env("PYTHONUNBUFFERED", "1") // Help debugging #78665
1170 .env("PYTHONPATH", self.config.lldb_python_dir.as_ref().unwrap()),
1171 )
1172 }
1173
1174 fn cmd2procres(&self, cmd: &mut Command) -> ProcRes {
1175 let (status, out, err) = match cmd.output() {
1176 Ok(Output { status, stdout, stderr }) => {
1177 (status, String::from_utf8(stdout).unwrap(), String::from_utf8(stderr).unwrap())
1178 }
1179 Err(e) => self.fatal(&format!(
1180 "Failed to setup Python process for \
1181 LLDB script: {}",
1182 e
1183 )),
1184 };
1185
1186 self.dump_output(&out, &err);
1187 ProcRes { status, stdout: out, stderr: err, cmdline: format!("{:?}", cmd) }
1188 }
1189
1190 fn parse_debugger_commands(&self, debugger_prefixes: &[&str]) -> DebuggerCommands {
1191 let directives = debugger_prefixes
1192 .iter()
1193 .map(|prefix| (format!("{}-command", prefix), format!("{}-check", prefix)))
1194 .collect::<Vec<_>>();
1195
1196 let mut breakpoint_lines = vec![];
1197 let mut commands = vec![];
1198 let mut check_lines = vec![];
1199 let mut counter = 1;
1200 let reader = BufReader::new(File::open(&self.testpaths.file).unwrap());
1201 for line in reader.lines() {
1202 match line {
1203 Ok(line) => {
1204 let line =
1205 if line.starts_with("//") { line[2..].trim_start() } else { line.as_str() };
1206
1207 if line.contains("#break") {
1208 breakpoint_lines.push(counter);
1209 }
1210
1211 for &(ref command_directive, ref check_directive) in &directives {
1212 self.config
1213 .parse_name_value_directive(&line, command_directive)
1214 .map(|cmd| commands.push(cmd));
1215
1216 self.config
1217 .parse_name_value_directive(&line, check_directive)
1218 .map(|cmd| check_lines.push(cmd));
1219 }
1220 }
1221 Err(e) => self.fatal(&format!("Error while parsing debugger commands: {}", e)),
1222 }
1223 counter += 1;
1224 }
1225
1226 DebuggerCommands { commands, check_lines, breakpoint_lines }
1227 }
1228
1229 fn cleanup_debug_info_options(&self, options: &Option<String>) -> Option<String> {
1230 if options.is_none() {
1231 return None;
1232 }
1233
1234 // Remove options that are either unwanted (-O) or may lead to duplicates due to RUSTFLAGS.
1235 let options_to_remove = ["-O".to_owned(), "-g".to_owned(), "--debuginfo".to_owned()];
1236 let new_options = self
1237 .split_maybe_args(options)
1238 .into_iter()
1239 .filter(|x| !options_to_remove.contains(x))
1240 .collect::<Vec<String>>();
1241
1242 Some(new_options.join(" "))
1243 }
1244
1245 fn maybe_add_external_args(&self, cmd: &mut Command, args: Vec<String>) {
1246 // Filter out the arguments that should not be added by runtest here.
1247 //
1248 // Notable use-cases are: do not add our optimisation flag if
1249 // `compile-flags: -Copt-level=x` and similar for debug-info level as well.
1250 const OPT_FLAGS: &[&str] = &["-O", "-Copt-level=", /*-C<space>*/ "opt-level="];
1251 const DEBUG_FLAGS: &[&str] = &["-g", "-Cdebuginfo=", /*-C<space>*/ "debuginfo="];
1252
1253 // FIXME: ideally we would "just" check the `cmd` itself, but it does not allow inspecting
1254 // its arguments. They need to be collected separately. For now I cannot be bothered to
1255 // implement this the "right" way.
1256 let have_opt_flag =
1257 self.props.compile_flags.iter().any(|arg| OPT_FLAGS.iter().any(|f| arg.starts_with(f)));
1258 let have_debug_flag = self
1259 .props
1260 .compile_flags
1261 .iter()
1262 .any(|arg| DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)));
1263
1264 for arg in args {
1265 if OPT_FLAGS.iter().any(|f| arg.starts_with(f)) && have_opt_flag {
1266 continue;
1267 }
1268 if DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)) && have_debug_flag {
1269 continue;
1270 }
1271 cmd.arg(arg);
1272 }
1273 }
1274
1275 fn check_debugger_output(&self, debugger_run_result: &ProcRes, check_lines: &[String]) {
1276 let num_check_lines = check_lines.len();
1277
1278 let mut check_line_index = 0;
1279 for line in debugger_run_result.stdout.lines() {
1280 if check_line_index >= num_check_lines {
1281 break;
1282 }
1283
1284 if check_single_line(line, &(check_lines[check_line_index])[..]) {
1285 check_line_index += 1;
1286 }
1287 }
1288 if check_line_index != num_check_lines && num_check_lines > 0 {
1289 self.fatal_proc_rec(
1290 &format!("line not found in debugger output: {}", check_lines[check_line_index]),
1291 debugger_run_result,
1292 );
1293 }
1294
1295 fn check_single_line(line: &str, check_line: &str) -> bool {
1296 // Allow check lines to leave parts unspecified (e.g., uninitialized
1297 // bits in the wrong case of an enum) with the notation "[...]".
1298 let line = line.trim();
1299 let check_line = check_line.trim();
1300 let can_start_anywhere = check_line.starts_with("[...]");
1301 let can_end_anywhere = check_line.ends_with("[...]");
1302
1303 let check_fragments: Vec<&str> =
1304 check_line.split("[...]").filter(|frag| !frag.is_empty()).collect();
1305 if check_fragments.is_empty() {
1306 return true;
1307 }
1308
1309 let (mut rest, first_fragment) = if can_start_anywhere {
1310 match line.find(check_fragments[0]) {
1311 Some(pos) => (&line[pos + check_fragments[0].len()..], 1),
1312 None => return false,
1313 }
1314 } else {
1315 (line, 0)
1316 };
1317
1318 for current_fragment in &check_fragments[first_fragment..] {
1319 match rest.find(current_fragment) {
1320 Some(pos) => {
1321 rest = &rest[pos + current_fragment.len()..];
1322 }
1323 None => return false,
1324 }
1325 }
1326
1327 if !can_end_anywhere && !rest.is_empty() {
1328 return false;
1329 }
1330
1331 true
1332 }
1333 }
1334
1335 fn check_error_patterns(
1336 &self,
1337 output_to_check: &str,
1338 proc_res: &ProcRes,
1339 pm: Option<PassMode>,
1340 ) {
1341 debug!("check_error_patterns");
1342 if self.props.error_patterns.is_empty() {
1343 if pm.is_some() {
1344 // FIXME(#65865)
1345 return;
1346 } else {
1347 self.fatal(&format!(
1348 "no error pattern specified in {:?}",
1349 self.testpaths.file.display()
1350 ));
1351 }
1352 }
1353
1354 let mut missing_patterns: Vec<String> = Vec::new();
1355
1356 for pattern in &self.props.error_patterns {
1357 if output_to_check.contains(pattern.trim()) {
1358 debug!("found error pattern {}", pattern);
1359 } else {
1360 missing_patterns.push(pattern.to_string());
1361 }
1362 }
1363
1364 if missing_patterns.is_empty() {
1365 return;
1366 }
1367
1368 if missing_patterns.len() == 1 {
1369 self.fatal_proc_rec(
1370 &format!("error pattern '{}' not found!", missing_patterns[0]),
1371 proc_res,
1372 );
1373 } else {
1374 for pattern in missing_patterns {
1375 self.error(&format!("error pattern '{}' not found!", pattern));
1376 }
1377 self.fatal_proc_rec("multiple error patterns not found", proc_res);
1378 }
1379 }
1380
1381 fn check_no_compiler_crash(&self, proc_res: &ProcRes, should_ice: bool) {
1382 match proc_res.status.code() {
1383 Some(101) if !should_ice => {
1384 self.fatal_proc_rec("compiler encountered internal error", proc_res)
1385 }
1386 None => self.fatal_proc_rec("compiler terminated by signal", proc_res),
1387 _ => (),
1388 }
1389 }
1390
1391 fn check_forbid_output(&self, output_to_check: &str, proc_res: &ProcRes) {
1392 for pat in &self.props.forbid_output {
1393 if output_to_check.contains(pat) {
1394 self.fatal_proc_rec("forbidden pattern found in compiler output", proc_res);
1395 }
1396 }
1397 }
1398
1399 fn check_expected_errors(&self, expected_errors: Vec<errors::Error>, proc_res: &ProcRes) {
1400 debug!(
1401 "check_expected_errors: expected_errors={:?} proc_res.status={:?}",
1402 expected_errors, proc_res.status
1403 );
1404 if proc_res.status.success()
1405 && expected_errors.iter().any(|x| x.kind == Some(ErrorKind::Error))
1406 {
1407 self.fatal_proc_rec("process did not return an error status", proc_res);
1408 }
1409
1410 // On Windows, keep all '\' path separators to match the paths reported in the JSON output
1411 // from the compiler
1412 let os_file_name = self.testpaths.file.display().to_string();
1413
1414 // on windows, translate all '\' path separators to '/'
1415 let file_name = format!("{}", self.testpaths.file.display()).replace(r"\", "/");
1416
1417 // If the testcase being checked contains at least one expected "help"
1418 // message, then we'll ensure that all "help" messages are expected.
1419 // Otherwise, all "help" messages reported by the compiler will be ignored.
1420 // This logic also applies to "note" messages.
1421 let expect_help = expected_errors.iter().any(|ee| ee.kind == Some(ErrorKind::Help));
1422 let expect_note = expected_errors.iter().any(|ee| ee.kind == Some(ErrorKind::Note));
1423
1424 // Parse the JSON output from the compiler and extract out the messages.
1425 let actual_errors = json::parse_output(&os_file_name, &proc_res.stderr, proc_res);
1426 let mut unexpected = Vec::new();
1427 let mut found = vec![false; expected_errors.len()];
1428 for actual_error in &actual_errors {
1429 let opt_index =
1430 expected_errors.iter().enumerate().position(|(index, expected_error)| {
1431 !found[index]
1432 && actual_error.line_num == expected_error.line_num
1433 && (expected_error.kind.is_none()
1434 || actual_error.kind == expected_error.kind)
1435 && actual_error.msg.contains(&expected_error.msg)
1436 });
1437
1438 match opt_index {
1439 Some(index) => {
1440 // found a match, everybody is happy
1441 assert!(!found[index]);
1442 found[index] = true;
1443 }
1444
1445 None => {
1446 if self.is_unexpected_compiler_message(actual_error, expect_help, expect_note) {
1447 self.error(&format!(
1448 "{}:{}: unexpected {}: '{}'",
1449 file_name,
1450 actual_error.line_num,
1451 actual_error
1452 .kind
1453 .as_ref()
1454 .map_or(String::from("message"), |k| k.to_string()),
1455 actual_error.msg
1456 ));
1457 unexpected.push(actual_error);
1458 }
1459 }
1460 }
1461 }
1462
1463 let mut not_found = Vec::new();
1464 // anything not yet found is a problem
1465 for (index, expected_error) in expected_errors.iter().enumerate() {
1466 if !found[index] {
1467 self.error(&format!(
1468 "{}:{}: expected {} not found: {}",
1469 file_name,
1470 expected_error.line_num,
1471 expected_error.kind.as_ref().map_or("message".into(), |k| k.to_string()),
1472 expected_error.msg
1473 ));
1474 not_found.push(expected_error);
1475 }
1476 }
1477
1478 if !unexpected.is_empty() || !not_found.is_empty() {
1479 self.error(&format!(
1480 "{} unexpected errors found, {} expected errors not found",
1481 unexpected.len(),
1482 not_found.len()
1483 ));
1484 println!("status: {}\ncommand: {}", proc_res.status, proc_res.cmdline);
1485 if !unexpected.is_empty() {
1486 println!("unexpected errors (from JSON output): {:#?}\n", unexpected);
1487 }
1488 if !not_found.is_empty() {
1489 println!("not found errors (from test file): {:#?}\n", not_found);
1490 }
1491 panic!();
1492 }
1493 }
1494
1495 /// Returns `true` if we should report an error about `actual_error`,
1496 /// which did not match any of the expected error. We always require
1497 /// errors/warnings to be explicitly listed, but only require
1498 /// helps/notes if there are explicit helps/notes given.
1499 fn is_unexpected_compiler_message(
1500 &self,
1501 actual_error: &Error,
1502 expect_help: bool,
1503 expect_note: bool,
1504 ) -> bool {
1505 match actual_error.kind {
1506 Some(ErrorKind::Help) => expect_help,
1507 Some(ErrorKind::Note) => expect_note,
1508 Some(ErrorKind::Error) | Some(ErrorKind::Warning) => true,
1509 Some(ErrorKind::Suggestion) | None => false,
1510 }
1511 }
1512
1513 fn should_emit_metadata(&self, pm: Option<PassMode>) -> EmitMetadata {
1514 match (pm, self.props.fail_mode, self.config.mode) {
1515 (Some(PassMode::Check), ..) | (_, Some(FailMode::Check), Ui) => EmitMetadata::Yes,
1516 _ => EmitMetadata::No,
1517 }
1518 }
1519
1520 fn compile_test(&self, will_execute: WillExecute, emit_metadata: EmitMetadata) -> ProcRes {
1521 self.compile_test_general(will_execute, emit_metadata, self.props.local_pass_mode())
1522 }
1523
1524 fn compile_test_general(
1525 &self,
1526 will_execute: WillExecute,
1527 emit_metadata: EmitMetadata,
1528 local_pm: Option<PassMode>,
1529 ) -> ProcRes {
1530 // Only use `make_exe_name` when the test ends up being executed.
1531 let output_file = match will_execute {
1532 WillExecute::Yes => TargetLocation::ThisFile(self.make_exe_name()),
1533 WillExecute::No => TargetLocation::ThisDirectory(self.output_base_dir()),
1534 };
1535
1536 let allow_unused = match self.config.mode {
1537 Ui => {
1538 // UI tests tend to have tons of unused code as
1539 // it's just testing various pieces of the compile, but we don't
1540 // want to actually assert warnings about all this code. Instead
1541 // let's just ignore unused code warnings by defaults and tests
1542 // can turn it back on if needed.
1543 if !self.is_rustdoc()
1544 // Note that we use the local pass mode here as we don't want
1545 // to set unused to allow if we've overridden the pass mode
1546 // via command line flags.
1547 && local_pm != Some(PassMode::Run)
1548 {
1549 AllowUnused::Yes
1550 } else {
1551 AllowUnused::No
1552 }
1553 }
1554 _ => AllowUnused::No,
1555 };
1556
1557 let mut rustc =
1558 self.make_compile_args(&self.testpaths.file, output_file, emit_metadata, allow_unused);
1559
1560 rustc.arg("-L").arg(&self.aux_output_dir_name());
1561
1562 self.compose_and_run_compiler(rustc, None)
1563 }
1564
1565 fn document(&self, out_dir: &Path) -> ProcRes {
1566 if self.props.build_aux_docs {
1567 for rel_ab in &self.props.aux_builds {
1568 let aux_testpaths = self.compute_aux_test_paths(rel_ab);
1569 let aux_props =
1570 self.props.from_aux_file(&aux_testpaths.file, self.revision, self.config);
1571 let aux_cx = TestCx {
1572 config: self.config,
1573 props: &aux_props,
1574 testpaths: &aux_testpaths,
1575 revision: self.revision,
1576 };
1577 // Create the directory for the stdout/stderr files.
1578 create_dir_all(aux_cx.output_base_dir()).unwrap();
1579 let auxres = aux_cx.document(out_dir);
1580 if !auxres.status.success() {
1581 return auxres;
1582 }
1583 }
1584 }
1585
1586 let aux_dir = self.aux_output_dir_name();
1587
1588 let rustdoc_path = self.config.rustdoc_path.as_ref().expect("--rustdoc-path passed");
1589 let mut rustdoc = Command::new(rustdoc_path);
1590
1591 rustdoc
1592 .arg("-L")
1593 .arg(self.config.run_lib_path.to_str().unwrap())
1594 .arg("-L")
1595 .arg(aux_dir)
1596 .arg("-o")
1597 .arg(out_dir)
1598 .arg(&self.testpaths.file)
1599 .args(&self.props.compile_flags);
1600
1601 if self.config.mode == RustdocJson {
1602 rustdoc.arg("--output-format").arg("json");
1603 }
1604
1605 if let Some(ref linker) = self.config.linker {
1606 rustdoc.arg(format!("-Clinker={}", linker));
1607 }
1608
1609 self.compose_and_run_compiler(rustdoc, None)
1610 }
1611
1612 fn exec_compiled_test(&self) -> ProcRes {
1613 let env = &self.props.exec_env;
1614
1615 let proc_res = match &*self.config.target {
1616 // This is pretty similar to below, we're transforming:
1617 //
1618 // program arg1 arg2
1619 //
1620 // into
1621 //
1622 // remote-test-client run program 2 support-lib.so support-lib2.so arg1 arg2
1623 //
1624 // The test-client program will upload `program` to the emulator
1625 // along with all other support libraries listed (in this case
1626 // `support-lib.so` and `support-lib2.so`. It will then execute
1627 // the program on the emulator with the arguments specified
1628 // (in the environment we give the process) and then report back
1629 // the same result.
1630 _ if self.config.remote_test_client.is_some() => {
1631 let aux_dir = self.aux_output_dir_name();
1632 let ProcArgs { prog, args } = self.make_run_args();
1633 let mut support_libs = Vec::new();
1634 if let Ok(entries) = aux_dir.read_dir() {
1635 for entry in entries {
1636 let entry = entry.unwrap();
1637 if !entry.path().is_file() {
1638 continue;
1639 }
1640 support_libs.push(entry.path());
1641 }
1642 }
1643 let mut test_client =
1644 Command::new(self.config.remote_test_client.as_ref().unwrap());
1645 test_client
1646 .args(&["run", &support_libs.len().to_string(), &prog])
1647 .args(support_libs)
1648 .args(args)
1649 .envs(env.clone());
1650 self.compose_and_run(
1651 test_client,
1652 self.config.run_lib_path.to_str().unwrap(),
1653 Some(aux_dir.to_str().unwrap()),
1654 None,
1655 )
1656 }
1657 _ if self.config.target.contains("vxworks") => {
1658 let aux_dir = self.aux_output_dir_name();
1659 let ProcArgs { prog, args } = self.make_run_args();
1660 let mut wr_run = Command::new("wr-run");
1661 wr_run.args(&[&prog]).args(args).envs(env.clone());
1662 self.compose_and_run(
1663 wr_run,
1664 self.config.run_lib_path.to_str().unwrap(),
1665 Some(aux_dir.to_str().unwrap()),
1666 None,
1667 )
1668 }
1669 _ => {
1670 let aux_dir = self.aux_output_dir_name();
1671 let ProcArgs { prog, args } = self.make_run_args();
1672 let mut program = Command::new(&prog);
1673 program.args(args).current_dir(&self.output_base_dir()).envs(env.clone());
1674 self.compose_and_run(
1675 program,
1676 self.config.run_lib_path.to_str().unwrap(),
1677 Some(aux_dir.to_str().unwrap()),
1678 None,
1679 )
1680 }
1681 };
1682
1683 if proc_res.status.success() {
1684 // delete the executable after running it to save space.
1685 // it is ok if the deletion failed.
1686 let _ = fs::remove_file(self.make_exe_name());
1687 }
1688
1689 proc_res
1690 }
1691
1692 /// For each `aux-build: foo/bar` annotation, we check to find the
1693 /// file in a `auxiliary` directory relative to the test itself.
1694 fn compute_aux_test_paths(&self, rel_ab: &str) -> TestPaths {
1695 let test_ab = self
1696 .testpaths
1697 .file
1698 .parent()
1699 .expect("test file path has no parent")
1700 .join("auxiliary")
1701 .join(rel_ab);
1702 if !test_ab.exists() {
1703 self.fatal(&format!("aux-build `{}` source not found", test_ab.display()))
1704 }
1705
1706 TestPaths {
1707 file: test_ab,
1708 relative_dir: self
1709 .testpaths
1710 .relative_dir
1711 .join(self.output_testname_unique())
1712 .join("auxiliary")
1713 .join(rel_ab)
1714 .parent()
1715 .expect("aux-build path has no parent")
1716 .to_path_buf(),
1717 }
1718 }
1719
1720 fn is_vxworks_pure_static(&self) -> bool {
1721 if self.config.target.contains("vxworks") {
1722 match env::var("RUST_VXWORKS_TEST_DYLINK") {
1723 Ok(s) => s != "1",
1724 _ => true,
1725 }
1726 } else {
1727 false
1728 }
1729 }
1730
1731 fn is_vxworks_pure_dynamic(&self) -> bool {
1732 self.config.target.contains("vxworks") && !self.is_vxworks_pure_static()
1733 }
1734
1735 fn build_all_auxiliary(&self, rustc: &mut Command) -> PathBuf {
1736 let aux_dir = self.aux_output_dir_name();
1737
1738 if !self.props.aux_builds.is_empty() {
1739 let _ = fs::remove_dir_all(&aux_dir);
1740 create_dir_all(&aux_dir).unwrap();
1741 }
1742
1743 for rel_ab in &self.props.aux_builds {
1744 self.build_auxiliary(rel_ab, &aux_dir);
1745 }
1746
1747 for (aux_name, aux_path) in &self.props.aux_crates {
1748 let is_dylib = self.build_auxiliary(&aux_path, &aux_dir);
1749 let lib_name =
1750 get_lib_name(&aux_path.trim_end_matches(".rs").replace('-', "_"), is_dylib);
1751 rustc.arg("--extern").arg(format!("{}={}/{}", aux_name, aux_dir.display(), lib_name));
1752 }
1753
1754 aux_dir
1755 }
1756
1757 fn compose_and_run_compiler(&self, mut rustc: Command, input: Option<String>) -> ProcRes {
1758 let aux_dir = self.build_all_auxiliary(&mut rustc);
1759 self.props.unset_rustc_env.clone().iter().fold(&mut rustc, |rustc, v| rustc.env_remove(v));
1760 rustc.envs(self.props.rustc_env.clone());
1761 self.compose_and_run(
1762 rustc,
1763 self.config.compile_lib_path.to_str().unwrap(),
1764 Some(aux_dir.to_str().unwrap()),
1765 input,
1766 )
1767 }
1768
1769 /// Builds an aux dependency.
1770 ///
1771 /// Returns whether or not it is a dylib.
1772 fn build_auxiliary(&self, source_path: &str, aux_dir: &Path) -> bool {
1773 let aux_testpaths = self.compute_aux_test_paths(source_path);
1774 let aux_props = self.props.from_aux_file(&aux_testpaths.file, self.revision, self.config);
1775 let aux_output = TargetLocation::ThisDirectory(self.aux_output_dir_name());
1776 let aux_cx = TestCx {
1777 config: self.config,
1778 props: &aux_props,
1779 testpaths: &aux_testpaths,
1780 revision: self.revision,
1781 };
1782 // Create the directory for the stdout/stderr files.
1783 create_dir_all(aux_cx.output_base_dir()).unwrap();
1784 let input_file = &aux_testpaths.file;
1785 let mut aux_rustc =
1786 aux_cx.make_compile_args(input_file, aux_output, EmitMetadata::No, AllowUnused::No);
1787
1788 for key in &aux_props.unset_rustc_env {
1789 aux_rustc.env_remove(key);
1790 }
1791 aux_rustc.envs(aux_props.rustc_env.clone());
1792
1793 let (dylib, crate_type) = if aux_props.no_prefer_dynamic {
1794 (true, None)
1795 } else if self.config.target.contains("emscripten")
1796 || (self.config.target.contains("musl")
1797 && !aux_props.force_host
1798 && !self.config.host.contains("musl"))
1799 || self.config.target.contains("wasm32")
1800 || self.config.target.contains("nvptx")
1801 || self.is_vxworks_pure_static()
1802 || self.config.target.contains("sgx")
1803 {
1804 // We primarily compile all auxiliary libraries as dynamic libraries
1805 // to avoid code size bloat and large binaries as much as possible
1806 // for the test suite (otherwise including libstd statically in all
1807 // executables takes up quite a bit of space).
1808 //
1809 // For targets like MUSL or Emscripten, however, there is no support for
1810 // dynamic libraries so we just go back to building a normal library. Note,
1811 // however, that for MUSL if the library is built with `force_host` then
1812 // it's ok to be a dylib as the host should always support dylibs.
1813 (false, Some("lib"))
1814 } else {
1815 (true, Some("dylib"))
1816 };
1817
1818 if let Some(crate_type) = crate_type {
1819 aux_rustc.args(&["--crate-type", crate_type]);
1820 }
1821
1822 aux_rustc.arg("-L").arg(&aux_dir);
1823
1824 let auxres = aux_cx.compose_and_run(
1825 aux_rustc,
1826 aux_cx.config.compile_lib_path.to_str().unwrap(),
1827 Some(aux_dir.to_str().unwrap()),
1828 None,
1829 );
1830 if !auxres.status.success() {
1831 self.fatal_proc_rec(
1832 &format!(
1833 "auxiliary build of {:?} failed to compile: ",
1834 aux_testpaths.file.display()
1835 ),
1836 &auxres,
1837 );
1838 }
1839 dylib
1840 }
1841
1842 fn compose_and_run(
1843 &self,
1844 mut command: Command,
1845 lib_path: &str,
1846 aux_path: Option<&str>,
1847 input: Option<String>,
1848 ) -> ProcRes {
1849 let cmdline = {
1850 let cmdline = self.make_cmdline(&command, lib_path);
1851 logv(self.config, format!("executing {}", cmdline));
1852 cmdline
1853 };
1854
1855 command.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::piped());
1856
1857 // Need to be sure to put both the lib_path and the aux path in the dylib
1858 // search path for the child.
1859 let mut path =
1860 env::split_paths(&env::var_os(dylib_env_var()).unwrap_or_default()).collect::<Vec<_>>();
1861 if let Some(p) = aux_path {
1862 path.insert(0, PathBuf::from(p))
1863 }
1864 path.insert(0, PathBuf::from(lib_path));
1865
1866 // Add the new dylib search path var
1867 let newpath = env::join_paths(&path).unwrap();
1868 command.env(dylib_env_var(), newpath);
1869
1870 let mut child = disable_error_reporting(|| command.spawn())
1871 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", &command));
1872 if let Some(input) = input {
1873 child.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap();
1874 }
1875
1876 let Output { status, stdout, stderr } =
1877 read2_abbreviated(child).expect("failed to read output");
1878
1879 let result = ProcRes {
1880 status,
1881 stdout: String::from_utf8_lossy(&stdout).into_owned(),
1882 stderr: String::from_utf8_lossy(&stderr).into_owned(),
1883 cmdline,
1884 };
1885
1886 self.dump_output(&result.stdout, &result.stderr);
1887
1888 result
1889 }
1890
1891 fn is_rustdoc(&self) -> bool {
1892 self.config.src_base.ends_with("rustdoc-ui")
1893 || self.config.src_base.ends_with("rustdoc-js")
1894 || self.config.src_base.ends_with("rustdoc-json")
1895 }
1896
1897 fn make_compile_args(
1898 &self,
1899 input_file: &Path,
1900 output_file: TargetLocation,
1901 emit_metadata: EmitMetadata,
1902 allow_unused: AllowUnused,
1903 ) -> Command {
1904 let is_aux = input_file.components().map(|c| c.as_os_str()).any(|c| c == "auxiliary");
1905 let is_rustdoc = self.is_rustdoc() && !is_aux;
1906 let mut rustc = if !is_rustdoc {
1907 Command::new(&self.config.rustc_path)
1908 } else {
1909 Command::new(&self.config.rustdoc_path.clone().expect("no rustdoc built yet"))
1910 };
1911 // FIXME Why is -L here?
1912 rustc.arg(input_file); //.arg("-L").arg(&self.config.build_base);
1913
1914 // Use a single thread for efficiency and a deterministic error message order
1915 rustc.arg("-Zthreads=1");
1916
1917 // Optionally prevent default --target if specified in test compile-flags.
1918 let custom_target = self.props.compile_flags.iter().any(|x| x.starts_with("--target"));
1919
1920 if !custom_target {
1921 let target =
1922 if self.props.force_host { &*self.config.host } else { &*self.config.target };
1923
1924 rustc.arg(&format!("--target={}", target));
1925 }
1926 self.set_revision_flags(&mut rustc);
1927
1928 if !is_rustdoc {
1929 if let Some(ref incremental_dir) = self.props.incremental_dir {
1930 rustc.args(&["-C", &format!("incremental={}", incremental_dir.display())]);
1931 rustc.args(&["-Z", "incremental-verify-ich"]);
1932 }
1933
1934 if self.config.mode == CodegenUnits {
1935 rustc.args(&["-Z", "human_readable_cgu_names"]);
1936 }
1937 }
1938
1939 match self.config.mode {
1940 Incremental => {
1941 // If we are extracting and matching errors in the new
1942 // fashion, then you want JSON mode. Old-skool error
1943 // patterns still match the raw compiler output.
1944 if self.props.error_patterns.is_empty() {
1945 rustc.args(&["--error-format", "json"]);
1946 }
1947 rustc.arg("-Zui-testing");
1948 rustc.arg("-Zdeduplicate-diagnostics=no");
1949 }
1950 Ui => {
1951 if !self.props.compile_flags.iter().any(|s| s.starts_with("--error-format")) {
1952 rustc.args(&["--error-format", "json"]);
1953 }
1954 rustc.arg("-Zui-testing");
1955 rustc.arg("-Zdeduplicate-diagnostics=no");
1956 rustc.arg("-Zemit-future-incompat-report");
1957 }
1958 MirOpt => {
1959 rustc.args(&[
1960 "-Zdump-mir=all",
1961 "-Zmir-opt-level=3",
1962 "-Zvalidate-mir",
1963 "-Zdump-mir-exclude-pass-number",
1964 ]);
1965
1966 let mir_dump_dir = self.get_mir_dump_dir();
1967 let _ = fs::remove_dir_all(&mir_dump_dir);
1968 create_dir_all(mir_dump_dir.as_path()).unwrap();
1969 let mut dir_opt = "-Zdump-mir-dir=".to_string();
1970 dir_opt.push_str(mir_dump_dir.to_str().unwrap());
1971 debug!("dir_opt: {:?}", dir_opt);
1972
1973 rustc.arg(dir_opt);
1974 }
1975 RunPassValgrind | Pretty | DebugInfo | Codegen | Rustdoc | RustdocJson | RunMake
1976 | CodegenUnits | JsDocTest | Assembly => {
1977 // do not use JSON output
1978 }
1979 }
1980
1981 if let (false, EmitMetadata::Yes) = (is_rustdoc, emit_metadata) {
1982 rustc.args(&["--emit", "metadata"]);
1983 }
1984
1985 if !is_rustdoc {
1986 if self.config.target == "wasm32-unknown-unknown" || self.is_vxworks_pure_static() {
1987 // rustc.arg("-g"); // get any backtrace at all on errors
1988 } else if !self.props.no_prefer_dynamic {
1989 rustc.args(&["-C", "prefer-dynamic"]);
1990 }
1991 }
1992
1993 match output_file {
1994 TargetLocation::ThisFile(path) => {
1995 rustc.arg("-o").arg(path);
1996 }
1997 TargetLocation::ThisDirectory(path) => {
1998 if is_rustdoc {
1999 // `rustdoc` uses `-o` for the output directory.
2000 rustc.arg("-o").arg(path);
2001 } else {
2002 rustc.arg("--out-dir").arg(path);
2003 }
2004 }
2005 }
2006
2007 match self.config.compare_mode {
2008 Some(CompareMode::Nll) => {
2009 rustc.args(&["-Zborrowck=mir"]);
2010 }
2011 Some(CompareMode::Polonius) => {
2012 rustc.args(&["-Zpolonius", "-Zborrowck=mir"]);
2013 }
2014 Some(CompareMode::Chalk) => {
2015 rustc.args(&["-Zchalk"]);
2016 }
2017 Some(CompareMode::SplitDwarf) => {
2018 rustc.args(&["-Csplit-debuginfo=unpacked", "-Zunstable-options"]);
2019 }
2020 Some(CompareMode::SplitDwarfSingle) => {
2021 rustc.args(&["-Csplit-debuginfo=packed", "-Zunstable-options"]);
2022 }
2023 None => {}
2024 }
2025
2026 // Add `-A unused` before `config` flags and in-test (`props`) flags, so that they can
2027 // overwrite this.
2028 if let AllowUnused::Yes = allow_unused {
2029 rustc.args(&["-A", "unused"]);
2030 }
2031
2032 if self.props.force_host {
2033 self.maybe_add_external_args(
2034 &mut rustc,
2035 self.split_maybe_args(&self.config.host_rustcflags),
2036 );
2037 } else {
2038 self.maybe_add_external_args(
2039 &mut rustc,
2040 self.split_maybe_args(&self.config.target_rustcflags),
2041 );
2042 if !is_rustdoc {
2043 if let Some(ref linker) = self.config.linker {
2044 rustc.arg(format!("-Clinker={}", linker));
2045 }
2046 }
2047 }
2048
2049 // Use dynamic musl for tests because static doesn't allow creating dylibs
2050 if self.config.host.contains("musl") || self.is_vxworks_pure_dynamic() {
2051 rustc.arg("-Ctarget-feature=-crt-static");
2052 }
2053
2054 rustc.args(&self.props.compile_flags);
2055
2056 rustc
2057 }
2058
2059 fn make_exe_name(&self) -> PathBuf {
2060 // Using a single letter here to keep the path length down for
2061 // Windows. Some test names get very long. rustc creates `rcgu`
2062 // files with the module name appended to it which can more than
2063 // double the length.
2064 let mut f = self.output_base_dir().join("a");
2065 // FIXME: This is using the host architecture exe suffix, not target!
2066 if self.config.target.contains("emscripten") {
2067 f = f.with_extra_extension("js");
2068 } else if self.config.target.contains("wasm32") {
2069 f = f.with_extra_extension("wasm");
2070 } else if !env::consts::EXE_SUFFIX.is_empty() {
2071 f = f.with_extra_extension(env::consts::EXE_SUFFIX);
2072 }
2073 f
2074 }
2075
2076 fn make_run_args(&self) -> ProcArgs {
2077 // If we've got another tool to run under (valgrind),
2078 // then split apart its command
2079 let mut args = self.split_maybe_args(&self.config.runtool);
2080
2081 // If this is emscripten, then run tests under nodejs
2082 if self.config.target.contains("emscripten") {
2083 if let Some(ref p) = self.config.nodejs {
2084 args.push(p.clone());
2085 } else {
2086 self.fatal("no NodeJS binary found (--nodejs)");
2087 }
2088 // If this is otherwise wasm, then run tests under nodejs with our
2089 // shim
2090 } else if self.config.target.contains("wasm32") {
2091 if let Some(ref p) = self.config.nodejs {
2092 args.push(p.clone());
2093 } else {
2094 self.fatal("no NodeJS binary found (--nodejs)");
2095 }
2096
2097 let src = self
2098 .config
2099 .src_base
2100 .parent()
2101 .unwrap() // chop off `ui`
2102 .parent()
2103 .unwrap() // chop off `test`
2104 .parent()
2105 .unwrap(); // chop off `src`
2106 args.push(src.join("src/etc/wasm32-shim.js").display().to_string());
2107 }
2108
2109 let exe_file = self.make_exe_name();
2110
2111 // FIXME (#9639): This needs to handle non-utf8 paths
2112 args.push(exe_file.to_str().unwrap().to_owned());
2113
2114 // Add the arguments in the run_flags directive
2115 args.extend(self.split_maybe_args(&self.props.run_flags));
2116
2117 let prog = args.remove(0);
2118 ProcArgs { prog, args }
2119 }
2120
2121 fn split_maybe_args(&self, argstr: &Option<String>) -> Vec<String> {
2122 match *argstr {
2123 Some(ref s) => s
2124 .split(' ')
2125 .filter_map(|s| {
2126 if s.chars().all(|c| c.is_whitespace()) { None } else { Some(s.to_owned()) }
2127 })
2128 .collect(),
2129 None => Vec::new(),
2130 }
2131 }
2132
2133 fn make_cmdline(&self, command: &Command, libpath: &str) -> String {
2134 use crate::util;
2135
2136 // Linux and mac don't require adjusting the library search path
2137 if cfg!(unix) {
2138 format!("{:?}", command)
2139 } else {
2140 // Build the LD_LIBRARY_PATH variable as it would be seen on the command line
2141 // for diagnostic purposes
2142 fn lib_path_cmd_prefix(path: &str) -> String {
2143 format!("{}=\"{}\"", util::lib_path_env_var(), util::make_new_path(path))
2144 }
2145
2146 format!("{} {:?}", lib_path_cmd_prefix(libpath), command)
2147 }
2148 }
2149
2150 fn dump_output(&self, out: &str, err: &str) {
2151 let revision = if let Some(r) = self.revision { format!("{}.", r) } else { String::new() };
2152
2153 self.dump_output_file(out, &format!("{}out", revision));
2154 self.dump_output_file(err, &format!("{}err", revision));
2155 self.maybe_dump_to_stdout(out, err);
2156 }
2157
2158 fn dump_output_file(&self, out: &str, extension: &str) {
2159 let outfile = self.make_out_name(extension);
2160 fs::write(&outfile, out).unwrap();
2161 }
2162
2163 /// Creates a filename for output with the given extension.
2164 /// E.g., `/.../testname.revision.mode/testname.extension`.
2165 fn make_out_name(&self, extension: &str) -> PathBuf {
2166 self.output_base_name().with_extension(extension)
2167 }
2168
2169 /// Gets the directory where auxiliary files are written.
2170 /// E.g., `/.../testname.revision.mode/auxiliary/`.
2171 fn aux_output_dir_name(&self) -> PathBuf {
2172 self.output_base_dir()
2173 .join("auxiliary")
2174 .with_extra_extension(self.config.mode.disambiguator())
2175 }
2176
2177 /// Generates a unique name for the test, such as `testname.revision.mode`.
2178 fn output_testname_unique(&self) -> PathBuf {
2179 output_testname_unique(self.config, self.testpaths, self.safe_revision())
2180 }
2181
2182 /// The revision, ignored for incremental compilation since it wants all revisions in
2183 /// the same directory.
2184 fn safe_revision(&self) -> Option<&str> {
2185 if self.config.mode == Incremental { None } else { self.revision }
2186 }
2187
2188 /// Gets the absolute path to the directory where all output for the given
2189 /// test/revision should reside.
2190 /// E.g., `/path/to/build/host-triple/test/ui/relative/testname.revision.mode/`.
2191 fn output_base_dir(&self) -> PathBuf {
2192 output_base_dir(self.config, self.testpaths, self.safe_revision())
2193 }
2194
2195 /// Gets the absolute path to the base filename used as output for the given
2196 /// test/revision.
2197 /// E.g., `/.../relative/testname.revision.mode/testname`.
2198 fn output_base_name(&self) -> PathBuf {
2199 output_base_name(self.config, self.testpaths, self.safe_revision())
2200 }
2201
2202 fn maybe_dump_to_stdout(&self, out: &str, err: &str) {
2203 if self.config.verbose {
2204 println!("------{}------------------------------", "stdout");
2205 println!("{}", out);
2206 println!("------{}------------------------------", "stderr");
2207 println!("{}", err);
2208 println!("------------------------------------------");
2209 }
2210 }
2211
2212 fn error(&self, err: &str) {
2213 match self.revision {
2214 Some(rev) => println!("\nerror in revision `{}`: {}", rev, err),
2215 None => println!("\nerror: {}", err),
2216 }
2217 }
2218
2219 fn fatal(&self, err: &str) -> ! {
2220 self.error(err);
2221 error!("fatal error, panic: {:?}", err);
2222 panic!("fatal error");
2223 }
2224
2225 fn fatal_proc_rec(&self, err: &str, proc_res: &ProcRes) -> ! {
2226 self.error(err);
2227 proc_res.fatal(None, || ());
2228 }
2229
2230 fn fatal_proc_rec_with_ctx(
2231 &self,
2232 err: &str,
2233 proc_res: &ProcRes,
2234 on_failure: impl FnOnce(Self),
2235 ) -> ! {
2236 self.error(err);
2237 proc_res.fatal(None, || on_failure(*self));
2238 }
2239
2240 // codegen tests (using FileCheck)
2241
2242 fn compile_test_and_save_ir(&self) -> ProcRes {
2243 let aux_dir = self.aux_output_dir_name();
2244
2245 let output_file = TargetLocation::ThisDirectory(self.output_base_dir());
2246 let input_file = &self.testpaths.file;
2247 let mut rustc =
2248 self.make_compile_args(input_file, output_file, EmitMetadata::No, AllowUnused::No);
2249 rustc.arg("-L").arg(aux_dir).arg("--emit=llvm-ir");
2250
2251 self.compose_and_run_compiler(rustc, None)
2252 }
2253
2254 fn compile_test_and_save_assembly(&self) -> (ProcRes, PathBuf) {
2255 // This works with both `--emit asm` (as default output name for the assembly)
2256 // and `ptx-linker` because the latter can write output at requested location.
2257 let output_path = self.output_base_name().with_extension("s");
2258
2259 let output_file = TargetLocation::ThisFile(output_path.clone());
2260 let input_file = &self.testpaths.file;
2261 let mut rustc =
2262 self.make_compile_args(input_file, output_file, EmitMetadata::No, AllowUnused::No);
2263
2264 rustc.arg("-L").arg(self.aux_output_dir_name());
2265
2266 match self.props.assembly_output.as_ref().map(AsRef::as_ref) {
2267 Some("emit-asm") => {
2268 rustc.arg("--emit=asm");
2269 }
2270
2271 Some("ptx-linker") => {
2272 // No extra flags needed.
2273 }
2274
2275 Some(_) => self.fatal("unknown 'assembly-output' header"),
2276 None => self.fatal("missing 'assembly-output' header"),
2277 }
2278
2279 (self.compose_and_run_compiler(rustc, None), output_path)
2280 }
2281
2282 fn verify_with_filecheck(&self, output: &Path) -> ProcRes {
2283 let mut filecheck = Command::new(self.config.llvm_filecheck.as_ref().unwrap());
2284 filecheck.arg("--input-file").arg(output).arg(&self.testpaths.file);
2285 // It would be more appropriate to make most of the arguments configurable through
2286 // a comment-attribute similar to `compile-flags`. For example, --check-prefixes is a very
2287 // useful flag.
2288 //
2289 // For now, though…
2290 if let Some(rev) = self.revision {
2291 let prefixes = format!("CHECK,{}", rev);
2292 filecheck.args(&["--check-prefixes", &prefixes]);
2293 }
2294 self.compose_and_run(filecheck, "", None, None)
2295 }
2296
2297 fn run_codegen_test(&self) {
2298 if self.config.llvm_filecheck.is_none() {
2299 self.fatal("missing --llvm-filecheck");
2300 }
2301
2302 let proc_res = self.compile_test_and_save_ir();
2303 if !proc_res.status.success() {
2304 self.fatal_proc_rec("compilation failed!", &proc_res);
2305 }
2306
2307 let output_path = self.output_base_name().with_extension("ll");
2308 let proc_res = self.verify_with_filecheck(&output_path);
2309 if !proc_res.status.success() {
2310 self.fatal_proc_rec("verification with 'FileCheck' failed", &proc_res);
2311 }
2312 }
2313
2314 fn run_assembly_test(&self) {
2315 if self.config.llvm_filecheck.is_none() {
2316 self.fatal("missing --llvm-filecheck");
2317 }
2318
2319 let (proc_res, output_path) = self.compile_test_and_save_assembly();
2320 if !proc_res.status.success() {
2321 self.fatal_proc_rec("compilation failed!", &proc_res);
2322 }
2323
2324 let proc_res = self.verify_with_filecheck(&output_path);
2325 if !proc_res.status.success() {
2326 self.fatal_proc_rec("verification with 'FileCheck' failed", &proc_res);
2327 }
2328 }
2329
2330 fn charset() -> &'static str {
2331 // FreeBSD 10.1 defaults to GDB 6.1.1 which doesn't support "auto" charset
2332 if cfg!(target_os = "freebsd") { "ISO-8859-1" } else { "UTF-8" }
2333 }
2334
2335 fn run_rustdoc_test(&self) {
2336 assert!(self.revision.is_none(), "revisions not relevant here");
2337
2338 let out_dir = self.output_base_dir();
2339 let _ = fs::remove_dir_all(&out_dir);
2340 create_dir_all(&out_dir).unwrap();
2341
2342 let proc_res = self.document(&out_dir);
2343 if !proc_res.status.success() {
2344 self.fatal_proc_rec("rustdoc failed!", &proc_res);
2345 }
2346
2347 if self.props.check_test_line_numbers_match {
2348 self.check_rustdoc_test_option(proc_res);
2349 } else {
2350 let root = self.config.find_rust_src_root().unwrap();
2351 let res = self.cmd2procres(
2352 Command::new(&self.config.docck_python)
2353 .arg(root.join("src/etc/htmldocck.py"))
2354 .arg(&out_dir)
2355 .arg(&self.testpaths.file),
2356 );
2357 if !res.status.success() {
2358 self.fatal_proc_rec_with_ctx("htmldocck failed!", &res, |mut this| {
2359 this.compare_to_default_rustdoc(&out_dir)
2360 });
2361 }
2362 }
2363 }
2364
2365 fn compare_to_default_rustdoc(&mut self, out_dir: &Path) {
2366 println!("info: generating a diff against nightly rustdoc");
2367
2368 let suffix =
2369 self.safe_revision().map_or("nightly".into(), |path| path.to_owned() + "-nightly");
2370 let compare_dir = output_base_dir(self.config, self.testpaths, Some(&suffix));
2371 // Don't give an error if the directory didn't already exist
2372 let _ = fs::remove_dir_all(&compare_dir);
2373 create_dir_all(&compare_dir).unwrap();
2374
2375 // We need to create a new struct for the lifetimes on `config` to work.
2376 let new_rustdoc = TestCx {
2377 config: &Config {
2378 // FIXME: use beta or a user-specified rustdoc instead of
2379 // hardcoding the default toolchain
2380 rustdoc_path: Some("rustdoc".into()),
2381 // Needed for building auxiliary docs below
2382 rustc_path: "rustc".into(),
2383 ..self.config.clone()
2384 },
2385 ..*self
2386 };
2387
2388 let output_file = TargetLocation::ThisDirectory(new_rustdoc.aux_output_dir_name());
2389 let mut rustc = new_rustdoc.make_compile_args(
2390 &new_rustdoc.testpaths.file,
2391 output_file,
2392 EmitMetadata::No,
2393 AllowUnused::Yes,
2394 );
2395 rustc.arg("-L").arg(&new_rustdoc.aux_output_dir_name());
2396 new_rustdoc.build_all_auxiliary(&mut rustc);
2397
2398 let proc_res = new_rustdoc.document(&compare_dir);
2399 if !proc_res.status.success() {
2400 eprintln!("failed to run nightly rustdoc");
2401 return;
2402 }
2403
2404 #[rustfmt::skip]
2405 let tidy_args = [
2406 "--indent", "yes",
2407 "--indent-spaces", "2",
2408 "--wrap", "0",
2409 "--show-warnings", "no",
2410 "--markup", "yes",
2411 "--quiet", "yes",
2412 "-modify",
2413 ];
2414 let tidy_dir = |dir| {
2415 for entry in walkdir::WalkDir::new(dir) {
2416 let entry = entry.expect("failed to read file");
2417 if entry.file_type().is_file()
2418 && entry.path().extension().and_then(|p| p.to_str()) == Some("html".into())
2419 {
2420 let status =
2421 Command::new("tidy").args(&tidy_args).arg(entry.path()).status().unwrap();
2422 // `tidy` returns 1 if it modified the file.
2423 assert!(status.success() || status.code() == Some(1));
2424 }
2425 }
2426 };
2427 if self.config.has_tidy {
2428 tidy_dir(out_dir);
2429 tidy_dir(&compare_dir);
2430 }
2431
2432 let pager = {
2433 let output = Command::new("git").args(&["config", "--get", "core.pager"]).output().ok();
2434 output.and_then(|out| {
2435 if out.status.success() {
2436 Some(String::from_utf8(out.stdout).expect("invalid UTF8 in git pager"))
2437 } else {
2438 None
2439 }
2440 })
2441 };
2442 let mut diff = Command::new("diff");
2443 // diff recursively, showing context, and excluding .css files
2444 diff.args(&["-u", "-r", "-x", "*.css"]).args(&[&compare_dir, out_dir]);
2445
2446 let output = if let Some(pager) = pager {
2447 let diff_pid = diff.stdout(Stdio::piped()).spawn().expect("failed to run `diff`");
2448 let pager = pager.trim();
2449 if self.config.verbose {
2450 eprintln!("using pager {}", pager);
2451 }
2452 let output = Command::new(pager)
2453 // disable paging; we want this to be non-interactive
2454 .env("PAGER", "")
2455 .stdin(diff_pid.stdout.unwrap())
2456 // Capture output and print it explicitly so it will in turn be
2457 // captured by libtest.
2458 .output()
2459 .unwrap();
2460 assert!(output.status.success());
2461 output
2462 } else {
2463 eprintln!("warning: no pager configured, falling back to `diff --color`");
2464 eprintln!(
2465 "help: try configuring a git pager (e.g. `delta`) with `git config --global core.pager delta`"
2466 );
2467 let output = diff.arg("--color").output().unwrap();
2468 assert!(output.status.success() || output.status.code() == Some(1));
2469 output
2470 };
2471 println!("{}", String::from_utf8_lossy(&output.stdout));
2472 eprintln!("{}", String::from_utf8_lossy(&output.stderr));
2473 }
2474
2475 fn run_rustdoc_json_test(&self) {
2476 //FIXME: Add bless option.
2477
2478 assert!(self.revision.is_none(), "revisions not relevant here");
2479
2480 let out_dir = self.output_base_dir();
2481 let _ = fs::remove_dir_all(&out_dir);
2482 create_dir_all(&out_dir).unwrap();
2483
2484 let proc_res = self.document(&out_dir);
2485 if !proc_res.status.success() {
2486 self.fatal_proc_rec("rustdoc failed!", &proc_res);
2487 }
2488
2489 let root = self.config.find_rust_src_root().unwrap();
2490 let mut json_out = out_dir.join(self.testpaths.file.file_stem().unwrap());
2491 json_out.set_extension("json");
2492 let res = self.cmd2procres(
2493 Command::new(self.config.jsondocck_path.as_ref().unwrap())
2494 .arg("--doc-dir")
2495 .arg(root.join(&out_dir))
2496 .arg("--template")
2497 .arg(&self.testpaths.file),
2498 );
2499
2500 if !res.status.success() {
2501 self.fatal_proc_rec("jsondocck failed!", &res)
2502 }
2503
2504 let mut json_out = out_dir.join(self.testpaths.file.file_stem().unwrap());
2505 json_out.set_extension("json");
2506 let res = self.cmd2procres(
2507 Command::new(&self.config.docck_python)
2508 .arg(root.join("src/etc/check_missing_items.py"))
2509 .arg(&json_out),
2510 );
2511
2512 if !res.status.success() {
2513 self.fatal_proc_rec("check_missing_items failed!", &res);
2514 }
2515 }
2516
2517 fn get_lines<P: AsRef<Path>>(
2518 &self,
2519 path: &P,
2520 mut other_files: Option<&mut Vec<String>>,
2521 ) -> Vec<usize> {
2522 let content = fs::read_to_string(&path).unwrap();
2523 let mut ignore = false;
2524 content
2525 .lines()
2526 .enumerate()
2527 .filter_map(|(line_nb, line)| {
2528 if (line.trim_start().starts_with("pub mod ")
2529 || line.trim_start().starts_with("mod "))
2530 && line.ends_with(';')
2531 {
2532 if let Some(ref mut other_files) = other_files {
2533 other_files.push(line.rsplit("mod ").next().unwrap().replace(";", ""));
2534 }
2535 None
2536 } else {
2537 let sline = line.split("///").last().unwrap_or("");
2538 let line = sline.trim_start();
2539 if line.starts_with("```") {
2540 if ignore {
2541 ignore = false;
2542 None
2543 } else {
2544 ignore = true;
2545 Some(line_nb + 1)
2546 }
2547 } else {
2548 None
2549 }
2550 }
2551 })
2552 .collect()
2553 }
2554
2555 fn check_rustdoc_test_option(&self, res: ProcRes) {
2556 let mut other_files = Vec::new();
2557 let mut files: HashMap<String, Vec<usize>> = HashMap::new();
2558 let cwd = env::current_dir().unwrap();
2559 files.insert(
2560 self.testpaths
2561 .file
2562 .strip_prefix(&cwd)
2563 .unwrap_or(&self.testpaths.file)
2564 .to_str()
2565 .unwrap()
2566 .replace('\\', "/"),
2567 self.get_lines(&self.testpaths.file, Some(&mut other_files)),
2568 );
2569 for other_file in other_files {
2570 let mut path = self.testpaths.file.clone();
2571 path.set_file_name(&format!("{}.rs", other_file));
2572 files.insert(
2573 path.strip_prefix(&cwd).unwrap_or(&path).to_str().unwrap().replace('\\', "/"),
2574 self.get_lines(&path, None),
2575 );
2576 }
2577
2578 let mut tested = 0;
2579 for _ in res.stdout.split('\n').filter(|s| s.starts_with("test ")).inspect(|s| {
2580 let tmp: Vec<&str> = s.split(" - ").collect();
2581 if tmp.len() == 2 {
2582 let path = tmp[0].rsplit("test ").next().unwrap();
2583 if let Some(ref mut v) = files.get_mut(&path.replace('\\', "/")) {
2584 tested += 1;
2585 let mut iter = tmp[1].split("(line ");
2586 iter.next();
2587 let line = iter
2588 .next()
2589 .unwrap_or(")")
2590 .split(')')
2591 .next()
2592 .unwrap_or("0")
2593 .parse()
2594 .unwrap_or(0);
2595 if let Ok(pos) = v.binary_search(&line) {
2596 v.remove(pos);
2597 } else {
2598 self.fatal_proc_rec(
2599 &format!("Not found doc test: \"{}\" in \"{}\":{:?}", s, path, v),
2600 &res,
2601 );
2602 }
2603 }
2604 }
2605 }) {}
2606 if tested == 0 {
2607 self.fatal_proc_rec(&format!("No test has been found... {:?}", files), &res);
2608 } else {
2609 for (entry, v) in &files {
2610 if !v.is_empty() {
2611 self.fatal_proc_rec(
2612 &format!(
2613 "Not found test at line{} \"{}\":{:?}",
2614 if v.len() > 1 { "s" } else { "" },
2615 entry,
2616 v
2617 ),
2618 &res,
2619 );
2620 }
2621 }
2622 }
2623 }
2624
2625 fn run_codegen_units_test(&self) {
2626 assert!(self.revision.is_none(), "revisions not relevant here");
2627
2628 let proc_res = self.compile_test(WillExecute::No, EmitMetadata::No);
2629
2630 if !proc_res.status.success() {
2631 self.fatal_proc_rec("compilation failed!", &proc_res);
2632 }
2633
2634 self.check_no_compiler_crash(&proc_res, self.props.should_ice);
2635
2636 const PREFIX: &str = "MONO_ITEM ";
2637 const CGU_MARKER: &str = "@@";
2638
2639 let actual: Vec<MonoItem> = proc_res
2640 .stdout
2641 .lines()
2642 .filter(|line| line.starts_with(PREFIX))
2643 .map(|line| str_to_mono_item(line, true))
2644 .collect();
2645
2646 let expected: Vec<MonoItem> = errors::load_errors(&self.testpaths.file, None)
2647 .iter()
2648 .map(|e| str_to_mono_item(&e.msg[..], false))
2649 .collect();
2650
2651 let mut missing = Vec::new();
2652 let mut wrong_cgus = Vec::new();
2653
2654 for expected_item in &expected {
2655 let actual_item_with_same_name = actual.iter().find(|ti| ti.name == expected_item.name);
2656
2657 if let Some(actual_item) = actual_item_with_same_name {
2658 if !expected_item.codegen_units.is_empty() &&
2659 // Also check for codegen units
2660 expected_item.codegen_units != actual_item.codegen_units
2661 {
2662 wrong_cgus.push((expected_item.clone(), actual_item.clone()));
2663 }
2664 } else {
2665 missing.push(expected_item.string.clone());
2666 }
2667 }
2668
2669 let unexpected: Vec<_> = actual
2670 .iter()
2671 .filter(|acgu| !expected.iter().any(|ecgu| acgu.name == ecgu.name))
2672 .map(|acgu| acgu.string.clone())
2673 .collect();
2674
2675 if !missing.is_empty() {
2676 missing.sort();
2677
2678 println!("\nThese items should have been contained but were not:\n");
2679
2680 for item in &missing {
2681 println!("{}", item);
2682 }
2683
2684 println!("\n");
2685 }
2686
2687 if !unexpected.is_empty() {
2688 let sorted = {
2689 let mut sorted = unexpected.clone();
2690 sorted.sort();
2691 sorted
2692 };
2693
2694 println!("\nThese items were contained but should not have been:\n");
2695
2696 for item in sorted {
2697 println!("{}", item);
2698 }
2699
2700 println!("\n");
2701 }
2702
2703 if !wrong_cgus.is_empty() {
2704 wrong_cgus.sort_by_key(|pair| pair.0.name.clone());
2705 println!("\nThe following items were assigned to wrong codegen units:\n");
2706
2707 for &(ref expected_item, ref actual_item) in &wrong_cgus {
2708 println!("{}", expected_item.name);
2709 println!(" expected: {}", codegen_units_to_str(&expected_item.codegen_units));
2710 println!(" actual: {}", codegen_units_to_str(&actual_item.codegen_units));
2711 println!();
2712 }
2713 }
2714
2715 if !(missing.is_empty() && unexpected.is_empty() && wrong_cgus.is_empty()) {
2716 panic!();
2717 }
2718
2719 #[derive(Clone, Eq, PartialEq)]
2720 struct MonoItem {
2721 name: String,
2722 codegen_units: HashSet<String>,
2723 string: String,
2724 }
2725
2726 // [MONO_ITEM] name [@@ (cgu)+]
2727 fn str_to_mono_item(s: &str, cgu_has_crate_disambiguator: bool) -> MonoItem {
2728 let s = if s.starts_with(PREFIX) { (&s[PREFIX.len()..]).trim() } else { s.trim() };
2729
2730 let full_string = format!("{}{}", PREFIX, s);
2731
2732 let parts: Vec<&str> =
2733 s.split(CGU_MARKER).map(str::trim).filter(|s| !s.is_empty()).collect();
2734
2735 let name = parts[0].trim();
2736
2737 let cgus = if parts.len() > 1 {
2738 let cgus_str = parts[1];
2739
2740 cgus_str
2741 .split(' ')
2742 .map(str::trim)
2743 .filter(|s| !s.is_empty())
2744 .map(|s| {
2745 if cgu_has_crate_disambiguator {
2746 remove_crate_disambiguators_from_set_of_cgu_names(s)
2747 } else {
2748 s.to_string()
2749 }
2750 })
2751 .collect()
2752 } else {
2753 HashSet::new()
2754 };
2755
2756 MonoItem { name: name.to_owned(), codegen_units: cgus, string: full_string }
2757 }
2758
2759 fn codegen_units_to_str(cgus: &HashSet<String>) -> String {
2760 let mut cgus: Vec<_> = cgus.iter().collect();
2761 cgus.sort();
2762
2763 let mut string = String::new();
2764 for cgu in cgus {
2765 string.push_str(&cgu[..]);
2766 string.push_str(" ");
2767 }
2768
2769 string
2770 }
2771
2772 // Given a cgu-name-prefix of the form <crate-name>.<crate-disambiguator> or
2773 // the form <crate-name1>.<crate-disambiguator1>-in-<crate-name2>.<crate-disambiguator2>,
2774 // remove all crate-disambiguators.
2775 fn remove_crate_disambiguator_from_cgu(cgu: &str) -> String {
2776 lazy_static! {
2777 static ref RE: Regex =
2778 Regex::new(r"^[^\.]+(?P<d1>\.[[:alnum:]]+)(-in-[^\.]+(?P<d2>\.[[:alnum:]]+))?")
2779 .unwrap();
2780 }
2781
2782 let captures =
2783 RE.captures(cgu).unwrap_or_else(|| panic!("invalid cgu name encountered: {}", cgu));
2784
2785 let mut new_name = cgu.to_owned();
2786
2787 if let Some(d2) = captures.name("d2") {
2788 new_name.replace_range(d2.start()..d2.end(), "");
2789 }
2790
2791 let d1 = captures.name("d1").unwrap();
2792 new_name.replace_range(d1.start()..d1.end(), "");
2793
2794 new_name
2795 }
2796
2797 // The name of merged CGUs is constructed as the names of the original
2798 // CGUs joined with "--". This function splits such composite CGU names
2799 // and handles each component individually.
2800 fn remove_crate_disambiguators_from_set_of_cgu_names(cgus: &str) -> String {
2801 cgus.split("--")
2802 .map(|cgu| remove_crate_disambiguator_from_cgu(cgu))
2803 .collect::<Vec<_>>()
2804 .join("--")
2805 }
2806 }
2807
2808 fn init_incremental_test(&self) {
2809 // (See `run_incremental_test` for an overview of how incremental tests work.)
2810
2811 // Before any of the revisions have executed, create the
2812 // incremental workproduct directory. Delete any old
2813 // incremental work products that may be there from prior
2814 // runs.
2815 let incremental_dir = self.incremental_dir();
2816 if incremental_dir.exists() {
2817 // Canonicalizing the path will convert it to the //?/ format
2818 // on Windows, which enables paths longer than 260 character
2819 let canonicalized = incremental_dir.canonicalize().unwrap();
2820 fs::remove_dir_all(canonicalized).unwrap();
2821 }
2822 fs::create_dir_all(&incremental_dir).unwrap();
2823
2824 if self.config.verbose {
2825 print!("init_incremental_test: incremental_dir={}", incremental_dir.display());
2826 }
2827 }
2828
2829 fn run_incremental_test(&self) {
2830 // Basic plan for a test incremental/foo/bar.rs:
2831 // - load list of revisions rpass1, cfail2, rpass3
2832 // - each should begin with `rpass`, `cfail`, or `rfail`
2833 // - if `rpass`, expect compile and execution to succeed
2834 // - if `cfail`, expect compilation to fail
2835 // - if `rfail`, expect execution to fail
2836 // - create a directory build/foo/bar.incremental
2837 // - compile foo/bar.rs with -C incremental=.../foo/bar.incremental and -C rpass1
2838 // - because name of revision starts with "rpass", expect success
2839 // - compile foo/bar.rs with -C incremental=.../foo/bar.incremental and -C cfail2
2840 // - because name of revision starts with "cfail", expect an error
2841 // - load expected errors as usual, but filter for those that end in `[rfail2]`
2842 // - compile foo/bar.rs with -C incremental=.../foo/bar.incremental and -C rpass3
2843 // - because name of revision starts with "rpass", expect success
2844 // - execute build/foo/bar.exe and save output
2845 //
2846 // FIXME -- use non-incremental mode as an oracle? That doesn't apply
2847 // to #[rustc_dirty] and clean tests I guess
2848
2849 let revision = self.revision.expect("incremental tests require a list of revisions");
2850
2851 // Incremental workproduct directory should have already been created.
2852 let incremental_dir = self.incremental_dir();
2853 assert!(incremental_dir.exists(), "init_incremental_test failed to create incremental dir");
2854
2855 // Add an extra flag pointing at the incremental directory.
2856 let mut revision_props = self.props.clone();
2857 revision_props.incremental_dir = Some(incremental_dir);
2858
2859 let revision_cx = TestCx {
2860 config: self.config,
2861 props: &revision_props,
2862 testpaths: self.testpaths,
2863 revision: self.revision,
2864 };
2865
2866 if self.config.verbose {
2867 print!("revision={:?} revision_props={:#?}", revision, revision_props);
2868 }
2869
2870 if revision.starts_with("rpass") {
2871 if revision_cx.props.should_ice {
2872 revision_cx.fatal("can only use should-ice in cfail tests");
2873 }
2874 revision_cx.run_rpass_test();
2875 } else if revision.starts_with("rfail") {
2876 if revision_cx.props.should_ice {
2877 revision_cx.fatal("can only use should-ice in cfail tests");
2878 }
2879 revision_cx.run_rfail_test();
2880 } else if revision.starts_with("cfail") {
2881 revision_cx.run_cfail_test();
2882 } else {
2883 revision_cx.fatal("revision name must begin with rpass, rfail, or cfail");
2884 }
2885 }
2886
2887 /// Directory where incremental work products are stored.
2888 fn incremental_dir(&self) -> PathBuf {
2889 self.output_base_name().with_extension("inc")
2890 }
2891
2892 fn run_rmake_test(&self) {
2893 let cwd = env::current_dir().unwrap();
2894 let src_root = self.config.src_base.parent().unwrap().parent().unwrap().parent().unwrap();
2895 let src_root = cwd.join(&src_root);
2896
2897 let tmpdir = cwd.join(self.output_base_name());
2898 if tmpdir.exists() {
2899 self.aggressive_rm_rf(&tmpdir).unwrap();
2900 }
2901 create_dir_all(&tmpdir).unwrap();
2902
2903 let host = &self.config.host;
2904 let make = if host.contains("dragonfly")
2905 || host.contains("freebsd")
2906 || host.contains("netbsd")
2907 || host.contains("openbsd")
2908 {
2909 "gmake"
2910 } else {
2911 "make"
2912 };
2913
2914 let mut cmd = Command::new(make);
2915 cmd.current_dir(&self.testpaths.file)
2916 .stdout(Stdio::piped())
2917 .stderr(Stdio::piped())
2918 .env("TARGET", &self.config.target)
2919 .env("PYTHON", &self.config.docck_python)
2920 .env("S", src_root)
2921 .env("RUST_BUILD_STAGE", &self.config.stage_id)
2922 .env("RUSTC", cwd.join(&self.config.rustc_path))
2923 .env("TMPDIR", &tmpdir)
2924 .env("LD_LIB_PATH_ENVVAR", dylib_env_var())
2925 .env("HOST_RPATH_DIR", cwd.join(&self.config.compile_lib_path))
2926 .env("TARGET_RPATH_DIR", cwd.join(&self.config.run_lib_path))
2927 .env("LLVM_COMPONENTS", &self.config.llvm_components)
2928 // We for sure don't want these tests to run in parallel, so make
2929 // sure they don't have access to these vars if we run via `make`
2930 // at the top level
2931 .env_remove("MAKEFLAGS")
2932 .env_remove("MFLAGS")
2933 .env_remove("CARGO_MAKEFLAGS");
2934
2935 if let Some(ref rustdoc) = self.config.rustdoc_path {
2936 cmd.env("RUSTDOC", cwd.join(rustdoc));
2937 }
2938
2939 if let Some(ref rust_demangler) = self.config.rust_demangler_path {
2940 cmd.env("RUST_DEMANGLER", cwd.join(rust_demangler));
2941 }
2942
2943 if let Some(ref node) = self.config.nodejs {
2944 cmd.env("NODE", node);
2945 }
2946
2947 if let Some(ref linker) = self.config.linker {
2948 cmd.env("RUSTC_LINKER", linker);
2949 }
2950
2951 if let Some(ref clang) = self.config.run_clang_based_tests_with {
2952 cmd.env("CLANG", clang);
2953 }
2954
2955 if let Some(ref filecheck) = self.config.llvm_filecheck {
2956 cmd.env("LLVM_FILECHECK", filecheck);
2957 }
2958
2959 if let Some(ref llvm_bin_dir) = self.config.llvm_bin_dir {
2960 cmd.env("LLVM_BIN_DIR", llvm_bin_dir);
2961 }
2962
2963 // We don't want RUSTFLAGS set from the outside to interfere with
2964 // compiler flags set in the test cases:
2965 cmd.env_remove("RUSTFLAGS");
2966
2967 // Use dynamic musl for tests because static doesn't allow creating dylibs
2968 if self.config.host.contains("musl") {
2969 cmd.env("RUSTFLAGS", "-Ctarget-feature=-crt-static").env("IS_MUSL_HOST", "1");
2970 }
2971
2972 if self.config.bless {
2973 cmd.env("RUSTC_BLESS_TEST", "--bless");
2974 // Assume this option is active if the environment variable is "defined", with _any_ value.
2975 // As an example, a `Makefile` can use this option by:
2976 //
2977 // ifdef RUSTC_BLESS_TEST
2978 // cp "$(TMPDIR)"/actual_something.ext expected_something.ext
2979 // else
2980 // $(DIFF) expected_something.ext "$(TMPDIR)"/actual_something.ext
2981 // endif
2982 }
2983
2984 if self.config.target.contains("msvc") && self.config.cc != "" {
2985 // We need to pass a path to `lib.exe`, so assume that `cc` is `cl.exe`
2986 // and that `lib.exe` lives next to it.
2987 let lib = Path::new(&self.config.cc).parent().unwrap().join("lib.exe");
2988
2989 // MSYS doesn't like passing flags of the form `/foo` as it thinks it's
2990 // a path and instead passes `C:\msys64\foo`, so convert all
2991 // `/`-arguments to MSVC here to `-` arguments.
2992 let cflags = self
2993 .config
2994 .cflags
2995 .split(' ')
2996 .map(|s| s.replace("/", "-"))
2997 .collect::<Vec<_>>()
2998 .join(" ");
2999
3000 cmd.env("IS_MSVC", "1")
3001 .env("IS_WINDOWS", "1")
3002 .env("MSVC_LIB", format!("'{}' -nologo", lib.display()))
3003 .env("CC", format!("'{}' {}", self.config.cc, cflags))
3004 .env("CXX", format!("'{}'", &self.config.cxx));
3005 } else {
3006 cmd.env("CC", format!("{} {}", self.config.cc, self.config.cflags))
3007 .env("CXX", format!("{} {}", self.config.cxx, self.config.cflags))
3008 .env("AR", &self.config.ar);
3009
3010 if self.config.target.contains("windows") {
3011 cmd.env("IS_WINDOWS", "1");
3012 }
3013 }
3014
3015 let output = cmd.spawn().and_then(read2_abbreviated).expect("failed to spawn `make`");
3016 if !output.status.success() {
3017 let res = ProcRes {
3018 status: output.status,
3019 stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
3020 stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
3021 cmdline: format!("{:?}", cmd),
3022 };
3023 self.fatal_proc_rec("make failed", &res);
3024 }
3025 }
3026
3027 fn aggressive_rm_rf(&self, path: &Path) -> io::Result<()> {
3028 for e in path.read_dir()? {
3029 let entry = e?;
3030 let path = entry.path();
3031 if entry.file_type()?.is_dir() {
3032 self.aggressive_rm_rf(&path)?;
3033 } else {
3034 // Remove readonly files as well on windows (by default we can't)
3035 fs::remove_file(&path).or_else(|e| {
3036 if cfg!(windows) && e.kind() == io::ErrorKind::PermissionDenied {
3037 let mut meta = entry.metadata()?.permissions();
3038 meta.set_readonly(false);
3039 fs::set_permissions(&path, meta)?;
3040 fs::remove_file(&path)
3041 } else {
3042 Err(e)
3043 }
3044 })?;
3045 }
3046 }
3047 fs::remove_dir(path)
3048 }
3049
3050 fn run_js_doc_test(&self) {
3051 if let Some(nodejs) = &self.config.nodejs {
3052 let out_dir = self.output_base_dir();
3053
3054 self.document(&out_dir);
3055
3056 let root = self.config.find_rust_src_root().unwrap();
3057 let file_stem =
3058 self.testpaths.file.file_stem().and_then(|f| f.to_str()).expect("no file stem");
3059 let res = self.cmd2procres(
3060 Command::new(&nodejs)
3061 .arg(root.join("src/tools/rustdoc-js/tester.js"))
3062 .arg("--doc-folder")
3063 .arg(out_dir)
3064 .arg("--crate-name")
3065 .arg(file_stem.replace("-", "_"))
3066 .arg("--test-file")
3067 .arg(self.testpaths.file.with_extension("js")),
3068 );
3069 if !res.status.success() {
3070 self.fatal_proc_rec("rustdoc-js test failed!", &res);
3071 }
3072 } else {
3073 self.fatal("no nodeJS");
3074 }
3075 }
3076
3077 fn load_compare_outputs(
3078 &self,
3079 proc_res: &ProcRes,
3080 output_kind: TestOutput,
3081 explicit_format: bool,
3082 ) -> usize {
3083 let (stderr_kind, stdout_kind) = match output_kind {
3084 TestOutput::Compile => (UI_STDERR, UI_STDOUT),
3085 TestOutput::Run => (UI_RUN_STDERR, UI_RUN_STDOUT),
3086 };
3087
3088 let expected_stderr = self.load_expected_output(stderr_kind);
3089 let expected_stdout = self.load_expected_output(stdout_kind);
3090
3091 let normalized_stdout = match output_kind {
3092 TestOutput::Run if self.config.remote_test_client.is_some() => {
3093 // When tests are run using the remote-test-client, the string
3094 // 'uploaded "$TEST_BUILD_DIR/<test_executable>, waiting for result"'
3095 // is printed to stdout by the client and then captured in the ProcRes,
3096 // so it needs to be removed when comparing the run-pass test execution output
3097 lazy_static! {
3098 static ref REMOTE_TEST_RE: Regex = Regex::new(
3099 "^uploaded \"\\$TEST_BUILD_DIR(/[[:alnum:]_\\-]+)+\", waiting for result\n"
3100 )
3101 .unwrap();
3102 }
3103 REMOTE_TEST_RE
3104 .replace(
3105 &self.normalize_output(&proc_res.stdout, &self.props.normalize_stdout),
3106 "",
3107 )
3108 .to_string()
3109 }
3110 _ => self.normalize_output(&proc_res.stdout, &self.props.normalize_stdout),
3111 };
3112
3113 let stderr = if explicit_format {
3114 proc_res.stderr.clone()
3115 } else {
3116 json::extract_rendered(&proc_res.stderr)
3117 };
3118
3119 let normalized_stderr = self.normalize_output(&stderr, &self.props.normalize_stderr);
3120 let mut errors = 0;
3121 match output_kind {
3122 TestOutput::Compile => {
3123 if !self.props.dont_check_compiler_stdout {
3124 errors += self.compare_output("stdout", &normalized_stdout, &expected_stdout);
3125 }
3126 if !self.props.dont_check_compiler_stderr {
3127 errors += self.compare_output("stderr", &normalized_stderr, &expected_stderr);
3128 }
3129 }
3130 TestOutput::Run => {
3131 errors += self.compare_output(stdout_kind, &normalized_stdout, &expected_stdout);
3132 errors += self.compare_output(stderr_kind, &normalized_stderr, &expected_stderr);
3133 }
3134 }
3135 errors
3136 }
3137
3138 fn run_ui_test(&self) {
3139 if let Some(FailMode::Build) = self.props.fail_mode {
3140 // Make sure a build-fail test cannot fail due to failing analysis (e.g. typeck).
3141 let pm = Some(PassMode::Check);
3142 let proc_res = self.compile_test_general(WillExecute::No, EmitMetadata::Yes, pm);
3143 self.check_if_test_should_compile(&proc_res, pm);
3144 }
3145
3146 let pm = self.pass_mode();
3147 let should_run = self.should_run(pm);
3148 let emit_metadata = self.should_emit_metadata(pm);
3149 let proc_res = self.compile_test(should_run, emit_metadata);
3150 self.check_if_test_should_compile(&proc_res, pm);
3151
3152 // if the user specified a format in the ui test
3153 // print the output to the stderr file, otherwise extract
3154 // the rendered error messages from json and print them
3155 let explicit = self.props.compile_flags.iter().any(|s| s.contains("--error-format"));
3156
3157 let expected_fixed = self.load_expected_output(UI_FIXED);
3158
3159 let modes_to_prune = vec![CompareMode::Nll];
3160 self.prune_duplicate_outputs(&modes_to_prune);
3161
3162 let mut errors = self.load_compare_outputs(&proc_res, TestOutput::Compile, explicit);
3163 let rustfix_input = json::rustfix_diagnostics_only(&proc_res.stderr);
3164
3165 if self.config.compare_mode.is_some() {
3166 // don't test rustfix with nll right now
3167 } else if self.config.rustfix_coverage {
3168 // Find out which tests have `MachineApplicable` suggestions but are missing
3169 // `run-rustfix` or `run-rustfix-only-machine-applicable` headers.
3170 //
3171 // This will return an empty `Vec` in case the executed test file has a
3172 // `compile-flags: --error-format=xxxx` header with a value other than `json`.
3173 let suggestions = get_suggestions_from_json(
3174 &rustfix_input,
3175 &HashSet::new(),
3176 Filter::MachineApplicableOnly,
3177 )
3178 .unwrap_or_default();
3179 if !suggestions.is_empty()
3180 && !self.props.run_rustfix
3181 && !self.props.rustfix_only_machine_applicable
3182 {
3183 let mut coverage_file_path = self.config.build_base.clone();
3184 coverage_file_path.push("rustfix_missing_coverage.txt");
3185 debug!("coverage_file_path: {}", coverage_file_path.display());
3186
3187 let mut file = OpenOptions::new()
3188 .create(true)
3189 .append(true)
3190 .open(coverage_file_path.as_path())
3191 .expect("could not create or open file");
3192
3193 if writeln!(file, "{}", self.testpaths.file.display()).is_err() {
3194 panic!("couldn't write to {}", coverage_file_path.display());
3195 }
3196 }
3197 } else if self.props.run_rustfix {
3198 // Apply suggestions from rustc to the code itself
3199 let unfixed_code = self.load_expected_output_from_path(&self.testpaths.file).unwrap();
3200 let suggestions = get_suggestions_from_json(
3201 &rustfix_input,
3202 &HashSet::new(),
3203 if self.props.rustfix_only_machine_applicable {
3204 Filter::MachineApplicableOnly
3205 } else {
3206 Filter::Everything
3207 },
3208 )
3209 .unwrap();
3210 let fixed_code = apply_suggestions(&unfixed_code, &suggestions).unwrap_or_else(|_| {
3211 panic!("failed to apply suggestions for {:?} with rustfix", self.testpaths.file)
3212 });
3213
3214 errors += self.compare_output("fixed", &fixed_code, &expected_fixed);
3215 } else if !expected_fixed.is_empty() {
3216 panic!(
3217 "the `// run-rustfix` directive wasn't found but a `*.fixed` \
3218 file was found"
3219 );
3220 }
3221
3222 if errors > 0 {
3223 println!("To update references, rerun the tests and pass the `--bless` flag");
3224 let relative_path_to_file =
3225 self.testpaths.relative_dir.join(self.testpaths.file.file_name().unwrap());
3226 println!(
3227 "To only update this specific test, also pass `--test-args {}`",
3228 relative_path_to_file.display(),
3229 );
3230 self.fatal_proc_rec(
3231 &format!("{} errors occurred comparing output.", errors),
3232 &proc_res,
3233 );
3234 }
3235
3236 let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
3237
3238 if let WillExecute::Yes = should_run {
3239 let proc_res = self.exec_compiled_test();
3240 let run_output_errors = if self.props.check_run_results {
3241 self.load_compare_outputs(&proc_res, TestOutput::Run, explicit)
3242 } else {
3243 0
3244 };
3245 if run_output_errors > 0 {
3246 self.fatal_proc_rec(
3247 &format!("{} errors occurred comparing run output.", run_output_errors),
3248 &proc_res,
3249 );
3250 }
3251 if self.should_run_successfully(pm) {
3252 if !proc_res.status.success() {
3253 self.fatal_proc_rec("test run failed!", &proc_res);
3254 }
3255 } else {
3256 if proc_res.status.success() {
3257 self.fatal_proc_rec("test run succeeded!", &proc_res);
3258 }
3259 }
3260 if !self.props.error_patterns.is_empty() {
3261 // "// error-pattern" comments
3262 self.check_error_patterns(&proc_res.stderr, &proc_res, pm);
3263 }
3264 }
3265
3266 debug!(
3267 "run_ui_test: explicit={:?} config.compare_mode={:?} expected_errors={:?} \
3268 proc_res.status={:?} props.error_patterns={:?}",
3269 explicit,
3270 self.config.compare_mode,
3271 expected_errors,
3272 proc_res.status,
3273 self.props.error_patterns
3274 );
3275 if !explicit && self.config.compare_mode.is_none() {
3276 let check_patterns =
3277 should_run == WillExecute::No && !self.props.error_patterns.is_empty();
3278
3279 let check_annotations = !check_patterns || !expected_errors.is_empty();
3280
3281 if check_patterns {
3282 // "// error-pattern" comments
3283 self.check_error_patterns(&proc_res.stderr, &proc_res, pm);
3284 }
3285
3286 if check_annotations {
3287 // "//~ERROR comments"
3288 self.check_expected_errors(expected_errors, &proc_res);
3289 }
3290 }
3291
3292 if self.props.run_rustfix && self.config.compare_mode.is_none() {
3293 // And finally, compile the fixed code and make sure it both
3294 // succeeds and has no diagnostics.
3295 let mut rustc = self.make_compile_args(
3296 &self.testpaths.file.with_extension(UI_FIXED),
3297 TargetLocation::ThisFile(self.make_exe_name()),
3298 emit_metadata,
3299 AllowUnused::No,
3300 );
3301 rustc.arg("-L").arg(&self.aux_output_dir_name());
3302 let res = self.compose_and_run_compiler(rustc, None);
3303 if !res.status.success() {
3304 self.fatal_proc_rec("failed to compile fixed code", &res);
3305 }
3306 if !res.stderr.is_empty() && !self.props.rustfix_only_machine_applicable {
3307 if !json::rustfix_diagnostics_only(&res.stderr).is_empty() {
3308 self.fatal_proc_rec("fixed code is still producing diagnostics", &res);
3309 }
3310 }
3311 }
3312 }
3313
3314 fn run_mir_opt_test(&self) {
3315 let pm = self.pass_mode();
3316 let should_run = self.should_run(pm);
3317 let emit_metadata = self.should_emit_metadata(pm);
3318 let proc_res = self.compile_test(should_run, emit_metadata);
3319
3320 if !proc_res.status.success() {
3321 self.fatal_proc_rec("compilation failed!", &proc_res);
3322 }
3323
3324 self.check_mir_dump();
3325
3326 if let WillExecute::Yes = should_run {
3327 let proc_res = self.exec_compiled_test();
3328
3329 if !proc_res.status.success() {
3330 self.fatal_proc_rec("test run failed!", &proc_res);
3331 }
3332 }
3333 }
3334
3335 fn check_mir_dump(&self) {
3336 let test_file_contents = fs::read_to_string(&self.testpaths.file).unwrap();
3337
3338 let test_dir = self.testpaths.file.parent().unwrap();
3339 let test_crate =
3340 self.testpaths.file.file_stem().unwrap().to_str().unwrap().replace("-", "_");
3341
3342 let mut bit_width = String::new();
3343 if test_file_contents.lines().any(|l| l == "// EMIT_MIR_FOR_EACH_BIT_WIDTH") {
3344 bit_width = format!(".{}", get_pointer_width(&self.config.target));
3345 }
3346
3347 if self.config.bless {
3348 for e in
3349 glob(&format!("{}/{}.*{}.mir", test_dir.display(), test_crate, bit_width)).unwrap()
3350 {
3351 std::fs::remove_file(e.unwrap()).unwrap();
3352 }
3353 for e in
3354 glob(&format!("{}/{}.*{}.diff", test_dir.display(), test_crate, bit_width)).unwrap()
3355 {
3356 std::fs::remove_file(e.unwrap()).unwrap();
3357 }
3358 }
3359
3360 for l in test_file_contents.lines() {
3361 if l.starts_with("// EMIT_MIR ") {
3362 let test_name = l.trim_start_matches("// EMIT_MIR ").trim();
3363 let mut test_names = test_name.split(' ');
3364 // sometimes we specify two files so that we get a diff between the two files
3365 let test_name = test_names.next().unwrap();
3366 let mut expected_file;
3367 let from_file;
3368 let to_file;
3369
3370 if test_name.ends_with(".diff") {
3371 let trimmed = test_name.trim_end_matches(".diff");
3372 let test_against = format!("{}.after.mir", trimmed);
3373 from_file = format!("{}.before.mir", trimmed);
3374 expected_file = format!("{}{}.diff", trimmed, bit_width);
3375 assert!(
3376 test_names.next().is_none(),
3377 "two mir pass names specified for MIR diff"
3378 );
3379 to_file = Some(test_against);
3380 } else if let Some(first_pass) = test_names.next() {
3381 let second_pass = test_names.next().unwrap();
3382 assert!(
3383 test_names.next().is_none(),
3384 "three mir pass names specified for MIR diff"
3385 );
3386 expected_file =
3387 format!("{}{}.{}-{}.diff", test_name, bit_width, first_pass, second_pass);
3388 let second_file = format!("{}.{}.mir", test_name, second_pass);
3389 from_file = format!("{}.{}.mir", test_name, first_pass);
3390 to_file = Some(second_file);
3391 } else {
3392 let ext_re = Regex::new(r#"(\.(mir|dot|html))$"#).unwrap();
3393 let cap = ext_re
3394 .captures_iter(test_name)
3395 .next()
3396 .expect("test_name has an invalid extension");
3397 let extension = cap.get(1).unwrap().as_str();
3398 expected_file = format!(
3399 "{}{}{}",
3400 test_name.trim_end_matches(extension),
3401 bit_width,
3402 extension,
3403 );
3404 from_file = test_name.to_string();
3405 assert!(
3406 test_names.next().is_none(),
3407 "two mir pass names specified for MIR dump"
3408 );
3409 to_file = None;
3410 };
3411 if !expected_file.starts_with(&test_crate) {
3412 expected_file = format!("{}.{}", test_crate, expected_file);
3413 }
3414 let expected_file = test_dir.join(expected_file);
3415
3416 let dumped_string = if let Some(after) = to_file {
3417 self.diff_mir_files(from_file.into(), after.into())
3418 } else {
3419 let mut output_file = PathBuf::new();
3420 output_file.push(self.get_mir_dump_dir());
3421 output_file.push(&from_file);
3422 debug!(
3423 "comparing the contents of: {} with {}",
3424 output_file.display(),
3425 expected_file.display()
3426 );
3427 if !output_file.exists() {
3428 panic!(
3429 "Output file `{}` from test does not exist, available files are in `{}`",
3430 output_file.display(),
3431 output_file.parent().unwrap().display()
3432 );
3433 }
3434 self.check_mir_test_timestamp(&from_file, &output_file);
3435 let dumped_string = fs::read_to_string(&output_file).unwrap();
3436 self.normalize_output(&dumped_string, &[])
3437 };
3438
3439 if self.config.bless {
3440 let _ = std::fs::remove_file(&expected_file);
3441 std::fs::write(expected_file, dumped_string.as_bytes()).unwrap();
3442 } else {
3443 if !expected_file.exists() {
3444 panic!(
3445 "Output file `{}` from test does not exist",
3446 expected_file.display()
3447 );
3448 }
3449 let expected_string = fs::read_to_string(&expected_file).unwrap();
3450 if dumped_string != expected_string {
3451 print!("{}", write_diff(&expected_string, &dumped_string, 3));
3452 panic!(
3453 "Actual MIR output differs from expected MIR output {}",
3454 expected_file.display()
3455 );
3456 }
3457 }
3458 }
3459 }
3460 }
3461
3462 fn diff_mir_files(&self, before: PathBuf, after: PathBuf) -> String {
3463 let to_full_path = |path: PathBuf| {
3464 let full = self.get_mir_dump_dir().join(&path);
3465 if !full.exists() {
3466 panic!(
3467 "the mir dump file for {} does not exist (requested in {})",
3468 path.display(),
3469 self.testpaths.file.display(),
3470 );
3471 }
3472 full
3473 };
3474 let before = to_full_path(before);
3475 let after = to_full_path(after);
3476 debug!("comparing the contents of: {} with {}", before.display(), after.display());
3477 let before = fs::read_to_string(before).unwrap();
3478 let after = fs::read_to_string(after).unwrap();
3479 let before = self.normalize_output(&before, &[]);
3480 let after = self.normalize_output(&after, &[]);
3481 let mut dumped_string = String::new();
3482 for result in diff::lines(&before, &after) {
3483 use std::fmt::Write;
3484 match result {
3485 diff::Result::Left(s) => writeln!(dumped_string, "- {}", s).unwrap(),
3486 diff::Result::Right(s) => writeln!(dumped_string, "+ {}", s).unwrap(),
3487 diff::Result::Both(s, _) => writeln!(dumped_string, " {}", s).unwrap(),
3488 }
3489 }
3490 dumped_string
3491 }
3492
3493 fn check_mir_test_timestamp(&self, test_name: &str, output_file: &Path) {
3494 let t = |file| fs::metadata(file).unwrap().modified().unwrap();
3495 let source_file = &self.testpaths.file;
3496 let output_time = t(output_file);
3497 let source_time = t(source_file);
3498 if source_time > output_time {
3499 debug!("source file time: {:?} output file time: {:?}", source_time, output_time);
3500 panic!(
3501 "test source file `{}` is newer than potentially stale output file `{}`.",
3502 source_file.display(),
3503 test_name
3504 );
3505 }
3506 }
3507
3508 fn get_mir_dump_dir(&self) -> PathBuf {
3509 let mut mir_dump_dir = PathBuf::from(self.config.build_base.as_path());
3510 debug!("input_file: {:?}", self.testpaths.file);
3511 mir_dump_dir.push(&self.testpaths.relative_dir);
3512 mir_dump_dir.push(self.testpaths.file.file_stem().unwrap());
3513 mir_dump_dir
3514 }
3515
3516 fn normalize_output(&self, output: &str, custom_rules: &[(String, String)]) -> String {
3517 let cflags = self.props.compile_flags.join(" ");
3518 let json = cflags.contains("--error-format json")
3519 || cflags.contains("--error-format pretty-json")
3520 || cflags.contains("--error-format=json")
3521 || cflags.contains("--error-format=pretty-json")
3522 || cflags.contains("--output-format json")
3523 || cflags.contains("--output-format=json");
3524
3525 let mut normalized = output.to_string();
3526
3527 let mut normalize_path = |from: &Path, to: &str| {
3528 let mut from = from.display().to_string();
3529 if json {
3530 from = from.replace("\\", "\\\\");
3531 }
3532 normalized = normalized.replace(&from, to);
3533 };
3534
3535 let parent_dir = self.testpaths.file.parent().unwrap();
3536 normalize_path(parent_dir, "$DIR");
3537
3538 // Paths into the libstd/libcore
3539 let src_dir = self
3540 .config
3541 .src_base
3542 .parent()
3543 .unwrap()
3544 .parent()
3545 .unwrap()
3546 .parent()
3547 .unwrap()
3548 .join("library");
3549 normalize_path(&src_dir, "$SRC_DIR");
3550
3551 // Paths into the build directory
3552 let test_build_dir = &self.config.build_base;
3553 let parent_build_dir = test_build_dir.parent().unwrap().parent().unwrap().parent().unwrap();
3554
3555 // eg. /home/user/rust/build/x86_64-unknown-linux-gnu/test/ui
3556 normalize_path(test_build_dir, "$TEST_BUILD_DIR");
3557 // eg. /home/user/rust/build
3558 normalize_path(parent_build_dir, "$BUILD_DIR");
3559
3560 // Paths into lib directory.
3561 normalize_path(&parent_build_dir.parent().unwrap().join("lib"), "$LIB_DIR");
3562
3563 if json {
3564 // escaped newlines in json strings should be readable
3565 // in the stderr files. There's no point int being correct,
3566 // since only humans process the stderr files.
3567 // Thus we just turn escaped newlines back into newlines.
3568 normalized = normalized.replace("\\n", "\n");
3569 }
3570
3571 // If there are `$SRC_DIR` normalizations with line and column numbers, then replace them
3572 // with placeholders as we do not want tests needing updated when compiler source code
3573 // changes.
3574 // eg. $SRC_DIR/libcore/mem.rs:323:14 becomes $SRC_DIR/libcore/mem.rs:LL:COL
3575 normalized = Regex::new("SRC_DIR(.+):\\d+:\\d+(: \\d+:\\d+)?")
3576 .unwrap()
3577 .replace_all(&normalized, "SRC_DIR$1:LL:COL")
3578 .into_owned();
3579
3580 normalized = Self::normalize_platform_differences(&normalized);
3581 normalized = normalized.replace("\t", "\\t"); // makes tabs visible
3582
3583 // Remove test annotations like `//~ ERROR text` from the output,
3584 // since they duplicate actual errors and make the output hard to read.
3585 normalized =
3586 Regex::new("\\s*//(\\[.*\\])?~.*").unwrap().replace_all(&normalized, "").into_owned();
3587
3588 for rule in custom_rules {
3589 let re = Regex::new(&rule.0).expect("bad regex in custom normalization rule");
3590 normalized = re.replace_all(&normalized, &rule.1[..]).into_owned();
3591 }
3592 normalized
3593 }
3594
3595 /// Normalize output differences across platforms. Generally changes Windows output to be more
3596 /// Unix-like.
3597 ///
3598 /// Replaces backslashes in paths with forward slashes, and replaces CRLF line endings
3599 /// with LF.
3600 fn normalize_platform_differences(output: &str) -> String {
3601 lazy_static! {
3602 /// Used to find Windows paths.
3603 ///
3604 /// It's not possible to detect paths in the error messages generally, but this is a
3605 /// decent enough heuristic.
3606 static ref PATH_BACKSLASH_RE: Regex = Regex::new(r#"(?x)
3607 (?:
3608 # Match paths that don't include spaces.
3609 (?:\\[\pL\pN\.\-_']+)+\.\pL+
3610 |
3611 # If the path starts with a well-known root, then allow spaces.
3612 \$(?:DIR|SRC_DIR|TEST_BUILD_DIR|BUILD_DIR|LIB_DIR)(?:\\[\pL\pN\.\-_' ]+)+
3613 )"#
3614 ).unwrap();
3615 }
3616
3617 let output = output.replace(r"\\", r"\");
3618
3619 PATH_BACKSLASH_RE
3620 .replace_all(&output, |caps: &Captures<'_>| {
3621 println!("{}", &caps[0]);
3622 caps[0].replace(r"\", "/")
3623 })
3624 .replace("\r\n", "\n")
3625 }
3626
3627 fn expected_output_path(&self, kind: &str) -> PathBuf {
3628 let mut path =
3629 expected_output_path(&self.testpaths, self.revision, &self.config.compare_mode, kind);
3630
3631 if !path.exists() {
3632 if let Some(CompareMode::Polonius) = self.config.compare_mode {
3633 path = expected_output_path(
3634 &self.testpaths,
3635 self.revision,
3636 &Some(CompareMode::Nll),
3637 kind,
3638 );
3639 }
3640 }
3641
3642 if !path.exists() {
3643 path = expected_output_path(&self.testpaths, self.revision, &None, kind);
3644 }
3645
3646 path
3647 }
3648
3649 fn load_expected_output(&self, kind: &str) -> String {
3650 let path = self.expected_output_path(kind);
3651 if path.exists() {
3652 match self.load_expected_output_from_path(&path) {
3653 Ok(x) => x,
3654 Err(x) => self.fatal(&x),
3655 }
3656 } else {
3657 String::new()
3658 }
3659 }
3660
3661 fn load_expected_output_from_path(&self, path: &Path) -> Result<String, String> {
3662 fs::read_to_string(path).map_err(|err| {
3663 format!("failed to load expected output from `{}`: {}", path.display(), err)
3664 })
3665 }
3666
3667 fn delete_file(&self, file: &PathBuf) {
3668 if !file.exists() {
3669 // Deleting a nonexistant file would error.
3670 return;
3671 }
3672 if let Err(e) = fs::remove_file(file) {
3673 self.fatal(&format!("failed to delete `{}`: {}", file.display(), e,));
3674 }
3675 }
3676
3677 fn compare_output(&self, kind: &str, actual: &str, expected: &str) -> usize {
3678 if actual == expected {
3679 return 0;
3680 }
3681
3682 if !self.config.bless {
3683 if expected.is_empty() {
3684 println!("normalized {}:\n{}\n", kind, actual);
3685 } else {
3686 println!("diff of {}:\n", kind);
3687 print!("{}", write_diff(expected, actual, 3));
3688 }
3689 }
3690
3691 let mode = self.config.compare_mode.as_ref().map_or("", |m| m.to_str());
3692 let output_file = self
3693 .output_base_name()
3694 .with_extra_extension(self.revision.unwrap_or(""))
3695 .with_extra_extension(mode)
3696 .with_extra_extension(kind);
3697
3698 let mut files = vec![output_file];
3699 if self.config.bless {
3700 files.push(expected_output_path(
3701 self.testpaths,
3702 self.revision,
3703 &self.config.compare_mode,
3704 kind,
3705 ));
3706 }
3707
3708 for output_file in &files {
3709 if actual.is_empty() {
3710 self.delete_file(output_file);
3711 } else if let Err(err) = fs::write(&output_file, &actual) {
3712 self.fatal(&format!(
3713 "failed to write {} to `{}`: {}",
3714 kind,
3715 output_file.display(),
3716 err,
3717 ));
3718 }
3719 }
3720
3721 println!("\nThe actual {0} differed from the expected {0}.", kind);
3722 for output_file in files {
3723 println!("Actual {} saved to {}", kind, output_file.display());
3724 }
3725 if self.config.bless { 0 } else { 1 }
3726 }
3727
3728 fn prune_duplicate_output(&self, mode: CompareMode, kind: &str, canon_content: &str) {
3729 let examined_path = expected_output_path(&self.testpaths, self.revision, &Some(mode), kind);
3730
3731 let examined_content =
3732 self.load_expected_output_from_path(&examined_path).unwrap_or_else(|_| String::new());
3733
3734 if canon_content == examined_content {
3735 self.delete_file(&examined_path);
3736 }
3737 }
3738
3739 fn prune_duplicate_outputs(&self, modes: &[CompareMode]) {
3740 if self.config.bless {
3741 for kind in UI_EXTENSIONS {
3742 let canon_comparison_path =
3743 expected_output_path(&self.testpaths, self.revision, &None, kind);
3744
3745 if let Ok(canon) = self.load_expected_output_from_path(&canon_comparison_path) {
3746 for mode in modes {
3747 self.prune_duplicate_output(mode.clone(), kind, &canon);
3748 }
3749 }
3750 }
3751 }
3752 }
3753
3754 fn create_stamp(&self) {
3755 let stamp = crate::stamp(&self.config, self.testpaths, self.revision);
3756 fs::write(&stamp, compute_stamp_hash(&self.config)).unwrap();
3757 }
3758 }
3759
3760 struct ProcArgs {
3761 prog: String,
3762 args: Vec<String>,
3763 }
3764
3765 pub struct ProcRes {
3766 status: ExitStatus,
3767 stdout: String,
3768 stderr: String,
3769 cmdline: String,
3770 }
3771
3772 impl ProcRes {
3773 pub fn fatal(&self, err: Option<&str>, on_failure: impl FnOnce()) -> ! {
3774 if let Some(e) = err {
3775 println!("\nerror: {}", e);
3776 }
3777 print!(
3778 "\
3779 status: {}\n\
3780 command: {}\n\
3781 stdout:\n\
3782 ------------------------------------------\n\
3783 {}\n\
3784 ------------------------------------------\n\
3785 stderr:\n\
3786 ------------------------------------------\n\
3787 {}\n\
3788 ------------------------------------------\n\
3789 \n",
3790 self.status,
3791 self.cmdline,
3792 json::extract_rendered(&self.stdout),
3793 json::extract_rendered(&self.stderr),
3794 );
3795 on_failure();
3796 // Use resume_unwind instead of panic!() to prevent a panic message + backtrace from
3797 // compiletest, which is unnecessary noise.
3798 std::panic::resume_unwind(Box::new(()));
3799 }
3800 }
3801
3802 #[derive(Debug)]
3803 enum TargetLocation {
3804 ThisFile(PathBuf),
3805 ThisDirectory(PathBuf),
3806 }
3807
3808 enum AllowUnused {
3809 Yes,
3810 No,
3811 }
3812
3813 fn read2_abbreviated(mut child: Child) -> io::Result<Output> {
3814 use crate::read2::read2;
3815 use std::mem::replace;
3816
3817 const HEAD_LEN: usize = 160 * 1024;
3818 const TAIL_LEN: usize = 256 * 1024;
3819
3820 enum ProcOutput {
3821 Full(Vec<u8>),
3822 Abbreviated { head: Vec<u8>, skipped: usize, tail: Box<[u8]> },
3823 }
3824
3825 impl ProcOutput {
3826 fn extend(&mut self, data: &[u8]) {
3827 let new_self = match *self {
3828 ProcOutput::Full(ref mut bytes) => {
3829 bytes.extend_from_slice(data);
3830 let new_len = bytes.len();
3831 if new_len <= HEAD_LEN + TAIL_LEN {
3832 return;
3833 }
3834 let tail = bytes.split_off(new_len - TAIL_LEN).into_boxed_slice();
3835 let head = replace(bytes, Vec::new());
3836 let skipped = new_len - HEAD_LEN - TAIL_LEN;
3837 ProcOutput::Abbreviated { head, skipped, tail }
3838 }
3839 ProcOutput::Abbreviated { ref mut skipped, ref mut tail, .. } => {
3840 *skipped += data.len();
3841 if data.len() <= TAIL_LEN {
3842 tail[..data.len()].copy_from_slice(data);
3843 tail.rotate_left(data.len());
3844 } else {
3845 tail.copy_from_slice(&data[(data.len() - TAIL_LEN)..]);
3846 }
3847 return;
3848 }
3849 };
3850 *self = new_self;
3851 }
3852
3853 fn into_bytes(self) -> Vec<u8> {
3854 match self {
3855 ProcOutput::Full(bytes) => bytes,
3856 ProcOutput::Abbreviated { mut head, skipped, tail } => {
3857 write!(&mut head, "\n\n<<<<<< SKIPPED {} BYTES >>>>>>\n\n", skipped).unwrap();
3858 head.extend_from_slice(&tail);
3859 head
3860 }
3861 }
3862 }
3863 }
3864
3865 let mut stdout = ProcOutput::Full(Vec::new());
3866 let mut stderr = ProcOutput::Full(Vec::new());
3867
3868 drop(child.stdin.take());
3869 read2(
3870 child.stdout.take().unwrap(),
3871 child.stderr.take().unwrap(),
3872 &mut |is_stdout, data, _| {
3873 if is_stdout { &mut stdout } else { &mut stderr }.extend(data);
3874 data.clear();
3875 },
3876 )?;
3877 let status = child.wait()?;
3878
3879 Ok(Output { status, stdout: stdout.into_bytes(), stderr: stderr.into_bytes() })
3880 }