]> git.lizzy.rs Git - rust.git/blob - src/tools/compiletest/src/runtest.rs
Rollup merge of #41141 - michaelwoerister:direct-metadata-ich-final, r=nikomatsakis
[rust.git] / src / tools / compiletest / src / runtest.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use common::Config;
12 use common::{CompileFail, ParseFail, Pretty, RunFail, RunPass, RunPassValgrind};
13 use common::{Codegen, DebugInfoLldb, DebugInfoGdb, Rustdoc, CodegenUnits};
14 use common::{Incremental, RunMake, Ui, MirOpt};
15 use errors::{self, ErrorKind, Error};
16 use filetime::FileTime;
17 use json;
18 use header::TestProps;
19 use header;
20 use procsrv;
21 use test::TestPaths;
22 use uidiff;
23 use util::logv;
24
25 use std::collections::HashSet;
26 use std::env;
27 use std::fmt;
28 use std::fs::{self, File, create_dir_all};
29 use std::io::prelude::*;
30 use std::io::{self, BufReader};
31 use std::path::{Path, PathBuf};
32 use std::process::{Command, Output, ExitStatus};
33 use std::str;
34 use std::collections::HashMap;
35
36 use extract_gdb_version;
37
38 pub fn run(config: Config, testpaths: &TestPaths) {
39     match &*config.target {
40
41         "arm-linux-androideabi" | "armv7-linux-androideabi" | "aarch64-linux-android" => {
42             if !config.adb_device_status {
43                 panic!("android device not available");
44             }
45         }
46
47         _ => {
48             // android has its own gdb handling
49             if config.mode == DebugInfoGdb && config.gdb.is_none() {
50                 panic!("gdb not available but debuginfo gdb debuginfo test requested");
51             }
52         }
53     }
54
55     if config.verbose {
56         // We're going to be dumping a lot of info. Start on a new line.
57         print!("\n\n");
58     }
59     debug!("running {:?}", testpaths.file.display());
60     let base_props = TestProps::from_file(&testpaths.file);
61
62     let base_cx = TestCx { config: &config,
63                            props: &base_props,
64                            testpaths: testpaths,
65                            revision: None };
66     base_cx.init_all();
67
68     if base_props.revisions.is_empty() {
69         base_cx.run_revision()
70     } else {
71         for revision in &base_props.revisions {
72             let mut revision_props = base_props.clone();
73             revision_props.load_from(&testpaths.file, Some(&revision));
74             let rev_cx = TestCx {
75                 config: &config,
76                 props: &revision_props,
77                 testpaths: testpaths,
78                 revision: Some(revision)
79             };
80             rev_cx.run_revision();
81         }
82     }
83
84     base_cx.complete_all();
85
86     File::create(::stamp(&config, &testpaths)).unwrap();
87 }
88
89 struct TestCx<'test> {
90     config: &'test Config,
91     props: &'test TestProps,
92     testpaths: &'test TestPaths,
93     revision: Option<&'test str>
94 }
95
96 struct DebuggerCommands {
97     commands: Vec<String>,
98     check_lines: Vec<String>,
99     breakpoint_lines: Vec<usize>,
100 }
101
102 impl<'test> TestCx<'test> {
103     /// invoked once before any revisions have been processed
104     fn init_all(&self) {
105         assert!(self.revision.is_none(), "init_all invoked for a revision");
106         match self.config.mode {
107             Incremental => self.init_incremental_test(),
108             _ => { }
109         }
110     }
111
112     /// Code executed for each revision in turn (or, if there are no
113     /// revisions, exactly once, with revision == None).
114     fn run_revision(&self) {
115         match self.config.mode {
116             CompileFail => self.run_cfail_test(),
117             ParseFail => self.run_cfail_test(),
118             RunFail => self.run_rfail_test(),
119             RunPass => self.run_rpass_test(),
120             RunPassValgrind => self.run_valgrind_test(),
121             Pretty => self.run_pretty_test(),
122             DebugInfoGdb => self.run_debuginfo_gdb_test(),
123             DebugInfoLldb => self.run_debuginfo_lldb_test(),
124             Codegen => self.run_codegen_test(),
125             Rustdoc => self.run_rustdoc_test(),
126             CodegenUnits => self.run_codegen_units_test(),
127             Incremental => self.run_incremental_test(),
128             RunMake => self.run_rmake_test(),
129             Ui => self.run_ui_test(),
130             MirOpt => self.run_mir_opt_test(),
131         }
132     }
133
134     /// Invoked after all revisions have executed.
135     fn complete_all(&self) {
136         assert!(self.revision.is_none(), "init_all invoked for a revision");
137     }
138
139     fn run_cfail_test(&self) {
140         let proc_res = self.compile_test();
141
142         if self.props.must_compile_successfully {
143             if !proc_res.status.success() {
144                 self.fatal_proc_rec(
145                     "test compilation failed although it shouldn't!",
146                     &proc_res);
147             }
148         } else {
149             if proc_res.status.success() {
150                 self.fatal_proc_rec(
151                     &format!("{} test compiled successfully!", self.config.mode)[..],
152                     &proc_res);
153             }
154
155             self.check_correct_failure_status(&proc_res);
156         }
157
158         let output_to_check = self.get_output(&proc_res);
159         let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
160         if !expected_errors.is_empty() {
161             if !self.props.error_patterns.is_empty() {
162                 self.fatal("both error pattern and expected errors specified");
163             }
164             self.check_expected_errors(expected_errors, &proc_res);
165         } else {
166             self.check_error_patterns(&output_to_check, &proc_res);
167         }
168
169         self.check_no_compiler_crash(&proc_res);
170         self.check_forbid_output(&output_to_check, &proc_res);
171     }
172
173     fn run_rfail_test(&self) {
174         let proc_res = self.compile_test();
175
176         if !proc_res.status.success() {
177             self.fatal_proc_rec("compilation failed!", &proc_res);
178         }
179
180         let proc_res = self.exec_compiled_test();
181
182         // The value our Makefile configures valgrind to return on failure
183         const VALGRIND_ERR: i32 = 100;
184         if proc_res.status.code() == Some(VALGRIND_ERR) {
185             self.fatal_proc_rec("run-fail test isn't valgrind-clean!", &proc_res);
186         }
187
188         let output_to_check = self.get_output(&proc_res);
189         self.check_correct_failure_status(&proc_res);
190         self.check_error_patterns(&output_to_check, &proc_res);
191     }
192
193     fn get_output(&self, proc_res: &ProcRes) -> String {
194         if self.props.check_stdout {
195             format!("{}{}", proc_res.stdout, proc_res.stderr)
196         } else {
197             proc_res.stderr.clone()
198         }
199     }
200
201     fn check_correct_failure_status(&self, proc_res: &ProcRes) {
202         // The value the rust runtime returns on failure
203         const RUST_ERR: i32 = 101;
204         if proc_res.status.code() != Some(RUST_ERR) {
205             self.fatal_proc_rec(
206                 &format!("failure produced the wrong error: {}",
207                          proc_res.status),
208                 proc_res);
209         }
210     }
211
212     fn run_rpass_test(&self) {
213         let proc_res = self.compile_test();
214
215         if !proc_res.status.success() {
216             self.fatal_proc_rec("compilation failed!", &proc_res);
217         }
218
219         let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
220         if !expected_errors.is_empty() {
221             self.check_expected_errors(expected_errors, &proc_res);
222         }
223
224         let proc_res = self.exec_compiled_test();
225
226         if !proc_res.status.success() {
227             self.fatal_proc_rec("test run failed!", &proc_res);
228         }
229     }
230
231     fn run_valgrind_test(&self) {
232         assert!(self.revision.is_none(), "revisions not relevant here");
233
234         if self.config.valgrind_path.is_none() {
235             assert!(!self.config.force_valgrind);
236             return self.run_rpass_test();
237         }
238
239         let mut proc_res = self.compile_test();
240
241         if !proc_res.status.success() {
242             self.fatal_proc_rec("compilation failed!", &proc_res);
243         }
244
245         let mut new_config = self.config.clone();
246         new_config.runtool = new_config.valgrind_path.clone();
247         let new_cx = TestCx { config: &new_config, ..*self };
248         proc_res = new_cx.exec_compiled_test();
249
250         if !proc_res.status.success() {
251             self.fatal_proc_rec("test run failed!", &proc_res);
252         }
253     }
254
255     fn run_pretty_test(&self) {
256         if self.props.pp_exact.is_some() {
257             logv(self.config, "testing for exact pretty-printing".to_owned());
258         } else {
259             logv(self.config, "testing for converging pretty-printing".to_owned());
260         }
261
262         let rounds = match self.props.pp_exact { Some(_) => 1, None => 2 };
263
264         let mut src = String::new();
265         File::open(&self.testpaths.file).unwrap().read_to_string(&mut src).unwrap();
266         let mut srcs = vec![src];
267
268         let mut round = 0;
269         while round < rounds {
270             logv(self.config, format!("pretty-printing round {} revision {:?}",
271                                       round, self.revision));
272             let proc_res = self.print_source(srcs[round].to_owned(), &self.props.pretty_mode);
273
274             if !proc_res.status.success() {
275                 self.fatal_proc_rec(&format!("pretty-printing failed in round {} revision {:?}",
276                                              round, self.revision),
277                                     &proc_res);
278             }
279
280             let ProcRes{ stdout, .. } = proc_res;
281             srcs.push(stdout);
282             round += 1;
283         }
284
285         let mut expected = match self.props.pp_exact {
286             Some(ref file) => {
287                 let filepath = self.testpaths.file.parent().unwrap().join(file);
288                 let mut s = String::new();
289                 File::open(&filepath).unwrap().read_to_string(&mut s).unwrap();
290                 s
291             }
292             None => { srcs[srcs.len() - 2].clone() }
293         };
294         let mut actual = srcs[srcs.len() - 1].clone();
295
296         if self.props.pp_exact.is_some() {
297             // Now we have to care about line endings
298             let cr = "\r".to_owned();
299             actual = actual.replace(&cr, "").to_owned();
300             expected = expected.replace(&cr, "").to_owned();
301         }
302
303         self.compare_source(&expected, &actual);
304
305         // If we're only making sure that the output matches then just stop here
306         if self.props.pretty_compare_only { return; }
307
308         // Finally, let's make sure it actually appears to remain valid code
309         let proc_res = self.typecheck_source(actual);
310         if !proc_res.status.success() {
311             self.fatal_proc_rec("pretty-printed source does not typecheck", &proc_res);
312         }
313
314         if !self.props.pretty_expanded { return }
315
316         // additionally, run `--pretty expanded` and try to build it.
317         let proc_res = self.print_source(srcs[round].clone(), "expanded");
318         if !proc_res.status.success() {
319             self.fatal_proc_rec("pretty-printing (expanded) failed", &proc_res);
320         }
321
322         let ProcRes{ stdout: expanded_src, .. } = proc_res;
323         let proc_res = self.typecheck_source(expanded_src);
324         if !proc_res.status.success() {
325             self.fatal_proc_rec(
326                 "pretty-printed source (expanded) does not typecheck",
327                 &proc_res);
328         }
329     }
330
331     fn print_source(&self,
332                     src: String,
333                     pretty_type: &str)
334                     -> ProcRes {
335         let aux_dir = self.aux_output_dir_name();
336         self.compose_and_run(self.make_pp_args(pretty_type.to_owned()),
337                              self.props.exec_env.clone(),
338                              self.config.compile_lib_path.to_str().unwrap(),
339                              Some(aux_dir.to_str().unwrap()),
340                              Some(src))
341     }
342
343     fn make_pp_args(&self,
344                     pretty_type: String)
345                     -> ProcArgs {
346         let aux_dir = self.aux_output_dir_name();
347         // FIXME (#9639): This needs to handle non-utf8 paths
348         let mut args = vec!["-".to_owned(),
349                             "-Zunstable-options".to_owned(),
350                             "--unpretty".to_owned(),
351                             pretty_type,
352                             format!("--target={}", self.config.target),
353                             "-L".to_owned(),
354                             aux_dir.to_str().unwrap().to_owned()];
355         args.extend(self.split_maybe_args(&self.config.target_rustcflags));
356         args.extend(self.props.compile_flags.iter().cloned());
357         return ProcArgs {
358             prog: self.config.rustc_path.to_str().unwrap().to_owned(),
359             args: args,
360         };
361     }
362
363     fn compare_source(&self,
364                       expected: &str,
365                       actual: &str) {
366         if expected != actual {
367             self.error("pretty-printed source does not match expected source");
368             println!("\n\
369 expected:\n\
370 ------------------------------------------\n\
371 {}\n\
372 ------------------------------------------\n\
373 actual:\n\
374 ------------------------------------------\n\
375 {}\n\
376 ------------------------------------------\n\
377 \n",
378                      expected, actual);
379             panic!();
380         }
381     }
382
383     fn typecheck_source(&self, src: String) -> ProcRes {
384         let args = self.make_typecheck_args();
385         self.compose_and_run_compiler(args, Some(src))
386     }
387
388     fn make_typecheck_args(&self) -> ProcArgs {
389         let aux_dir = self.aux_output_dir_name();
390         let target = if self.props.force_host {
391             &*self.config.host
392         } else {
393             &*self.config.target
394         };
395
396         let out_dir = self.output_base_name().with_extension("pretty-out");
397         let _ = fs::remove_dir_all(&out_dir);
398         create_dir_all(&out_dir).unwrap();
399
400         // FIXME (#9639): This needs to handle non-utf8 paths
401         let mut args = vec!["-".to_owned(),
402                             "-Zno-trans".to_owned(),
403                             "--out-dir".to_owned(),
404                             out_dir.to_str().unwrap().to_owned(),
405                             format!("--target={}", target),
406                             "-L".to_owned(),
407                             self.config.build_base.to_str().unwrap().to_owned(),
408                             "-L".to_owned(),
409                             aux_dir.to_str().unwrap().to_owned()];
410         if let Some(revision) = self.revision {
411             args.extend(vec![
412                 format!("--cfg"),
413                 format!("{}", revision),
414             ]);
415         }
416         args.extend(self.split_maybe_args(&self.config.target_rustcflags));
417         args.extend(self.props.compile_flags.iter().cloned());
418         // FIXME (#9639): This needs to handle non-utf8 paths
419         return ProcArgs {
420             prog: self.config.rustc_path.to_str().unwrap().to_owned(),
421             args: args,
422         };
423     }
424
425     fn run_debuginfo_gdb_test(&self) {
426         assert!(self.revision.is_none(), "revisions not relevant here");
427
428         let config = Config {
429             target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
430             host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
431             .. self.config.clone()
432         };
433
434         let test_cx = TestCx {
435             config: &config,
436             ..*self
437         };
438
439         test_cx.run_debuginfo_gdb_test_no_opt();
440     }
441
442     fn run_debuginfo_gdb_test_no_opt(&self) {
443         let prefixes = if self.config.gdb_native_rust {
444             // GDB with Rust
445             static PREFIXES: &'static [&'static str] = &["gdb", "gdbr"];
446             println!("NOTE: compiletest thinks it is using GDB with native rust support");
447             PREFIXES
448         } else {
449             // Generic GDB
450             static PREFIXES: &'static [&'static str] = &["gdb", "gdbg"];
451             println!("NOTE: compiletest thinks it is using GDB without native rust support");
452             PREFIXES
453         };
454
455         let DebuggerCommands {
456             commands,
457             check_lines,
458             breakpoint_lines
459         } = self.parse_debugger_commands(prefixes);
460         let mut cmds = commands.join("\n");
461
462         // compile test file (it should have 'compile-flags:-g' in the header)
463         let compiler_run_result = self.compile_test();
464         if !compiler_run_result.status.success() {
465             self.fatal_proc_rec("compilation failed!", &compiler_run_result);
466         }
467
468         let exe_file = self.make_exe_name();
469
470         let debugger_run_result;
471         match &*self.config.target {
472             "arm-linux-androideabi" | "armv7-linux-androideabi" | "aarch64-linux-android" => {
473
474                 cmds = cmds.replace("run", "continue");
475
476                 let tool_path = match self.config.android_cross_path.to_str() {
477                     Some(x) => x.to_owned(),
478                     None => self.fatal("cannot find android cross path")
479                 };
480
481                 // write debugger script
482                 let mut script_str = String::with_capacity(2048);
483                 script_str.push_str(&format!("set charset {}\n", Self::charset()));
484                 script_str.push_str(&format!("set sysroot {}\n", tool_path));
485                 script_str.push_str(&format!("file {}\n", exe_file.to_str().unwrap()));
486                 script_str.push_str("target remote :5039\n");
487                 script_str.push_str(&format!("set solib-search-path \
488                                               ./{}/stage2/lib/rustlib/{}/lib/\n",
489                                              self.config.host, self.config.target));
490                 for line in &breakpoint_lines {
491                     script_str.push_str(&format!("break {:?}:{}\n",
492                                                  self.testpaths.file.file_name()
493                                                  .unwrap()
494                                                  .to_string_lossy(),
495                                                  *line)[..]);
496                 }
497                 script_str.push_str(&cmds);
498                 script_str.push_str("\nquit\n");
499
500                 debug!("script_str = {}", script_str);
501                 self.dump_output_file(&script_str, "debugger.script");
502
503
504                 procsrv::run("",
505                              &self.config.adb_path,
506                              None,
507                              &[
508                                  "push".to_owned(),
509                                  exe_file.to_str().unwrap().to_owned(),
510                                  self.config.adb_test_dir.clone()
511                              ],
512                              Vec::new(),
513                              None)
514                     .expect(&format!("failed to exec `{:?}`", self.config.adb_path));
515
516                 procsrv::run("",
517                              &self.config.adb_path,
518                              None,
519                              &[
520                                  "forward".to_owned(),
521                                  "tcp:5039".to_owned(),
522                                  "tcp:5039".to_owned()
523                              ],
524                              Vec::new(),
525                              None)
526                     .expect(&format!("failed to exec `{:?}`", self.config.adb_path));
527
528                 let adb_arg = format!("export LD_LIBRARY_PATH={}; \
529                                        gdbserver{} :5039 {}/{}",
530                                       self.config.adb_test_dir.clone(),
531                                       if self.config.target.contains("aarch64")
532                                       {"64"} else {""},
533                                       self.config.adb_test_dir.clone(),
534                                       exe_file.file_name().unwrap().to_str()
535                                       .unwrap());
536
537                 let mut process = procsrv::run_background("",
538                                                           &self.config.adb_path
539                                                           ,
540                                                           None,
541                                                           &[
542                                                               "shell".to_owned(),
543                                                               adb_arg.clone()
544                                                           ],
545                                                           Vec::new(),
546                                                           None)
547                     .expect(&format!("failed to exec `{:?}`", self.config.adb_path));
548
549                 // Wait for the gdbserver to print out "Listening on port ..."
550                 // at which point we know that it's started and then we can
551                 // execute the debugger below.
552                 let mut stdout = BufReader::new(process.stdout.take().unwrap());
553                 let mut line = String::new();
554                 loop {
555                     line.truncate(0);
556                     stdout.read_line(&mut line).unwrap();
557                     if line.starts_with("Listening on port 5039") {
558                         break
559                     }
560                 }
561                 drop(stdout);
562
563                 let debugger_script = self.make_out_name("debugger.script");
564                 // FIXME (#9639): This needs to handle non-utf8 paths
565                 let debugger_opts =
566                     vec!["-quiet".to_owned(),
567                          "-batch".to_owned(),
568                          "-nx".to_owned(),
569                          format!("-command={}", debugger_script.to_str().unwrap())];
570
571                 let mut gdb_path = tool_path;
572                 gdb_path.push_str(&format!("/bin/{}-gdb", self.config.target));
573                 let procsrv::Result {
574                     out,
575                     err,
576                     status
577                 } = procsrv::run("",
578                                  &gdb_path,
579                                  None,
580                                  &debugger_opts,
581                                  Vec::new(),
582                                  None)
583                     .expect(&format!("failed to exec `{:?}`", gdb_path));
584                 let cmdline = {
585                     let cmdline = self.make_cmdline("",
586                                                     &format!("{}-gdb", self.config.target),
587                                                     &debugger_opts);
588                     logv(self.config, format!("executing {}", cmdline));
589                     cmdline
590                 };
591
592                 debugger_run_result = ProcRes {
593                     status: Status::Normal(status),
594                     stdout: out,
595                     stderr: err,
596                     cmdline: cmdline
597                 };
598                 if process.kill().is_err() {
599                     println!("Adb process is already finished.");
600                 }
601             }
602
603             _=> {
604                 let rust_src_root = self.find_rust_src_root()
605                                         .expect("Could not find Rust source root");
606                 let rust_pp_module_rel_path = Path::new("./src/etc");
607                 let rust_pp_module_abs_path = rust_src_root.join(rust_pp_module_rel_path)
608                                                            .to_str()
609                                                            .unwrap()
610                                                            .to_owned();
611                 // write debugger script
612                 let mut script_str = String::with_capacity(2048);
613                 script_str.push_str(&format!("set charset {}\n", Self::charset()));
614                 script_str.push_str("show version\n");
615
616                 match self.config.gdb_version {
617                     Some(version) => {
618                         println!("NOTE: compiletest thinks it is using GDB version {}",
619                                  version);
620
621                         if version > extract_gdb_version("7.4").unwrap() {
622                             // Add the directory containing the pretty printers to
623                             // GDB's script auto loading safe path
624                             script_str.push_str(
625                                 &format!("add-auto-load-safe-path {}\n",
626                                          rust_pp_module_abs_path.replace(r"\", r"\\"))
627                             );
628                         }
629                     }
630                     _ => {
631                         println!("NOTE: compiletest does not know which version of \
632                                   GDB it is using");
633                     }
634                 }
635
636                 // The following line actually doesn't have to do anything with
637                 // pretty printing, it just tells GDB to print values on one line:
638                 script_str.push_str("set print pretty off\n");
639
640                 // Add the pretty printer directory to GDB's source-file search path
641                 script_str.push_str(&format!("directory {}\n",
642                                              rust_pp_module_abs_path));
643
644                 // Load the target executable
645                 script_str.push_str(&format!("file {}\n",
646                                              exe_file.to_str().unwrap()
647                                              .replace(r"\", r"\\")));
648
649                 // Add line breakpoints
650                 for line in &breakpoint_lines {
651                     script_str.push_str(&format!("break '{}':{}\n",
652                                                  self.testpaths.file.file_name().unwrap()
653                                                  .to_string_lossy(),
654                                                  *line));
655                 }
656
657                 script_str.push_str(&cmds);
658                 script_str.push_str("\nquit\n");
659
660                 debug!("script_str = {}", script_str);
661                 self.dump_output_file(&script_str, "debugger.script");
662
663                 let debugger_script = self.make_out_name("debugger.script");
664
665                 // FIXME (#9639): This needs to handle non-utf8 paths
666                 let debugger_opts =
667                     vec!["-quiet".to_owned(),
668                          "-batch".to_owned(),
669                          "-nx".to_owned(),
670                          format!("-command={}", debugger_script.to_str().unwrap())];
671
672                 let proc_args = ProcArgs {
673                     prog: self.config.gdb.as_ref().unwrap().to_owned(),
674                     args: debugger_opts,
675                 };
676
677                 let environment = vec![("PYTHONPATH".to_owned(), rust_pp_module_abs_path)];
678
679                 debugger_run_result =
680                     self.compose_and_run(proc_args,
681                                          environment,
682                                          self.config.run_lib_path.to_str().unwrap(),
683                                          None,
684                                          None);
685             }
686         }
687
688         if !debugger_run_result.status.success() {
689             self.fatal("gdb failed to execute");
690         }
691
692         self.check_debugger_output(&debugger_run_result, &check_lines);
693     }
694
695     fn find_rust_src_root(&self) -> Option<PathBuf> {
696         let mut path = self.config.src_base.clone();
697         let path_postfix = Path::new("src/etc/lldb_batchmode.py");
698
699         while path.pop() {
700             if path.join(&path_postfix).is_file() {
701                 return Some(path);
702             }
703         }
704
705         return None;
706     }
707
708     fn run_debuginfo_lldb_test(&self) {
709         assert!(self.revision.is_none(), "revisions not relevant here");
710
711         if self.config.lldb_python_dir.is_none() {
712             self.fatal("Can't run LLDB test because LLDB's python path is not set.");
713         }
714
715         let config = Config {
716             target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
717             host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
718             .. self.config.clone()
719         };
720
721
722         let test_cx = TestCx {
723             config: &config,
724             ..*self
725         };
726
727         test_cx.run_debuginfo_lldb_test_no_opt();
728     }
729
730     fn run_debuginfo_lldb_test_no_opt(&self) {
731         // compile test file (it should have 'compile-flags:-g' in the header)
732         let compile_result = self.compile_test();
733         if !compile_result.status.success() {
734             self.fatal_proc_rec("compilation failed!", &compile_result);
735         }
736
737         let exe_file = self.make_exe_name();
738
739         match self.config.lldb_version {
740             Some(ref version) => {
741                 println!("NOTE: compiletest thinks it is using LLDB version {}",
742                          version);
743             }
744             _ => {
745                 println!("NOTE: compiletest does not know which version of \
746                           LLDB it is using");
747             }
748         }
749
750         // Parse debugger commands etc from test files
751         let DebuggerCommands {
752             commands,
753             check_lines,
754             breakpoint_lines,
755             ..
756         } = self.parse_debugger_commands(&["lldb"]);
757
758         // Write debugger script:
759         // We don't want to hang when calling `quit` while the process is still running
760         let mut script_str = String::from("settings set auto-confirm true\n");
761
762         // Make LLDB emit its version, so we have it documented in the test output
763         script_str.push_str("version\n");
764
765         // Switch LLDB into "Rust mode"
766         let rust_src_root = self.find_rust_src_root().expect("Could not find Rust source root");
767         let rust_pp_module_rel_path = Path::new("./src/etc/lldb_rust_formatters.py");
768         let rust_pp_module_abs_path = rust_src_root.join(rust_pp_module_rel_path)
769                                                    .to_str()
770                                                    .unwrap()
771                                                    .to_owned();
772
773         script_str.push_str(&format!("command script import {}\n",
774                                      &rust_pp_module_abs_path[..])[..]);
775         script_str.push_str("type summary add --no-value ");
776         script_str.push_str("--python-function lldb_rust_formatters.print_val ");
777         script_str.push_str("-x \".*\" --category Rust\n");
778         script_str.push_str("type category enable Rust\n");
779
780         // Set breakpoints on every line that contains the string "#break"
781         let source_file_name = self.testpaths.file.file_name().unwrap().to_string_lossy();
782         for line in &breakpoint_lines {
783             script_str.push_str(&format!("breakpoint set --file '{}' --line {}\n",
784                                          source_file_name,
785                                          line));
786         }
787
788         // Append the other commands
789         for line in &commands {
790             script_str.push_str(line);
791             script_str.push_str("\n");
792         }
793
794         // Finally, quit the debugger
795         script_str.push_str("\nquit\n");
796
797         // Write the script into a file
798         debug!("script_str = {}", script_str);
799         self.dump_output_file(&script_str, "debugger.script");
800         let debugger_script = self.make_out_name("debugger.script");
801
802         // Let LLDB execute the script via lldb_batchmode.py
803         let debugger_run_result = self.run_lldb(&exe_file,
804                                                 &debugger_script,
805                                                 &rust_src_root);
806
807         if !debugger_run_result.status.success() {
808             self.fatal_proc_rec("Error while running LLDB", &debugger_run_result);
809         }
810
811         self.check_debugger_output(&debugger_run_result, &check_lines);
812     }
813
814     fn run_lldb(&self,
815                 test_executable: &Path,
816                 debugger_script: &Path,
817                 rust_src_root: &Path)
818                 -> ProcRes {
819         // Prepare the lldb_batchmode which executes the debugger script
820         let lldb_script_path = rust_src_root.join("src/etc/lldb_batchmode.py");
821         self.cmd2procres(Command::new(&self.config.lldb_python)
822                          .arg(&lldb_script_path)
823                          .arg(test_executable)
824                          .arg(debugger_script)
825                          .env("PYTHONPATH",
826                               self.config.lldb_python_dir.as_ref().unwrap()))
827     }
828
829     fn cmd2procres(&self, cmd: &mut Command) -> ProcRes {
830         let (status, out, err) = match cmd.output() {
831             Ok(Output { status, stdout, stderr }) => {
832                 (status,
833                  String::from_utf8(stdout).unwrap(),
834                  String::from_utf8(stderr).unwrap())
835             },
836             Err(e) => {
837                 self.fatal(&format!("Failed to setup Python process for \
838                                       LLDB script: {}", e))
839             }
840         };
841
842         self.dump_output(&out, &err);
843         ProcRes {
844             status: Status::Normal(status),
845             stdout: out,
846             stderr: err,
847             cmdline: format!("{:?}", cmd)
848         }
849     }
850
851     fn parse_debugger_commands(&self, debugger_prefixes: &[&str]) -> DebuggerCommands {
852         let directives = debugger_prefixes.iter().map(|prefix| (
853             format!("{}-command", prefix),
854             format!("{}-check", prefix),
855         )).collect::<Vec<_>>();
856
857         let mut breakpoint_lines = vec![];
858         let mut commands = vec![];
859         let mut check_lines = vec![];
860         let mut counter = 1;
861         let reader = BufReader::new(File::open(&self.testpaths.file).unwrap());
862         for line in reader.lines() {
863             match line {
864                 Ok(line) => {
865                     if line.contains("#break") {
866                         breakpoint_lines.push(counter);
867                     }
868
869                     for &(ref command_directive, ref check_directive) in &directives {
870                         header::parse_name_value_directive(
871                             &line,
872                             &command_directive).map(|cmd| {
873                                 commands.push(cmd)
874                             });
875
876                         header::parse_name_value_directive(
877                             &line,
878                             &check_directive).map(|cmd| {
879                                 check_lines.push(cmd)
880                             });
881                     }
882                 }
883                 Err(e) => {
884                     self.fatal(&format!("Error while parsing debugger commands: {}", e))
885                 }
886             }
887             counter += 1;
888         }
889
890         DebuggerCommands {
891             commands: commands,
892             check_lines: check_lines,
893             breakpoint_lines: breakpoint_lines,
894         }
895     }
896
897     fn cleanup_debug_info_options(&self, options: &Option<String>) -> Option<String> {
898         if options.is_none() {
899             return None;
900         }
901
902         // Remove options that are either unwanted (-O) or may lead to duplicates due to RUSTFLAGS.
903         let options_to_remove = [
904             "-O".to_owned(),
905             "-g".to_owned(),
906             "--debuginfo".to_owned()
907         ];
908         let new_options =
909             self.split_maybe_args(options).into_iter()
910                                           .filter(|x| !options_to_remove.contains(x))
911                                           .collect::<Vec<String>>();
912
913         Some(new_options.join(" "))
914     }
915
916     fn check_debugger_output(&self, debugger_run_result: &ProcRes, check_lines: &[String]) {
917         let num_check_lines = check_lines.len();
918
919         let mut check_line_index = 0;
920         for line in debugger_run_result.stdout.lines() {
921             if check_line_index >= num_check_lines {
922                 break;
923             }
924
925             if check_single_line(line, &(check_lines[check_line_index])[..]) {
926                 check_line_index += 1;
927             }
928         }
929         if check_line_index != num_check_lines && num_check_lines > 0 {
930             self.fatal_proc_rec(&format!("line not found in debugger output: {}",
931                                          check_lines[check_line_index]),
932                                 debugger_run_result);
933         }
934
935         fn check_single_line(line: &str, check_line: &str) -> bool {
936             // Allow check lines to leave parts unspecified (e.g., uninitialized
937             // bits in the  wrong case of an enum) with the notation "[...]".
938             let line = line.trim();
939             let check_line = check_line.trim();
940             let can_start_anywhere = check_line.starts_with("[...]");
941             let can_end_anywhere = check_line.ends_with("[...]");
942
943             let check_fragments: Vec<&str> = check_line.split("[...]")
944                                                        .filter(|frag| !frag.is_empty())
945                                                        .collect();
946             if check_fragments.is_empty() {
947                 return true;
948             }
949
950             let (mut rest, first_fragment) = if can_start_anywhere {
951                 match line.find(check_fragments[0]) {
952                     Some(pos) => (&line[pos + check_fragments[0].len() ..], 1),
953                     None => return false
954                 }
955             } else {
956                 (line, 0)
957             };
958
959             for fragment_index in first_fragment .. check_fragments.len() {
960                 let current_fragment = check_fragments[fragment_index];
961                 match rest.find(current_fragment) {
962                     Some(pos) => {
963                         rest = &rest[pos + current_fragment.len() .. ];
964                     }
965                     None => return false
966                 }
967             }
968
969             if !can_end_anywhere && !rest.is_empty() {
970                 return false;
971             }
972
973             return true;
974         }
975     }
976
977     fn check_error_patterns(&self,
978                             output_to_check: &str,
979                             proc_res: &ProcRes) {
980         if self.props.error_patterns.is_empty() {
981             if self.props.must_compile_successfully {
982                 return
983             } else {
984                 self.fatal(&format!("no error pattern specified in {:?}",
985                                     self.testpaths.file.display()));
986             }
987         }
988         let mut next_err_idx = 0;
989         let mut next_err_pat = self.props.error_patterns[next_err_idx].trim();
990         let mut done = false;
991         for line in output_to_check.lines() {
992             if line.contains(next_err_pat) {
993                 debug!("found error pattern {}", next_err_pat);
994                 next_err_idx += 1;
995                 if next_err_idx == self.props.error_patterns.len() {
996                     debug!("found all error patterns");
997                     done = true;
998                     break;
999                 }
1000                 next_err_pat = self.props.error_patterns[next_err_idx].trim();
1001             }
1002         }
1003         if done { return; }
1004
1005         let missing_patterns = &self.props.error_patterns[next_err_idx..];
1006         if missing_patterns.len() == 1 {
1007             self.fatal_proc_rec(
1008                 &format!("error pattern '{}' not found!", missing_patterns[0]),
1009                 proc_res);
1010         } else {
1011             for pattern in missing_patterns {
1012                 self.error(&format!("error pattern '{}' not found!", *pattern));
1013             }
1014             self.fatal_proc_rec("multiple error patterns not found", proc_res);
1015         }
1016     }
1017
1018     fn check_no_compiler_crash(&self, proc_res: &ProcRes) {
1019         for line in proc_res.stderr.lines() {
1020             if line.contains("error: internal compiler error") {
1021                 self.fatal_proc_rec("compiler encountered internal error", proc_res);
1022             }
1023         }
1024     }
1025
1026     fn check_forbid_output(&self,
1027                            output_to_check: &str,
1028                            proc_res: &ProcRes) {
1029         for pat in &self.props.forbid_output {
1030             if output_to_check.contains(pat) {
1031                 self.fatal_proc_rec("forbidden pattern found in compiler output", proc_res);
1032             }
1033         }
1034     }
1035
1036     fn check_expected_errors(&self,
1037                              expected_errors: Vec<errors::Error>,
1038                              proc_res: &ProcRes) {
1039         if proc_res.status.success() &&
1040             expected_errors.iter().any(|x| x.kind == Some(ErrorKind::Error)) {
1041             self.fatal_proc_rec("process did not return an error status", proc_res);
1042         }
1043
1044         let file_name =
1045             format!("{}", self.testpaths.file.display())
1046             .replace(r"\", "/"); // on windows, translate all '\' path separators to '/'
1047
1048         // If the testcase being checked contains at least one expected "help"
1049         // message, then we'll ensure that all "help" messages are expected.
1050         // Otherwise, all "help" messages reported by the compiler will be ignored.
1051         // This logic also applies to "note" messages.
1052         let expect_help = expected_errors.iter().any(|ee| ee.kind == Some(ErrorKind::Help));
1053         let expect_note = expected_errors.iter().any(|ee| ee.kind == Some(ErrorKind::Note));
1054
1055         // Parse the JSON output from the compiler and extract out the messages.
1056         let actual_errors = json::parse_output(&file_name, &proc_res.stderr, &proc_res);
1057         let mut unexpected = Vec::new();
1058         let mut found = vec![false; expected_errors.len()];
1059         for actual_error in &actual_errors {
1060             let opt_index =
1061                 expected_errors
1062                 .iter()
1063                 .enumerate()
1064                 .position(|(index, expected_error)| {
1065                     !found[index] &&
1066                         actual_error.line_num == expected_error.line_num &&
1067                         (expected_error.kind.is_none() ||
1068                          actual_error.kind == expected_error.kind) &&
1069                         actual_error.msg.contains(&expected_error.msg)
1070                 });
1071
1072             match opt_index {
1073                 Some(index) => {
1074                     // found a match, everybody is happy
1075                     assert!(!found[index]);
1076                     found[index] = true;
1077                 }
1078
1079                 None => {
1080                     if self.is_unexpected_compiler_message(actual_error, expect_help, expect_note) {
1081                         self.error(
1082                             &format!("{}:{}: unexpected {:?}: '{}'",
1083                                      file_name,
1084                                      actual_error.line_num,
1085                                      actual_error.kind.as_ref()
1086                                      .map_or(String::from("message"),
1087                                              |k| k.to_string()),
1088                                      actual_error.msg));
1089                         unexpected.push(actual_error.clone());
1090                     }
1091                 }
1092             }
1093         }
1094
1095         let mut not_found = Vec::new();
1096         // anything not yet found is a problem
1097         for (index, expected_error) in expected_errors.iter().enumerate() {
1098             if !found[index] {
1099                 self.error(
1100                     &format!("{}:{}: expected {} not found: {}",
1101                              file_name,
1102                              expected_error.line_num,
1103                              expected_error.kind.as_ref()
1104                              .map_or("message".into(),
1105                                      |k| k.to_string()),
1106                              expected_error.msg));
1107                 not_found.push(expected_error.clone());
1108             }
1109         }
1110
1111         if unexpected.len() > 0 || not_found.len() > 0 {
1112             self.error(
1113                 &format!("{} unexpected errors found, {} expected errors not found",
1114                          unexpected.len(), not_found.len()));
1115             print!("status: {}\ncommand: {}\n",
1116                    proc_res.status, proc_res.cmdline);
1117             if unexpected.len() > 0 {
1118                 println!("unexpected errors (from JSON output): {:#?}\n", unexpected);
1119             }
1120             if not_found.len() > 0 {
1121                 println!("not found errors (from test file): {:#?}\n", not_found);
1122             }
1123             panic!();
1124         }
1125     }
1126
1127     /// Returns true if we should report an error about `actual_error`,
1128     /// which did not match any of the expected error. We always require
1129     /// errors/warnings to be explicitly listed, but only require
1130     /// helps/notes if there are explicit helps/notes given.
1131     fn is_unexpected_compiler_message(&self,
1132                                       actual_error: &Error,
1133                                       expect_help: bool,
1134                                       expect_note: bool)
1135                                       -> bool {
1136         match actual_error.kind {
1137             Some(ErrorKind::Help) => expect_help,
1138             Some(ErrorKind::Note) => expect_note,
1139             Some(ErrorKind::Error) => true,
1140             Some(ErrorKind::Warning) => true,
1141             Some(ErrorKind::Suggestion) => false,
1142             None => false
1143         }
1144     }
1145
1146     fn compile_test(&self) -> ProcRes {
1147         let aux_dir = self.aux_output_dir_name();
1148         // FIXME (#9639): This needs to handle non-utf8 paths
1149         let link_args = vec!["-L".to_owned(),
1150                              aux_dir.to_str().unwrap().to_owned()];
1151         let args = self.make_compile_args(link_args,
1152                                           &self.testpaths.file,
1153                                           TargetLocation::ThisFile(self.make_exe_name()));
1154         self.compose_and_run_compiler(args, None)
1155     }
1156
1157     fn document(&self, out_dir: &Path) -> ProcRes {
1158         if self.props.build_aux_docs {
1159             for rel_ab in &self.props.aux_builds {
1160                 let aux_testpaths = self.compute_aux_test_paths(rel_ab);
1161                 let aux_props = self.props.from_aux_file(&aux_testpaths.file, self.revision);
1162                 let aux_cx = TestCx {
1163                     config: self.config,
1164                     props: &aux_props,
1165                     testpaths: &aux_testpaths,
1166                     revision: self.revision
1167                 };
1168                 let auxres = aux_cx.document(out_dir);
1169                 if !auxres.status.success() {
1170                     return auxres;
1171                 }
1172             }
1173         }
1174
1175         let aux_dir = self.aux_output_dir_name();
1176         let mut args = vec!["-L".to_owned(),
1177                             aux_dir.to_str().unwrap().to_owned(),
1178                             "-o".to_owned(),
1179                             out_dir.to_str().unwrap().to_owned(),
1180                             self.testpaths.file.to_str().unwrap().to_owned()];
1181         args.extend(self.props.compile_flags.iter().cloned());
1182         let args = ProcArgs {
1183             prog: self.config.rustdoc_path.to_str().unwrap().to_owned(),
1184             args: args,
1185         };
1186         self.compose_and_run_compiler(args, None)
1187     }
1188
1189     fn exec_compiled_test(&self) -> ProcRes {
1190         let env = self.props.exec_env.clone();
1191
1192         match &*self.config.target {
1193
1194             "arm-linux-androideabi" | "armv7-linux-androideabi" | "aarch64-linux-android" => {
1195                 self._arm_exec_compiled_test(env)
1196             }
1197
1198             // This is pretty similar to below, we're transforming:
1199             //
1200             //      program arg1 arg2
1201             //
1202             // into
1203             //
1204             //      qemu-test-client run program:support-lib.so arg1 arg2
1205             //
1206             // The test-client program will upload `program` to the emulator
1207             // along with all other support libraries listed (in this case
1208             // `support-lib.so`. It will then execute the program on the
1209             // emulator with the arguments specified (in the environment we give
1210             // the process) and then report back the same result.
1211             _ if self.config.qemu_test_client.is_some() => {
1212                 let aux_dir = self.aux_output_dir_name();
1213                 let mut args = self.make_run_args();
1214                 let mut program = args.prog.clone();
1215                 if let Ok(entries) = aux_dir.read_dir() {
1216                     for entry in entries {
1217                         let entry = entry.unwrap();
1218                         if !entry.path().is_file() {
1219                             continue
1220                         }
1221                         program.push_str(":");
1222                         program.push_str(entry.path().to_str().unwrap());
1223                     }
1224                 }
1225                 args.args.insert(0, program);
1226                 args.args.insert(0, "run".to_string());
1227                 args.prog = self.config.qemu_test_client.clone().unwrap()
1228                                 .into_os_string().into_string().unwrap();
1229                 self.compose_and_run(args,
1230                                      env,
1231                                      self.config.run_lib_path.to_str().unwrap(),
1232                                      Some(aux_dir.to_str().unwrap()),
1233                                      None)
1234             }
1235             _ => {
1236                 let aux_dir = self.aux_output_dir_name();
1237                 self.compose_and_run(self.make_run_args(),
1238                                      env,
1239                                      self.config.run_lib_path.to_str().unwrap(),
1240                                      Some(aux_dir.to_str().unwrap()),
1241                                      None)
1242             }
1243         }
1244     }
1245
1246     /// For each `aux-build: foo/bar` annotation, we check to find the
1247     /// file in a `aux` directory relative to the test itself.
1248     fn compute_aux_test_paths(&self, rel_ab: &str) -> TestPaths {
1249         let test_ab = self.testpaths.file
1250                                     .parent()
1251                                     .expect("test file path has no parent")
1252                                     .join("auxiliary")
1253                                     .join(rel_ab);
1254         if !test_ab.exists() {
1255             self.fatal(&format!("aux-build `{}` source not found", test_ab.display()))
1256         }
1257
1258         TestPaths {
1259             file: test_ab,
1260             base: self.testpaths.base.clone(),
1261             relative_dir: self.testpaths.relative_dir
1262                                         .join("auxiliary")
1263                                         .join(rel_ab)
1264                                         .parent()
1265                                         .expect("aux-build path has no parent")
1266                                         .to_path_buf()
1267         }
1268     }
1269
1270     fn compose_and_run_compiler(&self, args: ProcArgs, input: Option<String>) -> ProcRes {
1271         if !self.props.aux_builds.is_empty() {
1272             create_dir_all(&self.aux_output_dir_name()).unwrap();
1273         }
1274
1275         let aux_dir = self.aux_output_dir_name();
1276         // FIXME (#9639): This needs to handle non-utf8 paths
1277         let extra_link_args = vec!["-L".to_owned(),
1278                                    aux_dir.to_str().unwrap().to_owned()];
1279
1280         for rel_ab in &self.props.aux_builds {
1281             let aux_testpaths = self.compute_aux_test_paths(rel_ab);
1282             let aux_props = self.props.from_aux_file(&aux_testpaths.file, self.revision);
1283             let mut crate_type = if aux_props.no_prefer_dynamic {
1284                 Vec::new()
1285             } else {
1286                 // We primarily compile all auxiliary libraries as dynamic libraries
1287                 // to avoid code size bloat and large binaries as much as possible
1288                 // for the test suite (otherwise including libstd statically in all
1289                 // executables takes up quite a bit of space).
1290                 //
1291                 // For targets like MUSL or Emscripten, however, there is no support for
1292                 // dynamic libraries so we just go back to building a normal library. Note,
1293                 // however, that for MUSL if the library is built with `force_host` then
1294                 // it's ok to be a dylib as the host should always support dylibs.
1295                 if (self.config.target.contains("musl") && !aux_props.force_host) ||
1296                     self.config.target.contains("emscripten")
1297                 {
1298                     vec!["--crate-type=lib".to_owned()]
1299                 } else {
1300                     vec!["--crate-type=dylib".to_owned()]
1301                 }
1302             };
1303             crate_type.extend(extra_link_args.clone());
1304             let aux_output = {
1305                 let f = self.make_lib_name(&self.testpaths.file);
1306                 let parent = f.parent().unwrap();
1307                 TargetLocation::ThisDirectory(parent.to_path_buf())
1308             };
1309             let aux_cx = TestCx {
1310                 config: self.config,
1311                 props: &aux_props,
1312                 testpaths: &aux_testpaths,
1313                 revision: self.revision
1314             };
1315             let aux_args = aux_cx.make_compile_args(crate_type, &aux_testpaths.file, aux_output);
1316             let auxres = aux_cx.compose_and_run(aux_args,
1317                                                 Vec::new(),
1318                                                 aux_cx.config.compile_lib_path.to_str().unwrap(),
1319                                                 Some(aux_dir.to_str().unwrap()),
1320                                                 None);
1321             if !auxres.status.success() {
1322                 self.fatal_proc_rec(
1323                     &format!("auxiliary build of {:?} failed to compile: ",
1324                              aux_testpaths.file.display()),
1325                     &auxres);
1326             }
1327
1328             match &*self.config.target {
1329                 "arm-linux-androideabi" | "armv7-linux-androideabi" | "aarch64-linux-android" => {
1330                     self._arm_push_aux_shared_library();
1331                 }
1332                 _ => {}
1333             }
1334         }
1335
1336         self.compose_and_run(args,
1337                              self.props.rustc_env.clone(),
1338                              self.config.compile_lib_path.to_str().unwrap(),
1339                              Some(aux_dir.to_str().unwrap()),
1340                              input)
1341     }
1342
1343
1344     fn compose_and_run(&self,
1345                        ProcArgs{ args, prog }: ProcArgs,
1346                        procenv: Vec<(String, String)> ,
1347                        lib_path: &str,
1348                        aux_path: Option<&str>,
1349                        input: Option<String>) -> ProcRes {
1350         return self.program_output(lib_path, prog, aux_path, args, procenv, input);
1351     }
1352
1353     fn make_compile_args(&self,
1354                          extras: Vec<String> ,
1355                          input_file: &Path,
1356                          output_file: TargetLocation)
1357                          -> ProcArgs
1358     {
1359         let target = if self.props.force_host {
1360             &*self.config.host
1361         } else {
1362             &*self.config.target
1363         };
1364
1365         // FIXME (#9639): This needs to handle non-utf8 paths
1366         let mut args = vec![input_file.to_str().unwrap().to_owned(),
1367                             "-L".to_owned(),
1368                             self.config.build_base.to_str().unwrap().to_owned()];
1369
1370         // Optionally prevent default --target if specified in test compile-flags.
1371         let custom_target = self.props.compile_flags
1372             .iter()
1373             .fold(false, |acc, ref x| acc || x.starts_with("--target"));
1374
1375         if !custom_target {
1376             args.extend(vec![
1377                 format!("--target={}", target),
1378             ]);
1379         }
1380
1381         if let Some(revision) = self.revision {
1382             args.extend(vec![
1383                 format!("--cfg"),
1384                 format!("{}", revision),
1385             ]);
1386         }
1387
1388         if let Some(ref incremental_dir) = self.props.incremental_dir {
1389             args.extend(vec![
1390                 format!("-Z"),
1391                 format!("incremental={}", incremental_dir.display()),
1392             ]);
1393         }
1394
1395
1396         match self.config.mode {
1397             CompileFail |
1398             ParseFail |
1399             RunPass |
1400             Incremental => {
1401                 // If we are extracting and matching errors in the new
1402                 // fashion, then you want JSON mode. Old-skool error
1403                 // patterns still match the raw compiler output.
1404                 if self.props.error_patterns.is_empty() {
1405                     args.extend(["--error-format",
1406                                  "json"]
1407                                 .iter()
1408                                 .map(|s| s.to_string()));
1409                 }
1410             }
1411             MirOpt => {
1412                 args.extend(["-Z",
1413                              "dump-mir=all",
1414                              "-Z",
1415                              "mir-opt-level=3",
1416                              "-Z"]
1417                             .iter()
1418                             .map(|s| s.to_string()));
1419
1420
1421                 let mir_dump_dir = self.get_mir_dump_dir();
1422                 create_dir_all(mir_dump_dir.as_path()).unwrap();
1423                 let mut dir_opt = "dump-mir-dir=".to_string();
1424                 dir_opt.push_str(mir_dump_dir.to_str().unwrap());
1425                 debug!("dir_opt: {:?}", dir_opt);
1426
1427                 args.push(dir_opt);
1428             }
1429             RunFail |
1430             RunPassValgrind |
1431             Pretty |
1432             DebugInfoGdb |
1433             DebugInfoLldb |
1434             Codegen |
1435             Rustdoc |
1436             RunMake |
1437             Ui |
1438             CodegenUnits => {
1439                 // do not use JSON output
1440             }
1441         }
1442
1443         args.extend_from_slice(&extras);
1444         if !self.props.no_prefer_dynamic {
1445             args.push("-C".to_owned());
1446             args.push("prefer-dynamic".to_owned());
1447         }
1448         let path = match output_file {
1449             TargetLocation::ThisFile(path) => {
1450                 args.push("-o".to_owned());
1451                 path
1452             }
1453             TargetLocation::ThisDirectory(path) => {
1454                 args.push("--out-dir".to_owned());
1455                 path
1456             }
1457         };
1458         args.push(path.to_str().unwrap().to_owned());
1459         if self.props.force_host {
1460             args.extend(self.split_maybe_args(&self.config.host_rustcflags));
1461         } else {
1462             args.extend(self.split_maybe_args(&self.config.target_rustcflags));
1463         }
1464         args.extend(self.props.compile_flags.iter().cloned());
1465         return ProcArgs {
1466             prog: self.config.rustc_path.to_str().unwrap().to_owned(),
1467             args: args,
1468         };
1469     }
1470
1471     fn make_lib_name(&self, auxfile: &Path) -> PathBuf {
1472         // what we return here is not particularly important, as it
1473         // happens; rustc ignores everything except for the directory.
1474         let auxname = self.output_testname(auxfile);
1475         self.aux_output_dir_name().join(&auxname)
1476     }
1477
1478     fn make_exe_name(&self) -> PathBuf {
1479         let mut f = self.output_base_name();
1480         // FIXME: This is using the host architecture exe suffix, not target!
1481         if self.config.target.contains("emscripten") {
1482             let mut fname = f.file_name().unwrap().to_os_string();
1483             fname.push(".js");
1484             f.set_file_name(&fname);
1485         } else if !env::consts::EXE_SUFFIX.is_empty() {
1486             let mut fname = f.file_name().unwrap().to_os_string();
1487             fname.push(env::consts::EXE_SUFFIX);
1488             f.set_file_name(&fname);
1489         }
1490         f
1491     }
1492
1493     fn make_run_args(&self) -> ProcArgs {
1494         // If we've got another tool to run under (valgrind),
1495         // then split apart its command
1496         let mut args = self.split_maybe_args(&self.config.runtool);
1497
1498         // If this is emscripten, then run tests under nodejs
1499         if self.config.target.contains("emscripten") {
1500             if let Some(ref p) = self.config.nodejs {
1501                 args.push(p.clone());
1502             } else {
1503                 self.fatal("no NodeJS binary found (--nodejs)");
1504             }
1505         }
1506
1507         let exe_file = self.make_exe_name();
1508
1509         // FIXME (#9639): This needs to handle non-utf8 paths
1510         args.push(exe_file.to_str().unwrap().to_owned());
1511
1512         // Add the arguments in the run_flags directive
1513         args.extend(self.split_maybe_args(&self.props.run_flags));
1514
1515         let prog = args.remove(0);
1516         return ProcArgs {
1517             prog: prog,
1518             args: args,
1519         };
1520     }
1521
1522     fn split_maybe_args(&self, argstr: &Option<String>) -> Vec<String> {
1523         match *argstr {
1524             Some(ref s) => {
1525                 s
1526                     .split(' ')
1527                     .filter_map(|s| {
1528                         if s.chars().all(|c| c.is_whitespace()) {
1529                             None
1530                         } else {
1531                             Some(s.to_owned())
1532                         }
1533                     }).collect()
1534             }
1535             None => Vec::new()
1536         }
1537     }
1538
1539     fn program_output(&self,
1540                       lib_path: &str,
1541                       prog: String,
1542                       aux_path: Option<&str>,
1543                       args: Vec<String>,
1544                       env: Vec<(String, String)>,
1545                       input: Option<String>)
1546                       -> ProcRes {
1547         let cmdline =
1548         {
1549             let cmdline = self.make_cmdline(lib_path,
1550                                             &prog,
1551                                             &args);
1552             logv(self.config, format!("executing {}", cmdline));
1553             cmdline
1554         };
1555         let procsrv::Result {
1556             out,
1557             err,
1558             status
1559         } = procsrv::run(lib_path,
1560                          &prog,
1561                          aux_path,
1562                          &args,
1563                          env,
1564                          input).expect(&format!("failed to exec `{}`", prog));
1565         self.dump_output(&out, &err);
1566         return ProcRes {
1567             status: Status::Normal(status),
1568             stdout: out,
1569             stderr: err,
1570             cmdline: cmdline,
1571         };
1572     }
1573
1574     fn make_cmdline(&self, libpath: &str, prog: &str, args: &[String]) -> String {
1575         use util;
1576
1577         // Linux and mac don't require adjusting the library search path
1578         if cfg!(unix) {
1579             format!("{} {}", prog, args.join(" "))
1580         } else {
1581             // Build the LD_LIBRARY_PATH variable as it would be seen on the command line
1582             // for diagnostic purposes
1583             fn lib_path_cmd_prefix(path: &str) -> String {
1584                 format!("{}=\"{}\"", util::lib_path_env_var(), util::make_new_path(path))
1585             }
1586
1587             format!("{} {} {}", lib_path_cmd_prefix(libpath), prog, args.join(" "))
1588         }
1589     }
1590
1591     fn dump_output(&self, out: &str, err: &str) {
1592         let revision = if let Some(r) = self.revision {
1593             format!("{}.", r)
1594         } else {
1595             String::new()
1596         };
1597
1598         self.dump_output_file(out, &format!("{}out", revision));
1599         self.dump_output_file(err, &format!("{}err", revision));
1600         self.maybe_dump_to_stdout(out, err);
1601     }
1602
1603     fn dump_output_file(&self,
1604                         out: &str,
1605                         extension: &str) {
1606         let outfile = self.make_out_name(extension);
1607         File::create(&outfile).unwrap().write_all(out.as_bytes()).unwrap();
1608     }
1609
1610     fn make_out_name(&self, extension: &str) -> PathBuf {
1611         self.output_base_name().with_extension(extension)
1612     }
1613
1614     fn aux_output_dir_name(&self) -> PathBuf {
1615         let f = self.output_base_name();
1616         let mut fname = f.file_name().unwrap().to_os_string();
1617         fname.push(&format!(".{}.libaux", self.config.mode));
1618         f.with_file_name(&fname)
1619     }
1620
1621     fn output_testname(&self, filepath: &Path) -> PathBuf {
1622         PathBuf::from(filepath.file_stem().unwrap())
1623     }
1624
1625     /// Given a test path like `compile-fail/foo/bar.rs` Returns a name like
1626     ///
1627     ///     <output>/foo/bar-stage1
1628     fn output_base_name(&self) -> PathBuf {
1629         let dir = self.config.build_base.join(&self.testpaths.relative_dir);
1630
1631         // Note: The directory `dir` is created during `collect_tests_from_dir`
1632         dir
1633             .join(&self.output_testname(&self.testpaths.file))
1634             .with_extension(&self.config.stage_id)
1635     }
1636
1637     fn maybe_dump_to_stdout(&self, out: &str, err: &str) {
1638         if self.config.verbose {
1639             println!("------{}------------------------------", "stdout");
1640             println!("{}", out);
1641             println!("------{}------------------------------", "stderr");
1642             println!("{}", err);
1643             println!("------------------------------------------");
1644         }
1645     }
1646
1647     fn error(&self, err: &str) {
1648         match self.revision {
1649             Some(rev) => println!("\nerror in revision `{}`: {}", rev, err),
1650             None => println!("\nerror: {}", err)
1651         }
1652     }
1653
1654     fn fatal(&self, err: &str) -> ! {
1655         self.error(err); panic!();
1656     }
1657
1658     fn fatal_proc_rec(&self, err: &str, proc_res: &ProcRes) -> ! {
1659         self.try_print_open_handles();
1660         self.error(err);
1661         proc_res.fatal(None);
1662     }
1663
1664     // This function is a poor man's attempt to debug rust-lang/rust#38620, if
1665     // that's closed then this should be deleted
1666     //
1667     // This is a very "opportunistic" debugging attempt, so we ignore all
1668     // errors here.
1669     fn try_print_open_handles(&self) {
1670         if !cfg!(windows) {
1671             return
1672         }
1673         if self.config.mode != Incremental {
1674             return
1675         }
1676
1677         let filename = match self.testpaths.file.file_stem() {
1678             Some(path) => path,
1679             None => return,
1680         };
1681
1682         let mut cmd = Command::new("handle.exe");
1683         cmd.arg("-a").arg("-u");
1684         cmd.arg(filename);
1685         cmd.arg("-nobanner");
1686         let output = match cmd.output() {
1687             Ok(output) => output,
1688             Err(_) => return,
1689         };
1690         println!("---------------------------------------------------");
1691         println!("ran extra command to debug rust-lang/rust#38620: ");
1692         println!("{:?}", cmd);
1693         println!("result: {}", output.status);
1694         println!("--- stdout ----------------------------------------");
1695         println!("{}", String::from_utf8_lossy(&output.stdout));
1696         println!("--- stderr ----------------------------------------");
1697         println!("{}", String::from_utf8_lossy(&output.stderr));
1698         println!("---------------------------------------------------");
1699     }
1700
1701     fn _arm_exec_compiled_test(&self, env: Vec<(String, String)>) -> ProcRes {
1702         let args = self.make_run_args();
1703         let cmdline = self.make_cmdline("", &args.prog, &args.args);
1704
1705         // get bare program string
1706         let mut tvec: Vec<String> = args.prog
1707                                         .split('/')
1708                                         .map(str::to_owned)
1709                                         .collect();
1710         let prog_short = tvec.pop().unwrap();
1711
1712         // copy to target
1713         let copy_result = procsrv::run("",
1714                                        &self.config.adb_path,
1715                                        None,
1716                                        &[
1717                                            "push".to_owned(),
1718                                            args.prog.clone(),
1719                                            self.config.adb_test_dir.clone()
1720                                        ],
1721                                        vec![("".to_owned(), "".to_owned())],
1722                                        Some("".to_owned()))
1723             .expect(&format!("failed to exec `{}`", self.config.adb_path));
1724
1725         if self.config.verbose {
1726             println!("push ({}) {} {} {}",
1727                      self.config.target,
1728                      args.prog,
1729                      copy_result.out,
1730                      copy_result.err);
1731         }
1732
1733         logv(self.config, format!("executing ({}) {}", self.config.target, cmdline));
1734
1735         let mut runargs = Vec::new();
1736
1737         // run test via adb_run_wrapper
1738         runargs.push("shell".to_owned());
1739         for (key, val) in env {
1740             runargs.push(format!("{}={}", key, val));
1741         }
1742         runargs.push(format!("{}/../adb_run_wrapper.sh", self.config.adb_test_dir));
1743         runargs.push(format!("{}", self.config.adb_test_dir));
1744         runargs.push(format!("{}", prog_short));
1745
1746         for tv in &args.args {
1747             runargs.push(tv.to_owned());
1748         }
1749         procsrv::run("",
1750                      &self.config.adb_path,
1751                      None,
1752                      &runargs,
1753                      vec![("".to_owned(), "".to_owned())], Some("".to_owned()))
1754             .expect(&format!("failed to exec `{}`", self.config.adb_path));
1755
1756         // get exitcode of result
1757         runargs = Vec::new();
1758         runargs.push("shell".to_owned());
1759         runargs.push("cat".to_owned());
1760         runargs.push(format!("{}/{}.exitcode", self.config.adb_test_dir, prog_short));
1761
1762         let procsrv::Result{ out: exitcode_out, err: _, status: _ } =
1763             procsrv::run("",
1764                          &self.config.adb_path,
1765                          None,
1766                          &runargs,
1767                          vec![("".to_owned(), "".to_owned())],
1768                          Some("".to_owned()))
1769             .expect(&format!("failed to exec `{}`", self.config.adb_path));
1770
1771         let mut exitcode: i32 = 0;
1772         for c in exitcode_out.chars() {
1773             if !c.is_numeric() { break; }
1774             exitcode = exitcode * 10 + match c {
1775                 '0' ... '9' => c as i32 - ('0' as i32),
1776                 _ => 101,
1777             }
1778         }
1779
1780         // get stdout of result
1781         runargs = Vec::new();
1782         runargs.push("shell".to_owned());
1783         runargs.push("cat".to_owned());
1784         runargs.push(format!("{}/{}.stdout", self.config.adb_test_dir, prog_short));
1785
1786         let procsrv::Result{ out: stdout_out, err: _, status: _ } =
1787             procsrv::run("",
1788                          &self.config.adb_path,
1789                          None,
1790                          &runargs,
1791                          vec![("".to_owned(), "".to_owned())],
1792                          Some("".to_owned()))
1793             .expect(&format!("failed to exec `{}`", self.config.adb_path));
1794
1795         // get stderr of result
1796         runargs = Vec::new();
1797         runargs.push("shell".to_owned());
1798         runargs.push("cat".to_owned());
1799         runargs.push(format!("{}/{}.stderr", self.config.adb_test_dir, prog_short));
1800
1801         let procsrv::Result{ out: stderr_out, err: _, status: _ } =
1802             procsrv::run("",
1803                          &self.config.adb_path,
1804                          None,
1805                          &runargs,
1806                          vec![("".to_owned(), "".to_owned())],
1807                          Some("".to_owned()))
1808             .expect(&format!("failed to exec `{}`", self.config.adb_path));
1809
1810         self.dump_output(&stdout_out, &stderr_out);
1811
1812         ProcRes {
1813             status: Status::Parsed(exitcode),
1814             stdout: stdout_out,
1815             stderr: stderr_out,
1816             cmdline: cmdline
1817         }
1818     }
1819
1820     fn _arm_push_aux_shared_library(&self) {
1821         let tdir = self.aux_output_dir_name();
1822
1823         let dirs = fs::read_dir(&tdir).unwrap();
1824         for file in dirs {
1825             let file = file.unwrap().path();
1826             if file.extension().and_then(|s| s.to_str()) == Some("so") {
1827                 // FIXME (#9639): This needs to handle non-utf8 paths
1828                 let copy_result = procsrv::run("",
1829                                                &self.config.adb_path,
1830                                                None,
1831                                                &[
1832                                                    "push".to_owned(),
1833                                                    file.to_str()
1834                                                        .unwrap()
1835                                                        .to_owned(),
1836                                                    self.config.adb_test_dir.to_owned(),
1837                                                ],
1838                                                vec![("".to_owned(),
1839                                                      "".to_owned())],
1840                                                Some("".to_owned()))
1841                     .expect(&format!("failed to exec `{}`", self.config.adb_path));
1842
1843                 if self.config.verbose {
1844                     println!("push ({}) {:?} {} {}",
1845                              self.config.target, file.display(),
1846                              copy_result.out, copy_result.err);
1847                 }
1848             }
1849         }
1850     }
1851
1852     // codegen tests (using FileCheck)
1853
1854     fn compile_test_and_save_ir(&self) -> ProcRes {
1855         let aux_dir = self.aux_output_dir_name();
1856         // FIXME (#9639): This needs to handle non-utf8 paths
1857         let mut link_args = vec!["-L".to_owned(),
1858                                  aux_dir.to_str().unwrap().to_owned()];
1859         let llvm_args = vec!["--emit=llvm-ir".to_owned(),];
1860         link_args.extend(llvm_args);
1861         let args = self.make_compile_args(link_args,
1862                                           &self.testpaths.file,
1863                                           TargetLocation::ThisDirectory(
1864                                               self.output_base_name().parent()
1865                                                                      .unwrap()
1866                                                                      .to_path_buf()));
1867         self.compose_and_run_compiler(args, None)
1868     }
1869
1870     fn check_ir_with_filecheck(&self) -> ProcRes {
1871         let irfile = self.output_base_name().with_extension("ll");
1872         let prog = self.config.llvm_filecheck.as_ref().unwrap();
1873         let proc_args = ProcArgs {
1874             // FIXME (#9639): This needs to handle non-utf8 paths
1875             prog: prog.to_str().unwrap().to_owned(),
1876             args: vec![format!("-input-file={}", irfile.to_str().unwrap()),
1877                        self.testpaths.file.to_str().unwrap().to_owned()]
1878         };
1879         self.compose_and_run(proc_args, Vec::new(), "", None, None)
1880     }
1881
1882     fn run_codegen_test(&self) {
1883         assert!(self.revision.is_none(), "revisions not relevant here");
1884
1885         if self.config.llvm_filecheck.is_none() {
1886             self.fatal("missing --llvm-filecheck");
1887         }
1888
1889         let mut proc_res = self.compile_test_and_save_ir();
1890         if !proc_res.status.success() {
1891             self.fatal_proc_rec("compilation failed!", &proc_res);
1892         }
1893
1894         proc_res = self.check_ir_with_filecheck();
1895         if !proc_res.status.success() {
1896             self.fatal_proc_rec("verification with 'FileCheck' failed", &proc_res);
1897         }
1898     }
1899
1900     fn charset() -> &'static str {
1901         // FreeBSD 10.1 defaults to GDB 6.1.1 which doesn't support "auto" charset
1902         if cfg!(target_os = "bitrig") {
1903             "auto"
1904         } else if cfg!(target_os = "freebsd") {
1905             "ISO-8859-1"
1906         } else {
1907             "UTF-8"
1908         }
1909     }
1910
1911     fn run_rustdoc_test(&self) {
1912         assert!(self.revision.is_none(), "revisions not relevant here");
1913
1914         let out_dir = self.output_base_name();
1915         let _ = fs::remove_dir_all(&out_dir);
1916         create_dir_all(&out_dir).unwrap();
1917
1918         let proc_res = self.document(&out_dir);
1919         if !proc_res.status.success() {
1920             self.fatal_proc_rec("rustdoc failed!", &proc_res);
1921         }
1922
1923         if self.props.check_test_line_numbers_match == true {
1924             self.check_rustdoc_test_option(proc_res);
1925         } else {
1926             let root = self.find_rust_src_root().unwrap();
1927             let res = self.cmd2procres(Command::new(&self.config.docck_python)
1928                                        .arg(root.join("src/etc/htmldocck.py"))
1929                                        .arg(out_dir)
1930                                        .arg(&self.testpaths.file));
1931             if !res.status.success() {
1932                 self.fatal_proc_rec("htmldocck failed!", &res);
1933             }
1934         }
1935     }
1936
1937     fn get_lines<P: AsRef<Path>>(&self, path: &P,
1938                                  mut other_files: Option<&mut Vec<String>>) -> Vec<usize> {
1939         let mut file = fs::File::open(path)
1940                                 .expect("markdown_test_output_check_entry File::open failed");
1941         let mut content = String::new();
1942         file.read_to_string(&mut content)
1943             .expect("markdown_test_output_check_entry read_to_string failed");
1944         let mut ignore = false;
1945         content.lines()
1946                .enumerate()
1947                .filter_map(|(line_nb, line)| {
1948                    if (line.trim_left().starts_with("pub mod ") ||
1949                        line.trim_left().starts_with("mod ")) &&
1950                       line.ends_with(";") {
1951                        if let Some(ref mut other_files) = other_files {
1952                            other_files.push(line.rsplit("mod ")
1953                                       .next()
1954                                       .unwrap()
1955                                       .replace(";", ""));
1956                        }
1957                        None
1958                    } else {
1959                        let sline = line.split("///").last().unwrap_or("");
1960                        let line = sline.trim_left();
1961                        if line.starts_with("```") {
1962                            if ignore {
1963                                ignore = false;
1964                                None
1965                            } else {
1966                                ignore = true;
1967                                Some(line_nb + 1)
1968                            }
1969                        } else {
1970                            None
1971                        }
1972                    }
1973                })
1974                .collect()
1975     }
1976
1977     fn check_rustdoc_test_option(&self, res: ProcRes) {
1978         let mut other_files = Vec::new();
1979         let mut files: HashMap<String, Vec<usize>> = HashMap::new();
1980         let cwd = env::current_dir().unwrap();
1981         files.insert(self.testpaths.file.strip_prefix(&cwd)
1982                                         .unwrap_or(&self.testpaths.file)
1983                                         .to_str()
1984                                         .unwrap()
1985                                         .replace('\\', "/"),
1986                      self.get_lines(&self.testpaths.file, Some(&mut other_files)));
1987         for other_file in other_files {
1988             let mut path = self.testpaths.file.clone();
1989             path.set_file_name(&format!("{}.rs", other_file));
1990             files.insert(path.strip_prefix(&cwd)
1991                              .unwrap_or(&path)
1992                              .to_str()
1993                              .unwrap()
1994                              .replace('\\', "/"),
1995                          self.get_lines(&path, None));
1996         }
1997
1998         let mut tested = 0;
1999         for _ in res.stdout.split("\n")
2000                            .filter(|s| s.starts_with("test "))
2001                            .inspect(|s| {
2002                                let tmp: Vec<&str> = s.split(" - ").collect();
2003                                if tmp.len() == 2 {
2004                                    let path = tmp[0].rsplit("test ").next().unwrap();
2005                                    if let Some(ref mut v) = files.get_mut(
2006                                                                 &path.replace('\\', "/")) {
2007                                        tested += 1;
2008                                        let mut iter = tmp[1].split("(line ");
2009                                        iter.next();
2010                                        let line = iter.next()
2011                                                       .unwrap_or(")")
2012                                                       .split(")")
2013                                                       .next()
2014                                                       .unwrap_or("0")
2015                                                       .parse()
2016                                                       .unwrap_or(0);
2017                                        if let Ok(pos) = v.binary_search(&line) {
2018                                            v.remove(pos);
2019                                        } else {
2020                                            self.fatal_proc_rec(
2021                                                &format!("Not found doc test: \"{}\" in \"{}\":{:?}",
2022                                                         s, path, v),
2023                                                &res);
2024                                        }
2025                                    }
2026                                }
2027                            }) {}
2028         if tested == 0 {
2029             self.fatal_proc_rec(&format!("No test has been found... {:?}", files), &res);
2030         } else {
2031             for (entry, v) in &files {
2032                 if v.len() != 0 {
2033                     self.fatal_proc_rec(&format!("Not found test at line{} \"{}\":{:?}",
2034                                                  if v.len() > 1 { "s" } else { "" }, entry, v),
2035                                         &res);
2036                 }
2037             }
2038         }
2039     }
2040
2041     fn run_codegen_units_test(&self) {
2042         assert!(self.revision.is_none(), "revisions not relevant here");
2043
2044         let proc_res = self.compile_test();
2045
2046         if !proc_res.status.success() {
2047             self.fatal_proc_rec("compilation failed!", &proc_res);
2048         }
2049
2050         self.check_no_compiler_crash(&proc_res);
2051
2052         const PREFIX: &'static str = "TRANS_ITEM ";
2053         const CGU_MARKER: &'static str = "@@";
2054
2055         let actual: Vec<TransItem> = proc_res
2056             .stdout
2057             .lines()
2058             .filter(|line| line.starts_with(PREFIX))
2059             .map(str_to_trans_item)
2060             .collect();
2061
2062         let expected: Vec<TransItem> = errors::load_errors(&self.testpaths.file, None)
2063             .iter()
2064             .map(|e| str_to_trans_item(&e.msg[..]))
2065             .collect();
2066
2067         let mut missing = Vec::new();
2068         let mut wrong_cgus = Vec::new();
2069
2070         for expected_item in &expected {
2071             let actual_item_with_same_name = actual.iter()
2072                                                    .find(|ti| ti.name == expected_item.name);
2073
2074             if let Some(actual_item) = actual_item_with_same_name {
2075                 if !expected_item.codegen_units.is_empty() {
2076                     // Also check for codegen units
2077                     if expected_item.codegen_units != actual_item.codegen_units {
2078                         wrong_cgus.push((expected_item.clone(), actual_item.clone()));
2079                     }
2080                 }
2081             } else {
2082                 missing.push(expected_item.string.clone());
2083             }
2084         }
2085
2086         let unexpected: Vec<_> =
2087             actual.iter()
2088                   .filter(|acgu| !expected.iter().any(|ecgu| acgu.name == ecgu.name))
2089                   .map(|acgu| acgu.string.clone())
2090                   .collect();
2091
2092         if !missing.is_empty() {
2093             missing.sort();
2094
2095             println!("\nThese items should have been contained but were not:\n");
2096
2097             for item in &missing {
2098                 println!("{}", item);
2099             }
2100
2101             println!("\n");
2102         }
2103
2104         if !unexpected.is_empty() {
2105             let sorted = {
2106                 let mut sorted = unexpected.clone();
2107                 sorted.sort();
2108                 sorted
2109             };
2110
2111             println!("\nThese items were contained but should not have been:\n");
2112
2113             for item in sorted {
2114                 println!("{}", item);
2115             }
2116
2117             println!("\n");
2118         }
2119
2120         if !wrong_cgus.is_empty() {
2121             wrong_cgus.sort_by_key(|pair| pair.0.name.clone());
2122             println!("\nThe following items were assigned to wrong codegen units:\n");
2123
2124             for &(ref expected_item, ref actual_item) in &wrong_cgus {
2125                 println!("{}", expected_item.name);
2126                 println!("  expected: {}", codegen_units_to_str(&expected_item.codegen_units));
2127                 println!("  actual:   {}", codegen_units_to_str(&actual_item.codegen_units));
2128                 println!("");
2129             }
2130         }
2131
2132         if !(missing.is_empty() && unexpected.is_empty() && wrong_cgus.is_empty())
2133         {
2134             panic!();
2135         }
2136
2137         #[derive(Clone, Eq, PartialEq)]
2138         struct TransItem {
2139             name: String,
2140             codegen_units: HashSet<String>,
2141             string: String,
2142         }
2143
2144         // [TRANS_ITEM] name [@@ (cgu)+]
2145         fn str_to_trans_item(s: &str) -> TransItem {
2146             let s = if s.starts_with(PREFIX) {
2147                 (&s[PREFIX.len()..]).trim()
2148             } else {
2149                 s.trim()
2150             };
2151
2152             let full_string = format!("{}{}", PREFIX, s.trim().to_owned());
2153
2154             let parts: Vec<&str> = s.split(CGU_MARKER)
2155                                     .map(str::trim)
2156                                     .filter(|s| !s.is_empty())
2157                                     .collect();
2158
2159             let name = parts[0].trim();
2160
2161             let cgus = if parts.len() > 1 {
2162                 let cgus_str = parts[1];
2163
2164                 cgus_str.split(" ")
2165                         .map(str::trim)
2166                         .filter(|s| !s.is_empty())
2167                         .map(str::to_owned)
2168                         .collect()
2169             }
2170             else {
2171                 HashSet::new()
2172             };
2173
2174             TransItem {
2175                 name: name.to_owned(),
2176                 codegen_units: cgus,
2177                 string: full_string,
2178             }
2179         }
2180
2181         fn codegen_units_to_str(cgus: &HashSet<String>) -> String
2182         {
2183             let mut cgus: Vec<_> = cgus.iter().collect();
2184             cgus.sort();
2185
2186             let mut string = String::new();
2187             for cgu in cgus {
2188                 string.push_str(&cgu[..]);
2189                 string.push_str(" ");
2190             }
2191
2192             string
2193         }
2194     }
2195
2196     fn init_incremental_test(&self) {
2197         // (See `run_incremental_test` for an overview of how incremental tests work.)
2198
2199         // Before any of the revisions have executed, create the
2200         // incremental workproduct directory.  Delete any old
2201         // incremental work products that may be there from prior
2202         // runs.
2203         let incremental_dir = self.incremental_dir();
2204         if incremental_dir.exists() {
2205             // Canonicalizing the path will convert it to the //?/ format
2206             // on Windows, which enables paths longer than 260 character
2207             let canonicalized = incremental_dir.canonicalize().unwrap();
2208             fs::remove_dir_all(canonicalized).unwrap();
2209         }
2210         fs::create_dir_all(&incremental_dir).unwrap();
2211
2212         if self.config.verbose {
2213             print!("init_incremental_test: incremental_dir={}", incremental_dir.display());
2214         }
2215     }
2216
2217     fn run_incremental_test(&self) {
2218         // Basic plan for a test incremental/foo/bar.rs:
2219         // - load list of revisions rpass1, cfail2, rpass3
2220         //   - each should begin with `rpass`, `cfail`, or `cfail`
2221         //   - if `rpass`, expect compile and execution to succeed
2222         //   - if `cfail`, expect compilation to fail
2223         //   - if `rfail`, expect execution to fail
2224         // - create a directory build/foo/bar.incremental
2225         // - compile foo/bar.rs with -Z incremental=.../foo/bar.incremental and -C rpass1
2226         //   - because name of revision starts with "rpass", expect success
2227         // - compile foo/bar.rs with -Z incremental=.../foo/bar.incremental and -C cfail2
2228         //   - because name of revision starts with "cfail", expect an error
2229         //   - load expected errors as usual, but filter for those that end in `[rfail2]`
2230         // - compile foo/bar.rs with -Z incremental=.../foo/bar.incremental and -C rpass3
2231         //   - because name of revision starts with "rpass", expect success
2232         // - execute build/foo/bar.exe and save output
2233         //
2234         // FIXME -- use non-incremental mode as an oracle? That doesn't apply
2235         // to #[rustc_dirty] and clean tests I guess
2236
2237         let revision = self.revision.expect("incremental tests require a list of revisions");
2238
2239         // Incremental workproduct directory should have already been created.
2240         let incremental_dir = self.incremental_dir();
2241         assert!(incremental_dir.exists(), "init_incremental_test failed to create incremental dir");
2242
2243         // Add an extra flag pointing at the incremental directory.
2244         let mut revision_props = self.props.clone();
2245         revision_props.incremental_dir = Some(incremental_dir);
2246         revision_props.compile_flags.push(String::from("-Zincremental-info"));
2247
2248         let revision_cx = TestCx {
2249             config: self.config,
2250             props: &revision_props,
2251             testpaths: self.testpaths,
2252             revision: self.revision,
2253         };
2254
2255         if self.config.verbose {
2256             print!("revision={:?} revision_props={:#?}", revision, revision_props);
2257         }
2258
2259         if revision.starts_with("rpass") {
2260             revision_cx.run_rpass_test();
2261         } else if revision.starts_with("rfail") {
2262             revision_cx.run_rfail_test();
2263         } else if revision.starts_with("cfail") {
2264             revision_cx.run_cfail_test();
2265         } else {
2266             revision_cx.fatal(
2267                 "revision name must begin with rpass, rfail, or cfail");
2268         }
2269     }
2270
2271     /// Directory where incremental work products are stored.
2272     fn incremental_dir(&self) -> PathBuf {
2273         self.output_base_name().with_extension("inc")
2274     }
2275
2276     fn run_rmake_test(&self) {
2277         // FIXME(#11094): we should fix these tests
2278         if self.config.host != self.config.target {
2279             return
2280         }
2281
2282         let cwd = env::current_dir().unwrap();
2283         let src_root = self.config.src_base.parent().unwrap()
2284                                            .parent().unwrap()
2285                                            .parent().unwrap();
2286         let src_root = cwd.join(&src_root);
2287
2288         let tmpdir = cwd.join(self.output_base_name());
2289         if tmpdir.exists() {
2290             self.aggressive_rm_rf(&tmpdir).unwrap();
2291         }
2292         create_dir_all(&tmpdir).unwrap();
2293
2294         let host = &self.config.host;
2295         let make = if host.contains("bitrig") || host.contains("dragonfly") ||
2296             host.contains("freebsd") || host.contains("netbsd") ||
2297             host.contains("openbsd") {
2298             "gmake"
2299         } else {
2300             "make"
2301         };
2302
2303         let mut cmd = Command::new(make);
2304         cmd.current_dir(&self.testpaths.file)
2305            .env("TARGET", &self.config.target)
2306            .env("PYTHON", &self.config.docck_python)
2307            .env("S", src_root)
2308            .env("RUST_BUILD_STAGE", &self.config.stage_id)
2309            .env("RUSTC", cwd.join(&self.config.rustc_path))
2310            .env("RUSTDOC", cwd.join(&self.config.rustdoc_path))
2311            .env("TMPDIR", &tmpdir)
2312            .env("LD_LIB_PATH_ENVVAR", procsrv::dylib_env_var())
2313            .env("HOST_RPATH_DIR", cwd.join(&self.config.compile_lib_path))
2314            .env("TARGET_RPATH_DIR", cwd.join(&self.config.run_lib_path))
2315            .env("LLVM_COMPONENTS", &self.config.llvm_components)
2316            .env("LLVM_CXXFLAGS", &self.config.llvm_cxxflags);
2317
2318         // We don't want RUSTFLAGS set from the outside to interfere with
2319         // compiler flags set in the test cases:
2320         cmd.env_remove("RUSTFLAGS");
2321
2322         if self.config.target.contains("msvc") {
2323             // We need to pass a path to `lib.exe`, so assume that `cc` is `cl.exe`
2324             // and that `lib.exe` lives next to it.
2325             let lib = Path::new(&self.config.cc).parent().unwrap().join("lib.exe");
2326
2327             // MSYS doesn't like passing flags of the form `/foo` as it thinks it's
2328             // a path and instead passes `C:\msys64\foo`, so convert all
2329             // `/`-arguments to MSVC here to `-` arguments.
2330             let cflags = self.config.cflags.split(' ').map(|s| s.replace("/", "-"))
2331                                                  .collect::<Vec<_>>().join(" ");
2332
2333             cmd.env("IS_MSVC", "1")
2334                .env("IS_WINDOWS", "1")
2335                .env("MSVC_LIB", format!("'{}' -nologo", lib.display()))
2336                .env("CC", format!("'{}' {}", self.config.cc, cflags))
2337                .env("CXX", &self.config.cxx);
2338         } else {
2339             cmd.env("CC", format!("{} {}", self.config.cc, self.config.cflags))
2340                .env("CXX", format!("{} {}", self.config.cxx, self.config.cflags));
2341
2342             if self.config.target.contains("windows") {
2343                 cmd.env("IS_WINDOWS", "1");
2344             }
2345         }
2346
2347         let output = cmd.output().expect("failed to spawn `make`");
2348         if !output.status.success() {
2349             let res = ProcRes {
2350                 status: Status::Normal(output.status),
2351                 stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
2352                 stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
2353                 cmdline: format!("{:?}", cmd),
2354             };
2355             self.fatal_proc_rec("make failed", &res);
2356         }
2357     }
2358
2359     fn aggressive_rm_rf(&self, path: &Path) -> io::Result<()> {
2360         for e in path.read_dir()? {
2361             let entry = e?;
2362             let path = entry.path();
2363             if entry.file_type()?.is_dir() {
2364                 self.aggressive_rm_rf(&path)?;
2365             } else {
2366                 // Remove readonly files as well on windows (by default we can't)
2367                 fs::remove_file(&path).or_else(|e| {
2368                     if cfg!(windows) && e.kind() == io::ErrorKind::PermissionDenied {
2369                         let mut meta = entry.metadata()?.permissions();
2370                         meta.set_readonly(false);
2371                         fs::set_permissions(&path, meta)?;
2372                         fs::remove_file(&path)
2373                     } else {
2374                         Err(e)
2375                     }
2376                 })?;
2377             }
2378         }
2379         fs::remove_dir(path)
2380     }
2381
2382     fn run_ui_test(&self) {
2383         println!("ui: {}", self.testpaths.file.display());
2384
2385         let proc_res = self.compile_test();
2386
2387         let expected_stderr_path = self.expected_output_path("stderr");
2388         let expected_stderr = self.load_expected_output(&expected_stderr_path);
2389
2390         let expected_stdout_path = self.expected_output_path("stdout");
2391         let expected_stdout = self.load_expected_output(&expected_stdout_path);
2392
2393         let normalized_stdout = self.normalize_output(&proc_res.stdout);
2394         let normalized_stderr = self.normalize_output(&proc_res.stderr);
2395
2396         let mut errors = 0;
2397         errors += self.compare_output("stdout", &normalized_stdout, &expected_stdout);
2398         errors += self.compare_output("stderr", &normalized_stderr, &expected_stderr);
2399
2400         if errors > 0 {
2401             println!("To update references, run this command from build directory:");
2402             let relative_path_to_file =
2403                 self.testpaths.relative_dir
2404                               .join(self.testpaths.file.file_name().unwrap());
2405             println!("{}/update-references.sh '{}' '{}'",
2406                      self.config.src_base.display(),
2407                      self.config.build_base.display(),
2408                      relative_path_to_file.display());
2409             self.fatal_proc_rec(&format!("{} errors occurred comparing output.", errors),
2410                                 &proc_res);
2411         }
2412     }
2413
2414     fn run_mir_opt_test(&self) {
2415         let proc_res = self.compile_test();
2416
2417         if !proc_res.status.success() {
2418             self.fatal_proc_rec("compilation failed!", &proc_res);
2419         }
2420
2421         let proc_res = self.exec_compiled_test();
2422
2423         if !proc_res.status.success() {
2424             self.fatal_proc_rec("test run failed!", &proc_res);
2425         }
2426         self.check_mir_dump();
2427     }
2428
2429     fn check_mir_dump(&self) {
2430         let mut test_file_contents = String::new();
2431         fs::File::open(self.testpaths.file.clone()).unwrap()
2432                                                    .read_to_string(&mut test_file_contents)
2433                                                    .unwrap();
2434         if let Some(idx) =  test_file_contents.find("// END RUST SOURCE") {
2435             let (_, tests_text) = test_file_contents.split_at(idx + "// END_RUST SOURCE".len());
2436             let tests_text_str = String::from(tests_text);
2437             let mut curr_test : Option<&str> = None;
2438             let mut curr_test_contents = Vec::new();
2439             for l in tests_text_str.lines() {
2440                 debug!("line: {:?}", l);
2441                 if l.starts_with("// START ") {
2442                     let (_, t) = l.split_at("// START ".len());
2443                     curr_test = Some(t);
2444                 } else if l.starts_with("// END") {
2445                     let (_, t) = l.split_at("// END ".len());
2446                     if Some(t) != curr_test {
2447                         panic!("mismatched START END test name");
2448                     }
2449                     self.compare_mir_test_output(curr_test.unwrap(), &curr_test_contents);
2450                     curr_test = None;
2451                     curr_test_contents.clear();
2452                 } else if l.is_empty() {
2453                     // ignore
2454                 } else if l.starts_with("// ") {
2455                     let (_, test_content) = l.split_at("// ".len());
2456                     curr_test_contents.push(test_content);
2457                 }
2458             }
2459         }
2460     }
2461
2462     fn check_mir_test_timestamp(&self, test_name: &str, output_file: &Path) {
2463         let t = |file| FileTime::from_last_modification_time(&fs::metadata(file).unwrap());
2464         let source_file = &self.testpaths.file;
2465         let output_time = t(output_file);
2466         let source_time = t(source_file);
2467         if source_time > output_time {
2468             debug!("source file time: {:?} output file time: {:?}", source_time, output_time);
2469             panic!("test source file `{}` is newer than potentially stale output file `{}`.",
2470                    source_file.display(), test_name);
2471         }
2472     }
2473
2474     fn compare_mir_test_output(&self, test_name: &str, expected_content: &Vec<&str>) {
2475         let mut output_file = PathBuf::new();
2476         output_file.push(self.get_mir_dump_dir());
2477         output_file.push(test_name);
2478         debug!("comparing the contests of: {:?}", output_file);
2479         debug!("with: {:?}", expected_content);
2480         self.check_mir_test_timestamp(test_name, &output_file);
2481
2482         let mut dumped_file = fs::File::open(output_file.clone()).unwrap();
2483         let mut dumped_string = String::new();
2484         dumped_file.read_to_string(&mut dumped_string).unwrap();
2485         let mut dumped_lines = dumped_string.lines().filter(|l| !l.is_empty());
2486         let mut expected_lines = expected_content.iter().filter(|l| !l.is_empty());
2487
2488         // We expect each non-empty line from expected_content to appear
2489         // in the dump in order, but there may be extra lines interleaved
2490         while let Some(expected_line) = expected_lines.next() {
2491             let e_norm = normalize_mir_line(expected_line);
2492             if e_norm.is_empty() {
2493                 continue;
2494             };
2495             let mut found = false;
2496             while let Some(dumped_line) = dumped_lines.next() {
2497                 let d_norm = normalize_mir_line(dumped_line);
2498                 debug!("found: {:?}", d_norm);
2499                 debug!("expected: {:?}", e_norm);
2500                 if e_norm == d_norm {
2501                     found = true;
2502                     break;
2503                 };
2504             }
2505             if !found {
2506                 let normalize_all = dumped_string.lines()
2507                                                  .map(nocomment_mir_line)
2508                                                  .filter(|l| !l.is_empty())
2509                                                  .collect::<Vec<_>>()
2510                                                  .join("\n");
2511                 panic!("ran out of mir dump output to match against.\n\
2512                         Did not find expected line: {:?}\n\
2513                         Expected:\n{}\n\
2514                         Actual:\n{}",
2515                         expected_line,
2516                         expected_content.join("\n"),
2517                         normalize_all);
2518             }
2519         }
2520     }
2521
2522     fn get_mir_dump_dir(&self) -> PathBuf {
2523         let mut mir_dump_dir = PathBuf::from(self.config.build_base
2524                                                     .as_path()
2525                                                     .to_str()
2526                                                     .unwrap());
2527         debug!("input_file: {:?}", self.testpaths.file);
2528         mir_dump_dir.push(self.testpaths.file.file_stem().unwrap().to_str().unwrap());
2529         mir_dump_dir
2530     }
2531
2532     fn normalize_output(&self, output: &str) -> String {
2533         let parent_dir = self.testpaths.file.parent().unwrap();
2534         let parent_dir_str = parent_dir.display().to_string();
2535         output.replace(&parent_dir_str, "$DIR")
2536               .replace("\\", "/") // normalize for paths on windows
2537               .replace("\r\n", "\n") // normalize for linebreaks on windows
2538               .replace("\t", "\\t") // makes tabs visible
2539     }
2540
2541     fn expected_output_path(&self, kind: &str) -> PathBuf {
2542         let extension = match self.revision {
2543             Some(r) => format!("{}.{}", r, kind),
2544             None => kind.to_string(),
2545         };
2546         self.testpaths.file.with_extension(extension)
2547     }
2548
2549     fn load_expected_output(&self, path: &Path) -> String {
2550         if !path.exists() {
2551             return String::new();
2552         }
2553
2554         let mut result = String::new();
2555         match File::open(path).and_then(|mut f| f.read_to_string(&mut result)) {
2556             Ok(_) => result,
2557             Err(e) => {
2558                 self.fatal(&format!("failed to load expected output from `{}`: {}",
2559                                     path.display(), e))
2560             }
2561         }
2562     }
2563
2564     fn compare_output(&self, kind: &str, actual: &str, expected: &str) -> usize {
2565         if actual == expected {
2566             return 0;
2567         }
2568
2569         println!("normalized {}:\n{}\n", kind, actual);
2570         println!("expected {}:\n{}\n", kind, expected);
2571         println!("diff of {}:\n", kind);
2572         for line in uidiff::diff_lines(actual, expected) {
2573             println!("{}", line);
2574         }
2575
2576         let output_file = self.output_base_name().with_extension(kind);
2577         match File::create(&output_file).and_then(|mut f| f.write_all(actual.as_bytes())) {
2578             Ok(()) => { }
2579             Err(e) => {
2580                 self.fatal(&format!("failed to write {} to `{}`: {}",
2581                                     kind, output_file.display(), e))
2582             }
2583         }
2584
2585         println!("\nThe actual {0} differed from the expected {0}.", kind);
2586         println!("Actual {} saved to {}", kind, output_file.display());
2587         1
2588     }
2589 }
2590
2591 struct ProcArgs {
2592     prog: String,
2593     args: Vec<String>,
2594 }
2595
2596 pub struct ProcRes {
2597     status: Status,
2598     stdout: String,
2599     stderr: String,
2600     cmdline: String,
2601 }
2602
2603 enum Status {
2604     Parsed(i32),
2605     Normal(ExitStatus),
2606 }
2607
2608 impl ProcRes {
2609     pub fn fatal(&self, err: Option<&str>) -> ! {
2610         if let Some(e) = err {
2611             println!("\nerror: {}", e);
2612         }
2613         print!("\
2614             status: {}\n\
2615             command: {}\n\
2616             stdout:\n\
2617             ------------------------------------------\n\
2618             {}\n\
2619             ------------------------------------------\n\
2620             stderr:\n\
2621             ------------------------------------------\n\
2622             {}\n\
2623             ------------------------------------------\n\
2624             \n",
2625                self.status, self.cmdline, self.stdout,
2626                self.stderr);
2627         panic!();
2628     }
2629 }
2630
2631 impl Status {
2632     fn code(&self) -> Option<i32> {
2633         match *self {
2634             Status::Parsed(i) => Some(i),
2635             Status::Normal(ref e) => e.code(),
2636         }
2637     }
2638
2639     fn success(&self) -> bool {
2640         match *self {
2641             Status::Parsed(i) => i == 0,
2642             Status::Normal(ref e) => e.success(),
2643         }
2644     }
2645 }
2646
2647 impl fmt::Display for Status {
2648     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2649         match *self {
2650             Status::Parsed(i) => write!(f, "exit code: {}", i),
2651             Status::Normal(ref e) => e.fmt(f),
2652         }
2653     }
2654 }
2655
2656 enum TargetLocation {
2657     ThisFile(PathBuf),
2658     ThisDirectory(PathBuf),
2659 }
2660
2661 fn normalize_mir_line(line: &str) -> String {
2662     nocomment_mir_line(line).replace(char::is_whitespace, "")
2663 }
2664
2665 fn nocomment_mir_line(line: &str) -> &str {
2666     if let Some(idx) = line.find("//") {
2667         let (l, _) = line.split_at(idx);
2668         l.trim_right()
2669     } else {
2670         line
2671     }
2672 }