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.
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.
11 use self::TargetLocation::*;
14 use common::{CompileFail, Pretty, RunFail, RunPass, RunPassValgrind, DebugInfoGdb};
15 use common::{Codegen, DebugInfoLldb};
17 use header::TestProps;
21 #[cfg(target_os = "windows")]
24 #[cfg(target_os = "windows")]
25 use std::ascii::AsciiExt;
27 use std::io::fs::PathExtensions;
29 use std::io::net::tcp;
30 use std::io::process::ProcessExit;
35 use std::iter::repeat;
37 use std::string::String;
38 use std::thread::Thread;
39 use std::time::Duration;
42 pub fn run(config: Config, testfile: String) {
43 match config.target.as_slice() {
45 "arm-linux-androideabi" => {
46 if !config.adb_device_status {
47 panic!("android device not available");
54 let mut _mm = MetricMap::new();
55 run_metrics(config, testfile, &mut _mm);
58 pub fn run_metrics(config: Config, testfile: String, mm: &mut MetricMap) {
60 // We're going to be dumping a lot of info. Start on a new line.
63 let testfile = Path::new(testfile);
64 debug!("running {:?}", testfile.display());
65 let props = header::load_props(&testfile);
66 debug!("loaded props");
68 CompileFail => run_cfail_test(&config, &props, &testfile),
69 RunFail => run_rfail_test(&config, &props, &testfile),
70 RunPass => run_rpass_test(&config, &props, &testfile),
71 RunPassValgrind => run_valgrind_test(&config, &props, &testfile),
72 Pretty => run_pretty_test(&config, &props, &testfile),
73 DebugInfoGdb => run_debuginfo_gdb_test(&config, &props, &testfile),
74 DebugInfoLldb => run_debuginfo_lldb_test(&config, &props, &testfile),
75 Codegen => run_codegen_test(&config, &props, &testfile, mm),
79 fn get_output(props: &TestProps, proc_res: &ProcRes) -> String {
80 if props.check_stdout {
81 format!("{}{}", proc_res.stdout, proc_res.stderr)
83 proc_res.stderr.clone()
87 fn run_cfail_test(config: &Config, props: &TestProps, testfile: &Path) {
88 let proc_res = compile_test(config, props, testfile);
90 if proc_res.status.success() {
91 fatal_proc_rec("compile-fail test compiled successfully!",
95 check_correct_failure_status(&proc_res);
97 if proc_res.status.success() {
98 fatal("process did not return an error status");
101 let output_to_check = get_output(props, &proc_res);
102 let expected_errors = errors::load_errors(&config.cfail_regex, testfile);
103 if !expected_errors.is_empty() {
104 if !props.error_patterns.is_empty() {
105 fatal("both error pattern and expected errors specified");
107 check_expected_errors(expected_errors, testfile, &proc_res);
109 check_error_patterns(props, testfile, output_to_check.as_slice(), &proc_res);
111 check_no_compiler_crash(&proc_res);
112 check_forbid_output(props, output_to_check.as_slice(), &proc_res);
115 fn run_rfail_test(config: &Config, props: &TestProps, testfile: &Path) {
116 let proc_res = if !config.jit {
117 let proc_res = compile_test(config, props, testfile);
119 if !proc_res.status.success() {
120 fatal_proc_rec("compilation failed!", &proc_res);
123 exec_compiled_test(config, props, testfile)
125 jit_test(config, props, testfile)
128 // The value our Makefile configures valgrind to return on failure
129 static VALGRIND_ERR: int = 100;
130 if proc_res.status.matches_exit_status(VALGRIND_ERR) {
131 fatal_proc_rec("run-fail test isn't valgrind-clean!", &proc_res);
134 let output_to_check = get_output(props, &proc_res);
135 check_correct_failure_status(&proc_res);
136 check_error_patterns(props, testfile, output_to_check.as_slice(), &proc_res);
139 fn check_correct_failure_status(proc_res: &ProcRes) {
140 // The value the rust runtime returns on failure
141 static RUST_ERR: int = 101;
142 if !proc_res.status.matches_exit_status(RUST_ERR) {
144 format!("failure produced the wrong error: {:?}",
145 proc_res.status).as_slice(),
150 fn run_rpass_test(config: &Config, props: &TestProps, testfile: &Path) {
152 let mut proc_res = compile_test(config, props, testfile);
154 if !proc_res.status.success() {
155 fatal_proc_rec("compilation failed!", &proc_res);
158 proc_res = exec_compiled_test(config, props, testfile);
160 if !proc_res.status.success() {
161 fatal_proc_rec("test run failed!", &proc_res);
164 let proc_res = jit_test(config, props, testfile);
166 if !proc_res.status.success() {
167 fatal_proc_rec("jit failed!", &proc_res);
172 fn run_valgrind_test(config: &Config, props: &TestProps, testfile: &Path) {
173 if config.valgrind_path.is_none() {
174 assert!(!config.force_valgrind);
175 return run_rpass_test(config, props, testfile);
178 let mut proc_res = compile_test(config, props, testfile);
180 if !proc_res.status.success() {
181 fatal_proc_rec("compilation failed!", &proc_res);
184 let mut new_config = config.clone();
185 new_config.runtool = new_config.valgrind_path.clone();
186 proc_res = exec_compiled_test(&new_config, props, testfile);
188 if !proc_res.status.success() {
189 fatal_proc_rec("test run failed!", &proc_res);
193 fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
194 if props.pp_exact.is_some() {
195 logv(config, "testing for exact pretty-printing".to_string());
197 logv(config, "testing for converging pretty-printing".to_string());
201 match props.pp_exact { Some(_) => 1, None => 2 };
203 let src = File::open(testfile).read_to_end().unwrap();
204 let src = String::from_utf8(src.clone()).unwrap();
205 let mut srcs = vec!(src);
208 while round < rounds {
209 logv(config, format!("pretty-printing round {}", round));
210 let proc_res = print_source(config,
213 srcs[round].to_string(),
214 props.pretty_mode.as_slice());
216 if !proc_res.status.success() {
217 fatal_proc_rec(format!("pretty-printing failed in round {}",
222 let ProcRes{ stdout, .. } = proc_res;
227 let mut expected = match props.pp_exact {
229 let filepath = testfile.dir_path().join(file);
230 let s = File::open(&filepath).read_to_end().unwrap();
231 String::from_utf8(s).unwrap()
233 None => { srcs[srcs.len() - 2u].clone() }
235 let mut actual = srcs[srcs.len() - 1u].clone();
237 if props.pp_exact.is_some() {
238 // Now we have to care about line endings
239 let cr = "\r".to_string();
240 actual = actual.replace(cr.as_slice(), "").to_string();
241 expected = expected.replace(cr.as_slice(), "").to_string();
244 compare_source(expected.as_slice(), actual.as_slice());
246 // If we're only making sure that the output matches then just stop here
247 if props.pretty_compare_only { return; }
249 // Finally, let's make sure it actually appears to remain valid code
250 let proc_res = typecheck_source(config, props, testfile, actual);
252 if !proc_res.status.success() {
253 fatal_proc_rec("pretty-printed source does not typecheck", &proc_res);
255 if props.no_pretty_expanded { return }
257 // additionally, run `--pretty expanded` and try to build it.
258 let proc_res = print_source(config, props, testfile, srcs[round].clone(), "expanded");
259 if !proc_res.status.success() {
260 fatal_proc_rec("pretty-printing (expanded) failed", &proc_res);
263 let ProcRes{ stdout: expanded_src, .. } = proc_res;
264 let proc_res = typecheck_source(config, props, testfile, expanded_src);
265 if !proc_res.status.success() {
266 fatal_proc_rec("pretty-printed source (expanded) does not typecheck",
272 fn print_source(config: &Config,
276 pretty_type: &str) -> ProcRes {
277 let aux_dir = aux_output_dir_name(config, testfile);
278 compose_and_run(config,
283 pretty_type.to_string()),
284 props.exec_env.clone(),
285 config.compile_lib_path.as_slice(),
286 Some(aux_dir.as_str().unwrap()),
290 fn make_pp_args(config: &Config,
293 pretty_type: String) -> ProcArgs {
294 let aux_dir = aux_output_dir_name(config, testfile);
295 // FIXME (#9639): This needs to handle non-utf8 paths
296 let mut args = vec!("-".to_string(),
297 "--pretty".to_string(),
299 format!("--target={}", config.target),
301 aux_dir.as_str().unwrap().to_string());
302 args.extend(split_maybe_args(&config.target_rustcflags).into_iter());
303 args.extend(split_maybe_args(&props.compile_flags).into_iter());
305 prog: config.rustc_path.as_str().unwrap().to_string(),
310 fn compare_source(expected: &str, actual: &str) {
311 if expected != actual {
312 error("pretty-printed source does not match expected source");
315 ------------------------------------------\n\
317 ------------------------------------------\n\
319 ------------------------------------------\n\
321 ------------------------------------------\n\
328 fn typecheck_source(config: &Config, props: &TestProps,
329 testfile: &Path, src: String) -> ProcRes {
330 let args = make_typecheck_args(config, props, testfile);
331 compose_and_run_compiler(config, props, testfile, args, Some(src))
334 fn make_typecheck_args(config: &Config, props: &TestProps, testfile: &Path) -> ProcArgs {
335 let aux_dir = aux_output_dir_name(config, testfile);
336 let target = if props.force_host {
337 config.host.as_slice()
339 config.target.as_slice()
341 // FIXME (#9639): This needs to handle non-utf8 paths
342 let mut args = vec!("-".to_string(),
343 "--no-trans".to_string(),
344 "--crate-type=lib".to_string(),
345 format!("--target={}", target),
347 config.build_base.as_str().unwrap().to_string(),
349 aux_dir.as_str().unwrap().to_string());
350 args.extend(split_maybe_args(&config.target_rustcflags).into_iter());
351 args.extend(split_maybe_args(&props.compile_flags).into_iter());
352 // FIXME (#9639): This needs to handle non-utf8 paths
354 prog: config.rustc_path.as_str().unwrap().to_string(),
360 fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
361 let mut config = Config {
362 target_rustcflags: cleanup_debug_info_options(&config.target_rustcflags),
363 host_rustcflags: cleanup_debug_info_options(&config.host_rustcflags),
367 let config = &mut config;
368 let DebuggerCommands {
372 } = parse_debugger_commands(testfile, "gdb");
373 let mut cmds = commands.connect("\n");
375 // compile test file (it should have 'compile-flags:-g' in the header)
376 let compiler_run_result = compile_test(config, props, testfile);
377 if !compiler_run_result.status.success() {
378 fatal_proc_rec("compilation failed!", &compiler_run_result);
381 let exe_file = make_exe_name(config, testfile);
383 let debugger_run_result;
384 match config.target.as_slice() {
385 "arm-linux-androideabi" => {
387 cmds = cmds.replace("run", "continue").to_string();
389 // write debugger script
390 let script_str = ["set charset UTF-8".to_string(),
391 format!("file {}", exe_file.as_str().unwrap()
393 "target remote :5039".to_string(),
395 "quit".to_string()].connect("\n");
396 debug!("script_str = {}", script_str);
397 dump_output_file(config,
399 script_str.as_slice(),
404 config.adb_path.as_slice(),
408 exe_file.as_str().unwrap().to_string(),
409 config.adb_test_dir.clone()
411 vec!(("".to_string(), "".to_string())),
412 Some("".to_string()))
413 .expect(format!("failed to exec `{:?}`", config.adb_path).as_slice());
416 config.adb_path.as_slice(),
419 "forward".to_string(),
420 "tcp:5039".to_string(),
421 "tcp:5039".to_string()
423 vec!(("".to_string(), "".to_string())),
424 Some("".to_string()))
425 .expect(format!("failed to exec `{:?}`", config.adb_path).as_slice());
427 let adb_arg = format!("export LD_LIBRARY_PATH={}; \
428 gdbserver :5039 {}/{}",
429 config.adb_test_dir.clone(),
430 config.adb_test_dir.clone(),
433 .unwrap()).unwrap());
435 let mut process = procsrv::run_background("",
443 vec!(("".to_string(),
445 Some("".to_string()))
446 .expect(format!("failed to exec `{:?}`", config.adb_path).as_slice());
448 //waiting 1 second for gdbserver start
449 timer::sleep(Duration::milliseconds(1000));
450 let result = Thread::scoped(move || {
451 tcp::TcpStream::connect("127.0.0.1:5039").unwrap();
459 let tool_path = match config.android_cross_path.as_str() {
460 Some(x) => x.to_string(),
461 None => fatal("cannot find android cross path")
464 let debugger_script = make_out_name(config, testfile, "debugger.script");
465 // FIXME (#9639): This needs to handle non-utf8 paths
467 vec!("-quiet".to_string(),
468 "-batch".to_string(),
470 format!("-command={}", debugger_script.as_str().unwrap()));
472 let mut gdb_path = tool_path;
473 gdb_path.push_str("/bin/arm-linux-androideabi-gdb");
474 let procsrv::Result {
481 debugger_opts.as_slice(),
482 vec!(("".to_string(), "".to_string())),
484 .expect(format!("failed to exec `{:?}`", gdb_path).as_slice());
486 let cmdline = make_cmdline("",
487 "arm-linux-androideabi-gdb",
488 debugger_opts.as_slice());
489 logv(config, format!("executing {}", cmdline));
493 debugger_run_result = ProcRes {
499 process.signal_kill().unwrap();
503 let rust_src_root = find_rust_src_root(config)
504 .expect("Could not find Rust source root");
505 let rust_pp_module_rel_path = Path::new("./src/etc");
506 let rust_pp_module_abs_path = rust_src_root.join(rust_pp_module_rel_path)
510 // write debugger script
511 let mut script_str = String::with_capacity(2048);
513 script_str.push_str("set charset UTF-8\n");
514 script_str.push_str("show version\n");
516 match config.gdb_version {
517 Some(ref version) => {
518 println!("NOTE: compiletest thinks it is using GDB version {}",
521 if header::gdb_version_to_int(version.as_slice()) >
522 header::gdb_version_to_int("7.4") {
523 // Add the directory containing the pretty printers to
524 // GDB's script auto loading safe path
526 format!("add-auto-load-safe-path {}\n",
527 rust_pp_module_abs_path.replace("\\", "\\\\").as_slice())
532 println!("NOTE: compiletest does not know which version of \
537 // The following line actually doesn't have to do anything with
538 // pretty printing, it just tells GDB to print values on one line:
539 script_str.push_str("set print pretty off\n");
541 // Add the pretty printer directory to GDB's source-file search path
542 script_str.push_str(&format!("directory {}\n", rust_pp_module_abs_path)[]);
544 // Load the target executable
545 script_str.push_str(&format!("file {}\n",
546 exe_file.as_str().unwrap().replace("\\", "\\\\"))[]);
548 // Add line breakpoints
549 for line in breakpoint_lines.iter() {
550 script_str.push_str(&format!("break '{:?}':{}\n",
551 testfile.filename_display(),
555 script_str.push_str(cmds.as_slice());
556 script_str.push_str("quit\n");
558 debug!("script_str = {}", script_str);
559 dump_output_file(config,
561 script_str.as_slice(),
564 // run debugger script with gdb
566 fn debugger() -> String {
567 "gdb.exe".to_string()
570 fn debugger() -> String {
574 let debugger_script = make_out_name(config, testfile, "debugger.script");
576 // FIXME (#9639): This needs to handle non-utf8 paths
578 vec!("-quiet".to_string(),
579 "-batch".to_string(),
581 format!("-command={}", debugger_script.as_str().unwrap()));
583 let proc_args = ProcArgs {
588 let environment = vec![("PYTHONPATH".to_string(), rust_pp_module_abs_path)];
590 debugger_run_result = compose_and_run(config,
594 config.run_lib_path.as_slice(),
600 if !debugger_run_result.status.success() {
601 fatal("gdb failed to execute");
604 check_debugger_output(&debugger_run_result, check_lines.as_slice());
607 fn find_rust_src_root(config: &Config) -> Option<Path> {
608 let mut path = config.src_base.clone();
609 let path_postfix = Path::new("src/etc/lldb_batchmode.py");
612 if path.join(&path_postfix).is_file() {
620 fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path) {
621 use std::io::process::{Command, ProcessOutput};
623 if config.lldb_python_dir.is_none() {
624 fatal("Can't run LLDB test because LLDB's python path is not set.");
627 let mut config = Config {
628 target_rustcflags: cleanup_debug_info_options(&config.target_rustcflags),
629 host_rustcflags: cleanup_debug_info_options(&config.host_rustcflags),
633 let config = &mut config;
635 // compile test file (it should have 'compile-flags:-g' in the header)
636 let compile_result = compile_test(config, props, testfile);
637 if !compile_result.status.success() {
638 fatal_proc_rec("compilation failed!", &compile_result);
641 let exe_file = make_exe_name(config, testfile);
643 match config.lldb_version {
644 Some(ref version) => {
645 println!("NOTE: compiletest thinks it is using LLDB version {}",
649 println!("NOTE: compiletest does not know which version of \
654 // Parse debugger commands etc from test files
655 let DebuggerCommands {
660 } = parse_debugger_commands(testfile, "lldb");
662 // Write debugger script:
663 // We don't want to hang when calling `quit` while the process is still running
664 let mut script_str = String::from_str("settings set auto-confirm true\n");
666 // Make LLDB emit its version, so we have it documented in the test output
667 script_str.push_str("version\n");
669 // Switch LLDB into "Rust mode"
670 let rust_src_root = find_rust_src_root(config)
671 .expect("Could not find Rust source root");
672 let rust_pp_module_rel_path = Path::new("./src/etc/lldb_rust_formatters.py");
673 let rust_pp_module_abs_path = rust_src_root.join(rust_pp_module_rel_path)
678 script_str.push_str(&format!("command script import {}\n", &rust_pp_module_abs_path[])[]);
679 script_str.push_str("type summary add --no-value ");
680 script_str.push_str("--python-function lldb_rust_formatters.print_val ");
681 script_str.push_str("-x \".*\" --category Rust\n");
682 script_str.push_str("type category enable Rust\n");
684 // Set breakpoints on every line that contains the string "#break"
685 for line in breakpoint_lines.iter() {
686 script_str.push_str(format!("breakpoint set --line {}\n",
690 // Append the other commands
691 for line in commands.iter() {
692 script_str.push_str(line.as_slice());
693 script_str.push_str("\n");
696 // Finally, quit the debugger
697 script_str.push_str("quit\n");
699 // Write the script into a file
700 debug!("script_str = {}", script_str);
701 dump_output_file(config,
703 script_str.as_slice(),
705 let debugger_script = make_out_name(config, testfile, "debugger.script");
707 // Let LLDB execute the script via lldb_batchmode.py
708 let debugger_run_result = run_lldb(config,
713 if !debugger_run_result.status.success() {
714 fatal_proc_rec("Error while running LLDB", &debugger_run_result);
717 check_debugger_output(&debugger_run_result, check_lines.as_slice());
719 fn run_lldb(config: &Config,
720 test_executable: &Path,
721 debugger_script: &Path,
722 rust_src_root: &Path)
724 // Prepare the lldb_batchmode which executes the debugger script
725 let lldb_script_path = rust_src_root.join(Path::new("./src/etc/lldb_batchmode.py"));
727 let mut cmd = Command::new("python");
728 cmd.arg(lldb_script_path)
729 .arg(test_executable)
730 .arg(debugger_script)
731 .env_set_all(&[("PYTHONPATH", config.lldb_python_dir.clone().unwrap().as_slice())]);
733 let (status, out, err) = match cmd.spawn() {
735 let ProcessOutput { status, output, error } =
736 process.wait_with_output().unwrap();
739 String::from_utf8(output).unwrap(),
740 String::from_utf8(error).unwrap())
743 fatal(format!("Failed to setup Python process for \
744 LLDB script: {}", e).as_slice())
748 dump_output(config, test_executable, out.as_slice(), err.as_slice());
753 cmdline: format!("{}", cmd)
758 struct DebuggerCommands {
759 commands: Vec<String>,
760 check_lines: Vec<String>,
761 breakpoint_lines: Vec<uint>,
764 fn parse_debugger_commands(file_path: &Path, debugger_prefix: &str)
765 -> DebuggerCommands {
766 use std::io::{BufferedReader, File};
768 let command_directive = format!("{}-command", debugger_prefix);
769 let check_directive = format!("{}-check", debugger_prefix);
771 let mut breakpoint_lines = vec!();
772 let mut commands = vec!();
773 let mut check_lines = vec!();
775 let mut reader = BufferedReader::new(File::open(file_path).unwrap());
776 for line in reader.lines() {
779 if line.as_slice().contains("#break") {
780 breakpoint_lines.push(counter);
783 header::parse_name_value_directive(
785 command_directive.as_slice()).map(|cmd| {
789 header::parse_name_value_directive(
791 check_directive.as_slice()).map(|cmd| {
792 check_lines.push(cmd)
796 fatal(format!("Error while parsing debugger commands: {}",
805 check_lines: check_lines,
806 breakpoint_lines: breakpoint_lines,
810 fn cleanup_debug_info_options(options: &Option<String>) -> Option<String> {
811 if options.is_none() {
815 // Remove options that are either unwanted (-O) or may lead to duplicates due to RUSTFLAGS.
816 let options_to_remove = [
819 "--debuginfo".to_string()
822 split_maybe_args(options).into_iter()
823 .filter(|x| !options_to_remove.contains(x))
824 .collect::<Vec<String>>()
829 fn check_debugger_output(debugger_run_result: &ProcRes, check_lines: &[String]) {
830 let num_check_lines = check_lines.len();
831 if num_check_lines > 0 {
832 // Allow check lines to leave parts unspecified (e.g., uninitialized
833 // bits in the wrong case of an enum) with the notation "[...]".
834 let check_fragments: Vec<Vec<String>> =
835 check_lines.iter().map(|s| {
839 .map(|x| x.to_string())
842 // check if each line in props.check_lines appears in the
845 for line in debugger_run_result.stdout.as_slice().lines() {
846 let mut rest = line.trim();
847 let mut first = true;
848 let mut failed = false;
849 for frag in check_fragments[i].iter() {
850 let found = if first {
851 if rest.starts_with(frag.as_slice()) {
857 rest.find_str(frag.as_slice())
865 rest = rest.slice_from(i + frag.len());
870 if !failed && rest.len() == 0 {
873 if i == num_check_lines {
878 if i != num_check_lines {
879 fatal_proc_rec(format!("line not found in debugger output: {}",
880 check_lines.get(i).unwrap()).as_slice(),
881 debugger_run_result);
886 fn check_error_patterns(props: &TestProps,
888 output_to_check: &str,
889 proc_res: &ProcRes) {
890 if props.error_patterns.is_empty() {
891 fatal(format!("no error pattern specified in {:?}",
892 testfile.display()).as_slice());
894 let mut next_err_idx = 0u;
895 let mut next_err_pat = &props.error_patterns[next_err_idx];
896 let mut done = false;
897 for line in output_to_check.as_slice().lines() {
898 if line.contains(next_err_pat.as_slice()) {
899 debug!("found error pattern {}", next_err_pat);
901 if next_err_idx == props.error_patterns.len() {
902 debug!("found all error patterns");
906 next_err_pat = &props.error_patterns[next_err_idx];
911 let missing_patterns = &props.error_patterns[next_err_idx..];
912 if missing_patterns.len() == 1u {
913 fatal_proc_rec(format!("error pattern '{}' not found!",
914 missing_patterns[0]).as_slice(),
917 for pattern in missing_patterns.iter() {
918 error(format!("error pattern '{}' not found!",
919 *pattern).as_slice());
921 fatal_proc_rec("multiple error patterns not found", proc_res);
925 fn check_no_compiler_crash(proc_res: &ProcRes) {
926 for line in proc_res.stderr.as_slice().lines() {
927 if line.starts_with("error: internal compiler error:") {
928 fatal_proc_rec("compiler encountered internal error",
934 fn check_forbid_output(props: &TestProps,
935 output_to_check: &str,
936 proc_res: &ProcRes) {
937 for pat in props.forbid_output.iter() {
938 if output_to_check.contains(pat.as_slice()) {
939 fatal_proc_rec("forbidden pattern found in compiler output", proc_res);
944 fn check_expected_errors(expected_errors: Vec<errors::ExpectedError> ,
946 proc_res: &ProcRes) {
948 // true if we found the error in question
949 let mut found_flags: Vec<_> = repeat(false).take(expected_errors.len()).collect();
951 if proc_res.status.success() {
952 fatal("process did not return an error status");
955 let prefixes = expected_errors.iter().map(|ee| {
956 format!("{:?}:{}:", testfile.display(), ee.line)
957 }).collect::<Vec<String> >();
960 fn prefix_matches( line : &str, prefix : &str ) -> bool {
961 line.to_ascii_lowercase().starts_with(prefix.to_ascii_lowercase().as_slice())
965 fn prefix_matches( line : &str, prefix : &str ) -> bool {
966 line.starts_with( prefix )
969 // A multi-line error will have followup lines which will always
970 // start with one of these strings.
971 fn continuation( line: &str) -> bool {
972 line.starts_with(" expected") ||
973 line.starts_with(" found") ||
975 // Should have 4 spaces: see issue 18946
976 line.starts_with("(")
979 // Scan and extract our error/warning messages,
981 // filename:line1:col1: line2:col2: *error:* msg
982 // filename:line1:col1: line2:col2: *warning:* msg
983 // where line1:col1: is the starting point, line2:col2:
984 // is the ending point, and * represents ANSI color codes.
985 for line in proc_res.stderr.as_slice().lines() {
986 let mut was_expected = false;
987 for (i, ee) in expected_errors.iter().enumerate() {
989 debug!("prefix={} ee.kind={} ee.msg={} line={}",
990 prefixes[i].as_slice(),
994 if (prefix_matches(line, prefixes[i].as_slice()) || continuation(line)) &&
995 line.contains(ee.kind.as_slice()) &&
996 line.contains(ee.msg.as_slice()) {
997 found_flags[i] = true;
1004 // ignore this msg which gets printed at the end
1005 if line.contains("aborting due to") {
1006 was_expected = true;
1009 if !was_expected && is_compiler_error_or_warning(line) {
1010 fatal_proc_rec(format!("unexpected compiler error or warning: '{}'",
1016 for (i, &flag) in found_flags.iter().enumerate() {
1018 let ee = &expected_errors[i];
1019 fatal_proc_rec(format!("expected {} on line {} not found: {}",
1020 ee.kind, ee.line, ee.msg).as_slice(),
1026 fn is_compiler_error_or_warning(line: &str) -> bool {
1029 scan_until_char(line, ':', &mut i) &&
1030 scan_char(line, ':', &mut i) &&
1031 scan_integer(line, &mut i) &&
1032 scan_char(line, ':', &mut i) &&
1033 scan_integer(line, &mut i) &&
1034 scan_char(line, ':', &mut i) &&
1035 scan_char(line, ' ', &mut i) &&
1036 scan_integer(line, &mut i) &&
1037 scan_char(line, ':', &mut i) &&
1038 scan_integer(line, &mut i) &&
1039 scan_char(line, ' ', &mut i) &&
1040 (scan_string(line, "error", &mut i) ||
1041 scan_string(line, "warning", &mut i));
1044 fn scan_until_char(haystack: &str, needle: char, idx: &mut uint) -> bool {
1045 if *idx >= haystack.len() {
1048 let opt = haystack.slice_from(*idx).find(needle);
1052 *idx = opt.unwrap();
1056 fn scan_char(haystack: &str, needle: char, idx: &mut uint) -> bool {
1057 if *idx >= haystack.len() {
1060 let range = haystack.char_range_at(*idx);
1061 if range.ch != needle {
1068 fn scan_integer(haystack: &str, idx: &mut uint) -> bool {
1070 while i < haystack.len() {
1071 let range = haystack.char_range_at(i);
1072 if range.ch < '0' || '9' < range.ch {
1084 fn scan_string(haystack: &str, needle: &str, idx: &mut uint) -> bool {
1085 let mut haystack_i = *idx;
1086 let mut needle_i = 0u;
1087 while needle_i < needle.len() {
1088 if haystack_i >= haystack.len() {
1091 let range = haystack.char_range_at(haystack_i);
1092 haystack_i = range.next;
1093 if !scan_char(needle, range.ch, &mut needle_i) {
1107 status: ProcessExit,
1113 fn compile_test(config: &Config, props: &TestProps,
1114 testfile: &Path) -> ProcRes {
1115 compile_test_(config, props, testfile, &[])
1118 fn jit_test(config: &Config, props: &TestProps, testfile: &Path) -> ProcRes {
1119 compile_test_(config, props, testfile, &["--jit".to_string()])
1122 fn compile_test_(config: &Config, props: &TestProps,
1123 testfile: &Path, extra_args: &[String]) -> ProcRes {
1124 let aux_dir = aux_output_dir_name(config, testfile);
1125 // FIXME (#9639): This needs to handle non-utf8 paths
1126 let mut link_args = vec!("-L".to_string(),
1127 aux_dir.as_str().unwrap().to_string());
1128 link_args.extend(extra_args.iter().map(|s| s.clone()));
1129 let args = make_compile_args(config,
1132 |a, b| TargetLocation::ThisFile(make_exe_name(a, b)), testfile);
1133 compose_and_run_compiler(config, props, testfile, args, None)
1136 fn exec_compiled_test(config: &Config, props: &TestProps,
1137 testfile: &Path) -> ProcRes {
1139 let env = props.exec_env.clone();
1141 match config.target.as_slice() {
1143 "arm-linux-androideabi" => {
1144 _arm_exec_compiled_test(config, props, testfile, env)
1148 let aux_dir = aux_output_dir_name(config, testfile);
1149 compose_and_run(config,
1151 make_run_args(config, props, testfile),
1153 config.run_lib_path.as_slice(),
1154 Some(aux_dir.as_str().unwrap()),
1160 fn compose_and_run_compiler(
1165 input: Option<String>) -> ProcRes {
1167 if !props.aux_builds.is_empty() {
1168 ensure_dir(&aux_output_dir_name(config, testfile));
1171 let aux_dir = aux_output_dir_name(config, testfile);
1172 // FIXME (#9639): This needs to handle non-utf8 paths
1173 let extra_link_args = vec!("-L".to_string(), aux_dir.as_str().unwrap().to_string());
1175 for rel_ab in props.aux_builds.iter() {
1176 let abs_ab = config.aux_base.join(rel_ab.as_slice());
1177 let aux_props = header::load_props(&abs_ab);
1178 let mut crate_type = if aux_props.no_prefer_dynamic {
1181 vec!("--crate-type=dylib".to_string())
1183 crate_type.extend(extra_link_args.clone().into_iter());
1185 make_compile_args(config,
1189 let f = make_lib_name(a, b, testfile);
1190 TargetLocation::ThisDirectory(f.dir_path())
1193 let auxres = compose_and_run(config,
1197 config.compile_lib_path.as_slice(),
1198 Some(aux_dir.as_str().unwrap()),
1200 if !auxres.status.success() {
1202 format!("auxiliary build of {:?} failed to compile: ",
1203 abs_ab.display()).as_slice(),
1207 match config.target.as_slice() {
1208 "arm-linux-androideabi" => {
1209 _arm_push_aux_shared_library(config, testfile);
1215 compose_and_run(config,
1219 config.compile_lib_path.as_slice(),
1220 Some(aux_dir.as_str().unwrap()),
1224 fn ensure_dir(path: &Path) {
1225 if path.is_dir() { return; }
1226 fs::mkdir(path, io::USER_RWX).unwrap();
1229 fn compose_and_run(config: &Config, testfile: &Path,
1230 ProcArgs{ args, prog }: ProcArgs,
1231 procenv: Vec<(String, String)> ,
1233 aux_path: Option<&str>,
1234 input: Option<String>) -> ProcRes {
1235 return program_output(config, testfile, lib_path,
1236 prog, aux_path, args, procenv, input);
1239 enum TargetLocation {
1241 ThisDirectory(Path),
1244 fn make_compile_args<F>(config: &Config,
1246 extras: Vec<String> ,
1250 F: FnOnce(&Config, &Path) -> TargetLocation,
1252 let xform_file = xform(config, testfile);
1253 let target = if props.force_host {
1254 config.host.as_slice()
1256 config.target.as_slice()
1258 // FIXME (#9639): This needs to handle non-utf8 paths
1259 let mut args = vec!(testfile.as_str().unwrap().to_string(),
1261 config.build_base.as_str().unwrap().to_string(),
1262 format!("--target={}", target));
1263 args.push_all(extras.as_slice());
1264 if !props.no_prefer_dynamic {
1265 args.push("-C".to_string());
1266 args.push("prefer-dynamic".to_string());
1268 let path = match xform_file {
1269 TargetLocation::ThisFile(path) => {
1270 args.push("-o".to_string());
1273 TargetLocation::ThisDirectory(path) => {
1274 args.push("--out-dir".to_string());
1278 args.push(path.as_str().unwrap().to_string());
1279 if props.force_host {
1280 args.extend(split_maybe_args(&config.host_rustcflags).into_iter());
1282 args.extend(split_maybe_args(&config.target_rustcflags).into_iter());
1284 args.extend(split_maybe_args(&props.compile_flags).into_iter());
1286 prog: config.rustc_path.as_str().unwrap().to_string(),
1291 fn make_lib_name(config: &Config, auxfile: &Path, testfile: &Path) -> Path {
1292 // what we return here is not particularly important, as it
1293 // happens; rustc ignores everything except for the directory.
1294 let auxname = output_testname(auxfile);
1295 aux_output_dir_name(config, testfile).join(&auxname)
1298 fn make_exe_name(config: &Config, testfile: &Path) -> Path {
1299 let mut f = output_base_name(config, testfile);
1300 if !os::consts::EXE_SUFFIX.is_empty() {
1301 let mut fname = f.filename().unwrap().to_vec();
1302 fname.extend(os::consts::EXE_SUFFIX.bytes());
1303 f.set_filename(fname);
1308 fn make_run_args(config: &Config, props: &TestProps, testfile: &Path) ->
1310 // If we've got another tool to run under (valgrind),
1311 // then split apart its command
1312 let mut args = split_maybe_args(&config.runtool);
1313 let exe_file = make_exe_name(config, testfile);
1315 // FIXME (#9639): This needs to handle non-utf8 paths
1316 args.push(exe_file.as_str().unwrap().to_string());
1318 // Add the arguments in the run_flags directive
1319 args.extend(split_maybe_args(&props.run_flags).into_iter());
1321 let prog = args.remove(0);
1328 fn split_maybe_args(argstr: &Option<String>) -> Vec<String> {
1334 if s.chars().all(|c| c.is_whitespace()) {
1345 fn program_output(config: &Config, testfile: &Path, lib_path: &str, prog: String,
1346 aux_path: Option<&str>, args: Vec<String>,
1347 env: Vec<(String, String)>,
1348 input: Option<String>) -> ProcRes {
1351 let cmdline = make_cmdline(lib_path,
1354 logv(config, format!("executing {}", cmdline));
1357 let procsrv::Result {
1361 } = procsrv::run(lib_path,
1366 input).expect(format!("failed to exec `{}`", prog).as_slice());
1367 dump_output(config, testfile, out.as_slice(), err.as_slice());
1376 // Linux and mac don't require adjusting the library search path
1378 fn make_cmdline(_libpath: &str, prog: &str, args: &[String]) -> String {
1379 format!("{} {}", prog, args.connect(" "))
1383 fn make_cmdline(libpath: &str, prog: &str, args: &[String]) -> String {
1385 // Build the LD_LIBRARY_PATH variable as it would be seen on the command line
1386 // for diagnostic purposes
1387 fn lib_path_cmd_prefix(path: &str) -> String {
1388 format!("{}=\"{}\"", util::lib_path_env_var(), util::make_new_path(path))
1391 format!("{} {} {}", lib_path_cmd_prefix(libpath), prog, args.connect(" "))
1394 fn dump_output(config: &Config, testfile: &Path, out: &str, err: &str) {
1395 dump_output_file(config, testfile, out, "out");
1396 dump_output_file(config, testfile, err, "err");
1397 maybe_dump_to_stdout(config, out, err);
1400 fn dump_output_file(config: &Config, testfile: &Path,
1401 out: &str, extension: &str) {
1402 let outfile = make_out_name(config, testfile, extension);
1403 File::create(&outfile).write(out.as_bytes()).unwrap();
1406 fn make_out_name(config: &Config, testfile: &Path, extension: &str) -> Path {
1407 output_base_name(config, testfile).with_extension(extension)
1410 fn aux_output_dir_name(config: &Config, testfile: &Path) -> Path {
1411 let f = output_base_name(config, testfile);
1412 let mut fname = f.filename().unwrap().to_vec();
1413 fname.extend("libaux".bytes());
1414 f.with_filename(fname)
1417 fn output_testname(testfile: &Path) -> Path {
1418 Path::new(testfile.filestem().unwrap())
1421 fn output_base_name(config: &Config, testfile: &Path) -> Path {
1423 .join(&output_testname(testfile))
1424 .with_extension(config.stage_id.as_slice())
1427 fn maybe_dump_to_stdout(config: &Config, out: &str, err: &str) {
1429 println!("------{}------------------------------", "stdout");
1430 println!("{}", out);
1431 println!("------{}------------------------------", "stderr");
1432 println!("{}", err);
1433 println!("------------------------------------------");
1437 fn error(err: &str) { println!("\nerror: {}", err); }
1439 fn fatal(err: &str) -> ! { error(err); panic!(); }
1441 fn fatal_proc_rec(err: &str, proc_res: &ProcRes) -> ! {
1447 ------------------------------------------\n\
1449 ------------------------------------------\n\
1451 ------------------------------------------\n\
1453 ------------------------------------------\n\
1455 err, proc_res.status, proc_res.cmdline, proc_res.stdout,
1460 fn _arm_exec_compiled_test(config: &Config,
1463 env: Vec<(String, String)>)
1465 let args = make_run_args(config, props, testfile);
1466 let cmdline = make_cmdline("",
1467 args.prog.as_slice(),
1468 args.args.as_slice());
1470 // get bare program string
1471 let mut tvec: Vec<String> = args.prog
1474 .map(|ts| ts.to_string())
1476 let prog_short = tvec.pop().unwrap();
1479 let copy_result = procsrv::run("",
1480 config.adb_path.as_slice(),
1485 config.adb_test_dir.clone()
1487 vec!(("".to_string(), "".to_string())),
1488 Some("".to_string()))
1489 .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
1492 println!("push ({}) {} {} {}",
1499 logv(config, format!("executing ({}) {}", config.target, cmdline));
1501 let mut runargs = Vec::new();
1503 // run test via adb_run_wrapper
1504 runargs.push("shell".to_string());
1505 for (key, val) in env.into_iter() {
1506 runargs.push(format!("{}={}", key, val));
1508 runargs.push(format!("{}/adb_run_wrapper.sh", config.adb_test_dir));
1509 runargs.push(format!("{}", config.adb_test_dir));
1510 runargs.push(format!("{}", prog_short));
1512 for tv in args.args.iter() {
1513 runargs.push(tv.to_string());
1516 config.adb_path.as_slice(),
1519 vec!(("".to_string(), "".to_string())), Some("".to_string()))
1520 .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
1522 // get exitcode of result
1523 runargs = Vec::new();
1524 runargs.push("shell".to_string());
1525 runargs.push("cat".to_string());
1526 runargs.push(format!("{}/{}.exitcode", config.adb_test_dir, prog_short));
1528 let procsrv::Result{ out: exitcode_out, err: _, status: _ } =
1530 config.adb_path.as_slice(),
1533 vec!(("".to_string(), "".to_string())),
1534 Some("".to_string()))
1535 .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
1537 let mut exitcode: int = 0;
1538 for c in exitcode_out.as_slice().chars() {
1539 if !c.is_numeric() { break; }
1540 exitcode = exitcode * 10 + match c {
1541 '0' ... '9' => c as int - ('0' as int),
1546 // get stdout of result
1547 runargs = Vec::new();
1548 runargs.push("shell".to_string());
1549 runargs.push("cat".to_string());
1550 runargs.push(format!("{}/{}.stdout", config.adb_test_dir, prog_short));
1552 let procsrv::Result{ out: stdout_out, err: _, status: _ } =
1554 config.adb_path.as_slice(),
1557 vec!(("".to_string(), "".to_string())),
1558 Some("".to_string()))
1559 .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
1561 // get stderr of result
1562 runargs = Vec::new();
1563 runargs.push("shell".to_string());
1564 runargs.push("cat".to_string());
1565 runargs.push(format!("{}/{}.stderr", config.adb_test_dir, prog_short));
1567 let procsrv::Result{ out: stderr_out, err: _, status: _ } =
1569 config.adb_path.as_slice(),
1572 vec!(("".to_string(), "".to_string())),
1573 Some("".to_string()))
1574 .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
1578 stdout_out.as_slice(),
1579 stderr_out.as_slice());
1582 status: process::ProcessExit::ExitStatus(exitcode),
1589 fn _arm_push_aux_shared_library(config: &Config, testfile: &Path) {
1590 let tdir = aux_output_dir_name(config, testfile);
1592 let dirs = fs::readdir(&tdir).unwrap();
1593 for file in dirs.iter() {
1594 if file.extension_str() == Some("so") {
1595 // FIXME (#9639): This needs to handle non-utf8 paths
1596 let copy_result = procsrv::run("",
1597 config.adb_path.as_slice(),
1604 config.adb_test_dir.to_string()
1606 vec!(("".to_string(),
1608 Some("".to_string()))
1609 .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
1612 println!("push ({}) {:?} {} {}",
1613 config.target, file.display(),
1614 copy_result.out, copy_result.err);
1620 // codegen tests (vs. clang)
1622 fn append_suffix_to_stem(p: &Path, suffix: &str) -> Path {
1623 if suffix.len() == 0 {
1626 let mut stem = p.filestem().unwrap().to_vec();
1627 stem.extend("-".bytes());
1628 stem.extend(suffix.bytes());
1629 p.with_filename(stem)
1633 fn compile_test_and_save_bitcode(config: &Config, props: &TestProps,
1634 testfile: &Path) -> ProcRes {
1635 let aux_dir = aux_output_dir_name(config, testfile);
1636 // FIXME (#9639): This needs to handle non-utf8 paths
1637 let mut link_args = vec!("-L".to_string(),
1638 aux_dir.as_str().unwrap().to_string());
1639 let llvm_args = vec!("--emit=llvm-bc,obj".to_string(),
1640 "--crate-type=lib".to_string());
1641 link_args.extend(llvm_args.into_iter());
1642 let args = make_compile_args(config,
1645 |a, b| TargetLocation::ThisDirectory(
1646 output_base_name(a, b).dir_path()),
1648 compose_and_run_compiler(config, props, testfile, args, None)
1651 fn compile_cc_with_clang_and_save_bitcode(config: &Config, _props: &TestProps,
1652 testfile: &Path) -> ProcRes {
1653 let bitcodefile = output_base_name(config, testfile).with_extension("bc");
1654 let bitcodefile = append_suffix_to_stem(&bitcodefile, "clang");
1655 let testcc = testfile.with_extension("cc");
1656 let proc_args = ProcArgs {
1657 // FIXME (#9639): This needs to handle non-utf8 paths
1658 prog: config.clang_path.as_ref().unwrap().as_str().unwrap().to_string(),
1659 args: vec!("-c".to_string(),
1660 "-emit-llvm".to_string(),
1662 bitcodefile.as_str().unwrap().to_string(),
1663 testcc.as_str().unwrap().to_string())
1665 compose_and_run(config, testfile, proc_args, Vec::new(), "", None, None)
1668 fn extract_function_from_bitcode(config: &Config, _props: &TestProps,
1669 fname: &str, testfile: &Path,
1670 suffix: &str) -> ProcRes {
1671 let bitcodefile = output_base_name(config, testfile).with_extension("bc");
1672 let bitcodefile = append_suffix_to_stem(&bitcodefile, suffix);
1673 let extracted_bc = append_suffix_to_stem(&bitcodefile, "extract");
1674 let prog = config.llvm_bin_path.as_ref().unwrap().join("llvm-extract");
1675 let proc_args = ProcArgs {
1676 // FIXME (#9639): This needs to handle non-utf8 paths
1677 prog: prog.as_str().unwrap().to_string(),
1678 args: vec!(format!("-func={}", fname),
1679 format!("-o={}", extracted_bc.as_str().unwrap()),
1680 bitcodefile.as_str().unwrap().to_string())
1682 compose_and_run(config, testfile, proc_args, Vec::new(), "", None, None)
1685 fn disassemble_extract(config: &Config, _props: &TestProps,
1686 testfile: &Path, suffix: &str) -> ProcRes {
1687 let bitcodefile = output_base_name(config, testfile).with_extension("bc");
1688 let bitcodefile = append_suffix_to_stem(&bitcodefile, suffix);
1689 let extracted_bc = append_suffix_to_stem(&bitcodefile, "extract");
1690 let extracted_ll = extracted_bc.with_extension("ll");
1691 let prog = config.llvm_bin_path.as_ref().unwrap().join("llvm-dis");
1692 let proc_args = ProcArgs {
1693 // FIXME (#9639): This needs to handle non-utf8 paths
1694 prog: prog.as_str().unwrap().to_string(),
1695 args: vec!(format!("-o={}", extracted_ll.as_str().unwrap()),
1696 extracted_bc.as_str().unwrap().to_string())
1698 compose_and_run(config, testfile, proc_args, Vec::new(), "", None, None)
1702 fn count_extracted_lines(p: &Path) -> uint {
1703 let x = File::open(&p.with_extension("ll")).read_to_end().unwrap();
1704 let x = str::from_utf8(x.as_slice()).unwrap();
1709 fn run_codegen_test(config: &Config, props: &TestProps,
1710 testfile: &Path, mm: &mut MetricMap) {
1712 if config.llvm_bin_path.is_none() {
1713 fatal("missing --llvm-bin-path");
1716 if config.clang_path.is_none() {
1717 fatal("missing --clang-path");
1720 let mut proc_res = compile_test_and_save_bitcode(config, props, testfile);
1721 if !proc_res.status.success() {
1722 fatal_proc_rec("compilation failed!", &proc_res);
1725 proc_res = extract_function_from_bitcode(config, props, "test", testfile, "");
1726 if !proc_res.status.success() {
1727 fatal_proc_rec("extracting 'test' function failed",
1731 proc_res = disassemble_extract(config, props, testfile, "");
1732 if !proc_res.status.success() {
1733 fatal_proc_rec("disassembling extract failed", &proc_res);
1737 let mut proc_res = compile_cc_with_clang_and_save_bitcode(config, props, testfile);
1738 if !proc_res.status.success() {
1739 fatal_proc_rec("compilation failed!", &proc_res);
1742 proc_res = extract_function_from_bitcode(config, props, "test", testfile, "clang");
1743 if !proc_res.status.success() {
1744 fatal_proc_rec("extracting 'test' function failed",
1748 proc_res = disassemble_extract(config, props, testfile, "clang");
1749 if !proc_res.status.success() {
1750 fatal_proc_rec("disassembling extract failed", &proc_res);
1753 let base = output_base_name(config, testfile);
1754 let base_extract = append_suffix_to_stem(&base, "extract");
1756 let base_clang = append_suffix_to_stem(&base, "clang");
1757 let base_clang_extract = append_suffix_to_stem(&base_clang, "extract");
1759 let base_lines = count_extracted_lines(&base_extract);
1760 let clang_lines = count_extracted_lines(&base_clang_extract);
1762 mm.insert_metric("clang-codegen-ratio",
1763 (base_lines as f64) / (clang_lines as f64),