]> git.lizzy.rs Git - rust.git/blob - src/compiletest/runtest.rs
f8e2ba4828f383773acd17983a7db49636afd2e7
[rust.git] / src / compiletest / 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 self::TargetLocation::*;
12
13 use common::Config;
14 use common::{CompileFail, Pretty, RunFail, RunPass, RunPassValgrind, DebugInfoGdb};
15 use common::{Codegen, DebugInfoLldb};
16 use errors;
17 use header::TestProps;
18 use header;
19 use procsrv;
20 use util::logv;
21 #[cfg(target_os = "windows")]
22 use util;
23
24 #[cfg(target_os = "windows")]
25 use std::ascii::AsciiExt;
26 use std::io::File;
27 use std::io::fs::PathExtensions;
28 use std::io::fs;
29 use std::io::net::tcp;
30 use std::io::process::ProcessExit;
31 use std::io::process;
32 use std::io::timer;
33 use std::io;
34 use std::os;
35 use std::iter::repeat;
36 use std::str;
37 use std::string::String;
38 use std::thread::Thread;
39 use std::time::Duration;
40 use test::MetricMap;
41
42 pub fn run(config: Config, testfile: String) {
43     match config.target.as_slice() {
44
45         "arm-linux-androideabi" => {
46             if !config.adb_device_status {
47                 panic!("android device not available");
48             }
49         }
50
51         _=> { }
52     }
53
54     let mut _mm = MetricMap::new();
55     run_metrics(config, testfile, &mut _mm);
56 }
57
58 pub fn run_metrics(config: Config, testfile: String, mm: &mut MetricMap) {
59     if config.verbose {
60         // We're going to be dumping a lot of info. Start on a new line.
61         print!("\n\n");
62     }
63     let testfile = Path::new(testfile);
64     debug!("running {:?}", testfile.display());
65     let props = header::load_props(&testfile);
66     debug!("loaded props");
67     match config.mode {
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),
76     }
77 }
78
79 fn get_output(props: &TestProps, proc_res: &ProcRes) -> String {
80     if props.check_stdout {
81         format!("{}{}", proc_res.stdout, proc_res.stderr)
82     } else {
83         proc_res.stderr.clone()
84     }
85 }
86
87 fn run_cfail_test(config: &Config, props: &TestProps, testfile: &Path) {
88     let proc_res = compile_test(config, props, testfile);
89
90     if proc_res.status.success() {
91         fatal_proc_rec("compile-fail test compiled successfully!",
92                       &proc_res);
93     }
94
95     check_correct_failure_status(&proc_res);
96
97     if proc_res.status.success() {
98         fatal("process did not return an error status");
99     }
100
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");
106         }
107         check_expected_errors(expected_errors, testfile, &proc_res);
108     } else {
109         check_error_patterns(props, testfile, output_to_check.as_slice(), &proc_res);
110     }
111     check_no_compiler_crash(&proc_res);
112     check_forbid_output(props, output_to_check.as_slice(), &proc_res);
113 }
114
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);
118
119         if !proc_res.status.success() {
120             fatal_proc_rec("compilation failed!", &proc_res);
121         }
122
123         exec_compiled_test(config, props, testfile)
124     } else {
125         jit_test(config, props, testfile)
126     };
127
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);
132     }
133
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);
137 }
138
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) {
143         fatal_proc_rec(
144             format!("failure produced the wrong error: {:?}",
145                     proc_res.status).as_slice(),
146             proc_res);
147     }
148 }
149
150 fn run_rpass_test(config: &Config, props: &TestProps, testfile: &Path) {
151     if !config.jit {
152         let mut proc_res = compile_test(config, props, testfile);
153
154         if !proc_res.status.success() {
155             fatal_proc_rec("compilation failed!", &proc_res);
156         }
157
158         proc_res = exec_compiled_test(config, props, testfile);
159
160         if !proc_res.status.success() {
161             fatal_proc_rec("test run failed!", &proc_res);
162         }
163     } else {
164         let proc_res = jit_test(config, props, testfile);
165
166         if !proc_res.status.success() {
167             fatal_proc_rec("jit failed!", &proc_res);
168         }
169     }
170 }
171
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);
176     }
177
178     let mut proc_res = compile_test(config, props, testfile);
179
180     if !proc_res.status.success() {
181         fatal_proc_rec("compilation failed!", &proc_res);
182     }
183
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);
187
188     if !proc_res.status.success() {
189         fatal_proc_rec("test run failed!", &proc_res);
190     }
191 }
192
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());
196     } else {
197         logv(config, "testing for converging pretty-printing".to_string());
198     }
199
200     let rounds =
201         match props.pp_exact { Some(_) => 1, None => 2 };
202
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);
206
207     let mut round = 0;
208     while round < rounds {
209         logv(config, format!("pretty-printing round {}", round));
210         let proc_res = print_source(config,
211                                     props,
212                                     testfile,
213                                     srcs[round].to_string(),
214                                     props.pretty_mode.as_slice());
215
216         if !proc_res.status.success() {
217             fatal_proc_rec(format!("pretty-printing failed in round {}",
218                                    round).as_slice(),
219                           &proc_res);
220         }
221
222         let ProcRes{ stdout, .. } = proc_res;
223         srcs.push(stdout);
224         round += 1;
225     }
226
227     let mut expected = match props.pp_exact {
228         Some(ref file) => {
229             let filepath = testfile.dir_path().join(file);
230             let s = File::open(&filepath).read_to_end().unwrap();
231             String::from_utf8(s).unwrap()
232         }
233         None => { srcs[srcs.len() - 2u].clone() }
234     };
235     let mut actual = srcs[srcs.len() - 1u].clone();
236
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();
242     }
243
244     compare_source(expected.as_slice(), actual.as_slice());
245
246     // If we're only making sure that the output matches then just stop here
247     if props.pretty_compare_only { return; }
248
249     // Finally, let's make sure it actually appears to remain valid code
250     let proc_res = typecheck_source(config, props, testfile, actual);
251
252     if !proc_res.status.success() {
253         fatal_proc_rec("pretty-printed source does not typecheck", &proc_res);
254     }
255     if props.no_pretty_expanded { return }
256
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);
261     }
262
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",
267                       &proc_res);
268     }
269
270     return;
271
272     fn print_source(config: &Config,
273                     props: &TestProps,
274                     testfile: &Path,
275                     src: String,
276                     pretty_type: &str) -> ProcRes {
277         let aux_dir = aux_output_dir_name(config, testfile);
278         compose_and_run(config,
279                         testfile,
280                         make_pp_args(config,
281                                      props,
282                                      testfile,
283                                      pretty_type.to_string()),
284                         props.exec_env.clone(),
285                         config.compile_lib_path.as_slice(),
286                         Some(aux_dir.as_str().unwrap()),
287                         Some(src))
288     }
289
290     fn make_pp_args(config: &Config,
291                     props: &TestProps,
292                     testfile: &Path,
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(),
298                             pretty_type,
299                             format!("--target={}", config.target),
300                             "-L".to_string(),
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());
304         return ProcArgs {
305             prog: config.rustc_path.as_str().unwrap().to_string(),
306             args: args,
307         };
308     }
309
310     fn compare_source(expected: &str, actual: &str) {
311         if expected != actual {
312             error("pretty-printed source does not match expected source");
313             println!("\n\
314 expected:\n\
315 ------------------------------------------\n\
316 {}\n\
317 ------------------------------------------\n\
318 actual:\n\
319 ------------------------------------------\n\
320 {}\n\
321 ------------------------------------------\n\
322 \n",
323                      expected, actual);
324             panic!();
325         }
326     }
327
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))
332     }
333
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()
338         } else {
339             config.target.as_slice()
340         };
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),
346                             "-L".to_string(),
347                             config.build_base.as_str().unwrap().to_string(),
348                             "-L".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
353         return ProcArgs {
354             prog: config.rustc_path.as_str().unwrap().to_string(),
355             args: args,
356         };
357     }
358 }
359
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),
364         .. config.clone()
365     };
366
367     let config = &mut config;
368     let DebuggerCommands {
369         commands,
370         check_lines,
371         breakpoint_lines
372     } = parse_debugger_commands(testfile, "gdb");
373     let mut cmds = commands.connect("\n");
374
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);
379     }
380
381     let exe_file = make_exe_name(config, testfile);
382
383     let debugger_run_result;
384     match config.target.as_slice() {
385         "arm-linux-androideabi" => {
386
387             cmds = cmds.replace("run", "continue").to_string();
388
389             // write debugger script
390             let script_str = ["set charset UTF-8".to_string(),
391                               format!("file {}", exe_file.as_str().unwrap()
392                                                          .to_string()),
393                               "target remote :5039".to_string(),
394                               cmds,
395                               "quit".to_string()].connect("\n");
396             debug!("script_str = {}", script_str);
397             dump_output_file(config,
398                              testfile,
399                              script_str.as_slice(),
400                              "debugger.script");
401
402
403             procsrv::run("",
404                          config.adb_path.as_slice(),
405                          None,
406                          &[
407                             "push".to_string(),
408                             exe_file.as_str().unwrap().to_string(),
409                             config.adb_test_dir.clone()
410                          ],
411                          vec!(("".to_string(), "".to_string())),
412                          Some("".to_string()))
413                 .expect(format!("failed to exec `{:?}`", config.adb_path).as_slice());
414
415             procsrv::run("",
416                          config.adb_path.as_slice(),
417                          None,
418                          &[
419                             "forward".to_string(),
420                             "tcp:5039".to_string(),
421                             "tcp:5039".to_string()
422                          ],
423                          vec!(("".to_string(), "".to_string())),
424                          Some("".to_string()))
425                 .expect(format!("failed to exec `{:?}`", config.adb_path).as_slice());
426
427             let adb_arg = format!("export LD_LIBRARY_PATH={}; \
428                                    gdbserver :5039 {}/{}",
429                                   config.adb_test_dir.clone(),
430                                   config.adb_test_dir.clone(),
431                                   str::from_utf8(
432                                       exe_file.filename()
433                                       .unwrap()).unwrap());
434
435             let mut process = procsrv::run_background("",
436                                                       config.adb_path
437                                                             .as_slice(),
438                                                       None,
439                                                       &[
440                                                         "shell".to_string(),
441                                                         adb_arg.clone()
442                                                       ],
443                                                       vec!(("".to_string(),
444                                                             "".to_string())),
445                                                       Some("".to_string()))
446                 .expect(format!("failed to exec `{:?}`", config.adb_path).as_slice());
447             loop {
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();
452                 }).join();
453                 if result.is_err() {
454                     continue;
455                 }
456                 break;
457             }
458
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")
462             };
463
464             let debugger_script = make_out_name(config, testfile, "debugger.script");
465             // FIXME (#9639): This needs to handle non-utf8 paths
466             let debugger_opts =
467                 vec!("-quiet".to_string(),
468                      "-batch".to_string(),
469                      "-nx".to_string(),
470                      format!("-command={}", debugger_script.as_str().unwrap()));
471
472             let mut gdb_path = tool_path;
473             gdb_path.push_str("/bin/arm-linux-androideabi-gdb");
474             let procsrv::Result {
475                 out,
476                 err,
477                 status
478             } = procsrv::run("",
479                              gdb_path.as_slice(),
480                              None,
481                              debugger_opts.as_slice(),
482                              vec!(("".to_string(), "".to_string())),
483                              None)
484                 .expect(format!("failed to exec `{:?}`", gdb_path).as_slice());
485             let cmdline = {
486                 let cmdline = make_cmdline("",
487                                            "arm-linux-androideabi-gdb",
488                                            debugger_opts.as_slice());
489                 logv(config, format!("executing {}", cmdline));
490                 cmdline
491             };
492
493             debugger_run_result = ProcRes {
494                 status: status,
495                 stdout: out,
496                 stderr: err,
497                 cmdline: cmdline
498             };
499             process.signal_kill().unwrap();
500         }
501
502         _=> {
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)
507                                                        .as_str()
508                                                        .unwrap()
509                                                        .to_string();
510             // write debugger script
511             let mut script_str = String::with_capacity(2048);
512
513             script_str.push_str("set charset UTF-8\n");
514             script_str.push_str("show version\n");
515
516             match config.gdb_version {
517                 Some(ref version) => {
518                     println!("NOTE: compiletest thinks it is using GDB version {}",
519                              version.as_slice());
520
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
525                         script_str.push_str(
526                             format!("add-auto-load-safe-path {}\n",
527                                     rust_pp_module_abs_path.replace("\\", "\\\\").as_slice())
528                                 .as_slice());
529                     }
530                 }
531                 _ => {
532                     println!("NOTE: compiletest does not know which version of \
533                               GDB it is using");
534                 }
535             }
536
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");
540
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)[]);
543
544             // Load the target executable
545             script_str.push_str(&format!("file {}\n",
546                                          exe_file.as_str().unwrap().replace("\\", "\\\\"))[]);
547
548             // Add line breakpoints
549             for line in breakpoint_lines.iter() {
550                 script_str.push_str(&format!("break '{:?}':{}\n",
551                                              testfile.filename_display(),
552                                              *line)[]);
553             }
554
555             script_str.push_str(cmds.as_slice());
556             script_str.push_str("quit\n");
557
558             debug!("script_str = {}", script_str);
559             dump_output_file(config,
560                              testfile,
561                              script_str.as_slice(),
562                              "debugger.script");
563
564             // run debugger script with gdb
565             #[cfg(windows)]
566             fn debugger() -> String {
567                 "gdb.exe".to_string()
568             }
569             #[cfg(unix)]
570             fn debugger() -> String {
571                 "gdb".to_string()
572             }
573
574             let debugger_script = make_out_name(config, testfile, "debugger.script");
575
576             // FIXME (#9639): This needs to handle non-utf8 paths
577             let debugger_opts =
578                 vec!("-quiet".to_string(),
579                      "-batch".to_string(),
580                      "-nx".to_string(),
581                      format!("-command={}", debugger_script.as_str().unwrap()));
582
583             let proc_args = ProcArgs {
584                 prog: debugger(),
585                 args: debugger_opts,
586             };
587
588             let environment = vec![("PYTHONPATH".to_string(), rust_pp_module_abs_path)];
589
590             debugger_run_result = compose_and_run(config,
591                                                   testfile,
592                                                   proc_args,
593                                                   environment,
594                                                   config.run_lib_path.as_slice(),
595                                                   None,
596                                                   None);
597         }
598     }
599
600     if !debugger_run_result.status.success() {
601         fatal("gdb failed to execute");
602     }
603
604     check_debugger_output(&debugger_run_result, check_lines.as_slice());
605 }
606
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");
610
611     while path.pop() {
612         if path.join(&path_postfix).is_file() {
613             return Some(path);
614         }
615     }
616
617     return None;
618 }
619
620 fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path) {
621     use std::io::process::{Command, ProcessOutput};
622
623     if config.lldb_python_dir.is_none() {
624         fatal("Can't run LLDB test because LLDB's python path is not set.");
625     }
626
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),
630         .. config.clone()
631     };
632
633     let config = &mut config;
634
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);
639     }
640
641     let exe_file = make_exe_name(config, testfile);
642
643     match config.lldb_version {
644         Some(ref version) => {
645             println!("NOTE: compiletest thinks it is using LLDB version {}",
646                      version.as_slice());
647         }
648         _ => {
649             println!("NOTE: compiletest does not know which version of \
650                       LLDB it is using");
651         }
652     }
653
654     // Parse debugger commands etc from test files
655     let DebuggerCommands {
656         commands,
657         check_lines,
658         breakpoint_lines,
659         ..
660     } = parse_debugger_commands(testfile, "lldb");
661
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");
665
666     // Make LLDB emit its version, so we have it documented in the test output
667     script_str.push_str("version\n");
668
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)
674                                                .as_str()
675                                                .unwrap()
676                                                .to_string();
677
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");
683
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",
687                                     line).as_slice());
688     }
689
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");
694     }
695
696     // Finally, quit the debugger
697     script_str.push_str("quit\n");
698
699     // Write the script into a file
700     debug!("script_str = {}", script_str);
701     dump_output_file(config,
702                      testfile,
703                      script_str.as_slice(),
704                      "debugger.script");
705     let debugger_script = make_out_name(config, testfile, "debugger.script");
706
707     // Let LLDB execute the script via lldb_batchmode.py
708     let debugger_run_result = run_lldb(config,
709                                        &exe_file,
710                                        &debugger_script,
711                                        &rust_src_root);
712
713     if !debugger_run_result.status.success() {
714         fatal_proc_rec("Error while running LLDB", &debugger_run_result);
715     }
716
717     check_debugger_output(&debugger_run_result, check_lines.as_slice());
718
719     fn run_lldb(config: &Config,
720                 test_executable: &Path,
721                 debugger_script: &Path,
722                 rust_src_root: &Path)
723                 -> ProcRes {
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"));
726
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())]);
732
733         let (status, out, err) = match cmd.spawn() {
734             Ok(process) => {
735                 let ProcessOutput { status, output, error } =
736                     process.wait_with_output().unwrap();
737
738                 (status,
739                  String::from_utf8(output).unwrap(),
740                  String::from_utf8(error).unwrap())
741             },
742             Err(e) => {
743                 fatal(format!("Failed to setup Python process for \
744                                LLDB script: {}", e).as_slice())
745             }
746         };
747
748         dump_output(config, test_executable, out.as_slice(), err.as_slice());
749         return ProcRes {
750             status: status,
751             stdout: out,
752             stderr: err,
753             cmdline: format!("{}", cmd)
754         };
755     }
756 }
757
758 struct DebuggerCommands {
759     commands: Vec<String>,
760     check_lines: Vec<String>,
761     breakpoint_lines: Vec<uint>,
762 }
763
764 fn parse_debugger_commands(file_path: &Path, debugger_prefix: &str)
765                            -> DebuggerCommands {
766     use std::io::{BufferedReader, File};
767
768     let command_directive = format!("{}-command", debugger_prefix);
769     let check_directive = format!("{}-check", debugger_prefix);
770
771     let mut breakpoint_lines = vec!();
772     let mut commands = vec!();
773     let mut check_lines = vec!();
774     let mut counter = 1;
775     let mut reader = BufferedReader::new(File::open(file_path).unwrap());
776     for line in reader.lines() {
777         match line {
778             Ok(line) => {
779                 if line.as_slice().contains("#break") {
780                     breakpoint_lines.push(counter);
781                 }
782
783                 header::parse_name_value_directive(
784                         line.as_slice(),
785                         command_directive.as_slice()).map(|cmd| {
786                     commands.push(cmd)
787                 });
788
789                 header::parse_name_value_directive(
790                         line.as_slice(),
791                         check_directive.as_slice()).map(|cmd| {
792                     check_lines.push(cmd)
793                 });
794             }
795             Err(e) => {
796                 fatal(format!("Error while parsing debugger commands: {}",
797                               e).as_slice())
798             }
799         }
800         counter += 1;
801     }
802
803     DebuggerCommands {
804         commands: commands,
805         check_lines: check_lines,
806         breakpoint_lines: breakpoint_lines,
807     }
808 }
809
810 fn cleanup_debug_info_options(options: &Option<String>) -> Option<String> {
811     if options.is_none() {
812         return None;
813     }
814
815     // Remove options that are either unwanted (-O) or may lead to duplicates due to RUSTFLAGS.
816     let options_to_remove = [
817         "-O".to_string(),
818         "-g".to_string(),
819         "--debuginfo".to_string()
820     ];
821     let new_options =
822         split_maybe_args(options).into_iter()
823                                  .filter(|x| !options_to_remove.contains(x))
824                                  .collect::<Vec<String>>()
825                                  .connect(" ");
826     Some(new_options)
827 }
828
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| {
836                 s.as_slice()
837                  .trim()
838                  .split_str("[...]")
839                  .map(|x| x.to_string())
840                  .collect()
841             }).collect();
842         // check if each line in props.check_lines appears in the
843         // output (in order)
844         let mut i = 0u;
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()) {
852                         Some(0)
853                     } else {
854                         None
855                     }
856                 } else {
857                     rest.find_str(frag.as_slice())
858                 };
859                 match found {
860                     None => {
861                         failed = true;
862                         break;
863                     }
864                     Some(i) => {
865                         rest = rest.slice_from(i + frag.len());
866                     }
867                 }
868                 first = false;
869             }
870             if !failed && rest.len() == 0 {
871                 i += 1u;
872             }
873             if i == num_check_lines {
874                 // all lines checked
875                 break;
876             }
877         }
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);
882         }
883     }
884 }
885
886 fn check_error_patterns(props: &TestProps,
887                         testfile: &Path,
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());
893     }
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);
900             next_err_idx += 1u;
901             if next_err_idx == props.error_patterns.len() {
902                 debug!("found all error patterns");
903                 done = true;
904                 break;
905             }
906             next_err_pat = &props.error_patterns[next_err_idx];
907         }
908     }
909     if done { return; }
910
911     let missing_patterns =
912         props.error_patterns.index(&(next_err_idx..));
913     if missing_patterns.len() == 1u {
914         fatal_proc_rec(format!("error pattern '{}' not found!",
915                               missing_patterns[0]).as_slice(),
916                       proc_res);
917     } else {
918         for pattern in missing_patterns.iter() {
919             error(format!("error pattern '{}' not found!",
920                           *pattern).as_slice());
921         }
922         fatal_proc_rec("multiple error patterns not found", proc_res);
923     }
924 }
925
926 fn check_no_compiler_crash(proc_res: &ProcRes) {
927     for line in proc_res.stderr.as_slice().lines() {
928         if line.starts_with("error: internal compiler error:") {
929             fatal_proc_rec("compiler encountered internal error",
930                           proc_res);
931         }
932     }
933 }
934
935 fn check_forbid_output(props: &TestProps,
936                        output_to_check: &str,
937                        proc_res: &ProcRes) {
938     for pat in props.forbid_output.iter() {
939         if output_to_check.contains(pat.as_slice()) {
940             fatal_proc_rec("forbidden pattern found in compiler output", proc_res);
941         }
942     }
943 }
944
945 fn check_expected_errors(expected_errors: Vec<errors::ExpectedError> ,
946                          testfile: &Path,
947                          proc_res: &ProcRes) {
948
949     // true if we found the error in question
950     let mut found_flags: Vec<_> = repeat(false).take(expected_errors.len()).collect();
951
952     if proc_res.status.success() {
953         fatal("process did not return an error status");
954     }
955
956     let prefixes = expected_errors.iter().map(|ee| {
957         format!("{:?}:{}:", testfile.display(), ee.line)
958     }).collect::<Vec<String> >();
959
960     #[cfg(windows)]
961     fn prefix_matches( line : &str, prefix : &str ) -> bool {
962         line.to_ascii_lowercase().starts_with(prefix.to_ascii_lowercase().as_slice())
963     }
964
965     #[cfg(unix)]
966     fn prefix_matches( line : &str, prefix : &str ) -> bool {
967         line.starts_with( prefix )
968     }
969
970     // Scan and extract our error/warning messages,
971     // which look like:
972     //    filename:line1:col1: line2:col2: *error:* msg
973     //    filename:line1:col1: line2:col2: *warning:* msg
974     // where line1:col1: is the starting point, line2:col2:
975     // is the ending point, and * represents ANSI color codes.
976     for line in proc_res.stderr.as_slice().lines() {
977         let mut was_expected = false;
978         for (i, ee) in expected_errors.iter().enumerate() {
979             if !found_flags[i] {
980                 debug!("prefix={} ee.kind={} ee.msg={} line={}",
981                        prefixes[i].as_slice(),
982                        ee.kind,
983                        ee.msg,
984                        line);
985                 if prefix_matches(line, prefixes[i].as_slice()) &&
986                     line.contains(ee.kind.as_slice()) &&
987                     line.contains(ee.msg.as_slice()) {
988                     found_flags[i] = true;
989                     was_expected = true;
990                     break;
991                 }
992             }
993         }
994
995         // ignore this msg which gets printed at the end
996         if line.contains("aborting due to") {
997             was_expected = true;
998         }
999
1000         if !was_expected && is_compiler_error_or_warning(line) {
1001             fatal_proc_rec(format!("unexpected compiler error or warning: '{}'",
1002                                   line).as_slice(),
1003                           proc_res);
1004         }
1005     }
1006
1007     for (i, &flag) in found_flags.iter().enumerate() {
1008         if !flag {
1009             let ee = &expected_errors[i];
1010             fatal_proc_rec(format!("expected {} on line {} not found: {}",
1011                                   ee.kind, ee.line, ee.msg).as_slice(),
1012                           proc_res);
1013         }
1014     }
1015 }
1016
1017 fn is_compiler_error_or_warning(line: &str) -> bool {
1018     let mut i = 0u;
1019     return
1020         scan_until_char(line, ':', &mut i) &&
1021         scan_char(line, ':', &mut i) &&
1022         scan_integer(line, &mut i) &&
1023         scan_char(line, ':', &mut i) &&
1024         scan_integer(line, &mut i) &&
1025         scan_char(line, ':', &mut i) &&
1026         scan_char(line, ' ', &mut i) &&
1027         scan_integer(line, &mut i) &&
1028         scan_char(line, ':', &mut i) &&
1029         scan_integer(line, &mut i) &&
1030         scan_char(line, ' ', &mut i) &&
1031         (scan_string(line, "error", &mut i) ||
1032          scan_string(line, "warning", &mut i));
1033 }
1034
1035 fn scan_until_char(haystack: &str, needle: char, idx: &mut uint) -> bool {
1036     if *idx >= haystack.len() {
1037         return false;
1038     }
1039     let opt = haystack.slice_from(*idx).find(needle);
1040     if opt.is_none() {
1041         return false;
1042     }
1043     *idx = opt.unwrap();
1044     return true;
1045 }
1046
1047 fn scan_char(haystack: &str, needle: char, idx: &mut uint) -> bool {
1048     if *idx >= haystack.len() {
1049         return false;
1050     }
1051     let range = haystack.char_range_at(*idx);
1052     if range.ch != needle {
1053         return false;
1054     }
1055     *idx = range.next;
1056     return true;
1057 }
1058
1059 fn scan_integer(haystack: &str, idx: &mut uint) -> bool {
1060     let mut i = *idx;
1061     while i < haystack.len() {
1062         let range = haystack.char_range_at(i);
1063         if range.ch < '0' || '9' < range.ch {
1064             break;
1065         }
1066         i = range.next;
1067     }
1068     if i == *idx {
1069         return false;
1070     }
1071     *idx = i;
1072     return true;
1073 }
1074
1075 fn scan_string(haystack: &str, needle: &str, idx: &mut uint) -> bool {
1076     let mut haystack_i = *idx;
1077     let mut needle_i = 0u;
1078     while needle_i < needle.len() {
1079         if haystack_i >= haystack.len() {
1080             return false;
1081         }
1082         let range = haystack.char_range_at(haystack_i);
1083         haystack_i = range.next;
1084         if !scan_char(needle, range.ch, &mut needle_i) {
1085             return false;
1086         }
1087     }
1088     *idx = haystack_i;
1089     return true;
1090 }
1091
1092 struct ProcArgs {
1093     prog: String,
1094     args: Vec<String>,
1095 }
1096
1097 struct ProcRes {
1098     status: ProcessExit,
1099     stdout: String,
1100     stderr: String,
1101     cmdline: String,
1102 }
1103
1104 fn compile_test(config: &Config, props: &TestProps,
1105                 testfile: &Path) -> ProcRes {
1106     compile_test_(config, props, testfile, &[])
1107 }
1108
1109 fn jit_test(config: &Config, props: &TestProps, testfile: &Path) -> ProcRes {
1110     compile_test_(config, props, testfile, &["--jit".to_string()])
1111 }
1112
1113 fn compile_test_(config: &Config, props: &TestProps,
1114                  testfile: &Path, extra_args: &[String]) -> ProcRes {
1115     let aux_dir = aux_output_dir_name(config, testfile);
1116     // FIXME (#9639): This needs to handle non-utf8 paths
1117     let mut link_args = vec!("-L".to_string(),
1118                              aux_dir.as_str().unwrap().to_string());
1119     link_args.extend(extra_args.iter().map(|s| s.clone()));
1120     let args = make_compile_args(config,
1121                                  props,
1122                                  link_args,
1123                                  |a, b| TargetLocation::ThisFile(make_exe_name(a, b)), testfile);
1124     compose_and_run_compiler(config, props, testfile, args, None)
1125 }
1126
1127 fn exec_compiled_test(config: &Config, props: &TestProps,
1128                       testfile: &Path) -> ProcRes {
1129
1130     let env = props.exec_env.clone();
1131
1132     match config.target.as_slice() {
1133
1134         "arm-linux-androideabi" => {
1135             _arm_exec_compiled_test(config, props, testfile, env)
1136         }
1137
1138         _=> {
1139             let aux_dir = aux_output_dir_name(config, testfile);
1140             compose_and_run(config,
1141                             testfile,
1142                             make_run_args(config, props, testfile),
1143                             env,
1144                             config.run_lib_path.as_slice(),
1145                             Some(aux_dir.as_str().unwrap()),
1146                             None)
1147         }
1148     }
1149 }
1150
1151 fn compose_and_run_compiler(
1152     config: &Config,
1153     props: &TestProps,
1154     testfile: &Path,
1155     args: ProcArgs,
1156     input: Option<String>) -> ProcRes {
1157
1158     if !props.aux_builds.is_empty() {
1159         ensure_dir(&aux_output_dir_name(config, testfile));
1160     }
1161
1162     let aux_dir = aux_output_dir_name(config, testfile);
1163     // FIXME (#9639): This needs to handle non-utf8 paths
1164     let extra_link_args = vec!("-L".to_string(), aux_dir.as_str().unwrap().to_string());
1165
1166     for rel_ab in props.aux_builds.iter() {
1167         let abs_ab = config.aux_base.join(rel_ab.as_slice());
1168         let aux_props = header::load_props(&abs_ab);
1169         let mut crate_type = if aux_props.no_prefer_dynamic {
1170             Vec::new()
1171         } else {
1172             vec!("--crate-type=dylib".to_string())
1173         };
1174         crate_type.extend(extra_link_args.clone().into_iter());
1175         let aux_args =
1176             make_compile_args(config,
1177                               &aux_props,
1178                               crate_type,
1179                               |a,b| {
1180                                   let f = make_lib_name(a, b, testfile);
1181                                   TargetLocation::ThisDirectory(f.dir_path())
1182                               },
1183                               &abs_ab);
1184         let auxres = compose_and_run(config,
1185                                      &abs_ab,
1186                                      aux_args,
1187                                      Vec::new(),
1188                                      config.compile_lib_path.as_slice(),
1189                                      Some(aux_dir.as_str().unwrap()),
1190                                      None);
1191         if !auxres.status.success() {
1192             fatal_proc_rec(
1193                 format!("auxiliary build of {:?} failed to compile: ",
1194                         abs_ab.display()).as_slice(),
1195                 &auxres);
1196         }
1197
1198         match config.target.as_slice() {
1199             "arm-linux-androideabi" => {
1200                 _arm_push_aux_shared_library(config, testfile);
1201             }
1202             _ => {}
1203         }
1204     }
1205
1206     compose_and_run(config,
1207                     testfile,
1208                     args,
1209                     Vec::new(),
1210                     config.compile_lib_path.as_slice(),
1211                     Some(aux_dir.as_str().unwrap()),
1212                     input)
1213 }
1214
1215 fn ensure_dir(path: &Path) {
1216     if path.is_dir() { return; }
1217     fs::mkdir(path, io::USER_RWX).unwrap();
1218 }
1219
1220 fn compose_and_run(config: &Config, testfile: &Path,
1221                    ProcArgs{ args, prog }: ProcArgs,
1222                    procenv: Vec<(String, String)> ,
1223                    lib_path: &str,
1224                    aux_path: Option<&str>,
1225                    input: Option<String>) -> ProcRes {
1226     return program_output(config, testfile, lib_path,
1227                           prog, aux_path, args, procenv, input);
1228 }
1229
1230 enum TargetLocation {
1231     ThisFile(Path),
1232     ThisDirectory(Path),
1233 }
1234
1235 fn make_compile_args<F>(config: &Config,
1236                         props: &TestProps,
1237                         extras: Vec<String> ,
1238                         xform: F,
1239                         testfile: &Path)
1240                         -> ProcArgs where
1241     F: FnOnce(&Config, &Path) -> TargetLocation,
1242 {
1243     let xform_file = xform(config, testfile);
1244     let target = if props.force_host {
1245         config.host.as_slice()
1246     } else {
1247         config.target.as_slice()
1248     };
1249     // FIXME (#9639): This needs to handle non-utf8 paths
1250     let mut args = vec!(testfile.as_str().unwrap().to_string(),
1251                         "-L".to_string(),
1252                         config.build_base.as_str().unwrap().to_string(),
1253                         format!("--target={}", target));
1254     args.push_all(extras.as_slice());
1255     if !props.no_prefer_dynamic {
1256         args.push("-C".to_string());
1257         args.push("prefer-dynamic".to_string());
1258     }
1259     let path = match xform_file {
1260         TargetLocation::ThisFile(path) => {
1261             args.push("-o".to_string());
1262             path
1263         }
1264         TargetLocation::ThisDirectory(path) => {
1265             args.push("--out-dir".to_string());
1266             path
1267         }
1268     };
1269     args.push(path.as_str().unwrap().to_string());
1270     if props.force_host {
1271         args.extend(split_maybe_args(&config.host_rustcflags).into_iter());
1272     } else {
1273         args.extend(split_maybe_args(&config.target_rustcflags).into_iter());
1274     }
1275     args.extend(split_maybe_args(&props.compile_flags).into_iter());
1276     return ProcArgs {
1277         prog: config.rustc_path.as_str().unwrap().to_string(),
1278         args: args,
1279     };
1280 }
1281
1282 fn make_lib_name(config: &Config, auxfile: &Path, testfile: &Path) -> Path {
1283     // what we return here is not particularly important, as it
1284     // happens; rustc ignores everything except for the directory.
1285     let auxname = output_testname(auxfile);
1286     aux_output_dir_name(config, testfile).join(&auxname)
1287 }
1288
1289 fn make_exe_name(config: &Config, testfile: &Path) -> Path {
1290     let mut f = output_base_name(config, testfile);
1291     if !os::consts::EXE_SUFFIX.is_empty() {
1292         let mut fname = f.filename().unwrap().to_vec();
1293         fname.extend(os::consts::EXE_SUFFIX.bytes());
1294         f.set_filename(fname);
1295     }
1296     f
1297 }
1298
1299 fn make_run_args(config: &Config, props: &TestProps, testfile: &Path) ->
1300    ProcArgs {
1301     // If we've got another tool to run under (valgrind),
1302     // then split apart its command
1303     let mut args = split_maybe_args(&config.runtool);
1304     let exe_file = make_exe_name(config, testfile);
1305
1306     // FIXME (#9639): This needs to handle non-utf8 paths
1307     args.push(exe_file.as_str().unwrap().to_string());
1308
1309     // Add the arguments in the run_flags directive
1310     args.extend(split_maybe_args(&props.run_flags).into_iter());
1311
1312     let prog = args.remove(0);
1313     return ProcArgs {
1314         prog: prog,
1315         args: args,
1316     };
1317 }
1318
1319 fn split_maybe_args(argstr: &Option<String>) -> Vec<String> {
1320     match *argstr {
1321         Some(ref s) => {
1322             s.as_slice()
1323              .split(' ')
1324              .filter_map(|s| {
1325                  if s.chars().all(|c| c.is_whitespace()) {
1326                      None
1327                  } else {
1328                      Some(s.to_string())
1329                  }
1330              }).collect()
1331         }
1332         None => Vec::new()
1333     }
1334 }
1335
1336 fn program_output(config: &Config, testfile: &Path, lib_path: &str, prog: String,
1337                   aux_path: Option<&str>, args: Vec<String>,
1338                   env: Vec<(String, String)>,
1339                   input: Option<String>) -> ProcRes {
1340     let cmdline =
1341         {
1342             let cmdline = make_cmdline(lib_path,
1343                                        prog.as_slice(),
1344                                        args.as_slice());
1345             logv(config, format!("executing {}", cmdline));
1346             cmdline
1347         };
1348     let procsrv::Result {
1349         out,
1350         err,
1351         status
1352     } = procsrv::run(lib_path,
1353                      prog.as_slice(),
1354                      aux_path,
1355                      args.as_slice(),
1356                      env,
1357                      input).expect(format!("failed to exec `{}`", prog).as_slice());
1358     dump_output(config, testfile, out.as_slice(), err.as_slice());
1359     return ProcRes {
1360         status: status,
1361         stdout: out,
1362         stderr: err,
1363         cmdline: cmdline,
1364     };
1365 }
1366
1367 // Linux and mac don't require adjusting the library search path
1368 #[cfg(unix)]
1369 fn make_cmdline(_libpath: &str, prog: &str, args: &[String]) -> String {
1370     format!("{} {}", prog, args.connect(" "))
1371 }
1372
1373 #[cfg(windows)]
1374 fn make_cmdline(libpath: &str, prog: &str, args: &[String]) -> String {
1375
1376     // Build the LD_LIBRARY_PATH variable as it would be seen on the command line
1377     // for diagnostic purposes
1378     fn lib_path_cmd_prefix(path: &str) -> String {
1379         format!("{}=\"{}\"", util::lib_path_env_var(), util::make_new_path(path))
1380     }
1381
1382     format!("{} {} {}", lib_path_cmd_prefix(libpath), prog, args.connect(" "))
1383 }
1384
1385 fn dump_output(config: &Config, testfile: &Path, out: &str, err: &str) {
1386     dump_output_file(config, testfile, out, "out");
1387     dump_output_file(config, testfile, err, "err");
1388     maybe_dump_to_stdout(config, out, err);
1389 }
1390
1391 fn dump_output_file(config: &Config, testfile: &Path,
1392                     out: &str, extension: &str) {
1393     let outfile = make_out_name(config, testfile, extension);
1394     File::create(&outfile).write(out.as_bytes()).unwrap();
1395 }
1396
1397 fn make_out_name(config: &Config, testfile: &Path, extension: &str) -> Path {
1398     output_base_name(config, testfile).with_extension(extension)
1399 }
1400
1401 fn aux_output_dir_name(config: &Config, testfile: &Path) -> Path {
1402     let f = output_base_name(config, testfile);
1403     let mut fname = f.filename().unwrap().to_vec();
1404     fname.extend("libaux".bytes());
1405     f.with_filename(fname)
1406 }
1407
1408 fn output_testname(testfile: &Path) -> Path {
1409     Path::new(testfile.filestem().unwrap())
1410 }
1411
1412 fn output_base_name(config: &Config, testfile: &Path) -> Path {
1413     config.build_base
1414         .join(&output_testname(testfile))
1415         .with_extension(config.stage_id.as_slice())
1416 }
1417
1418 fn maybe_dump_to_stdout(config: &Config, out: &str, err: &str) {
1419     if config.verbose {
1420         println!("------{}------------------------------", "stdout");
1421         println!("{}", out);
1422         println!("------{}------------------------------", "stderr");
1423         println!("{}", err);
1424         println!("------------------------------------------");
1425     }
1426 }
1427
1428 fn error(err: &str) { println!("\nerror: {}", err); }
1429
1430 fn fatal(err: &str) -> ! { error(err); panic!(); }
1431
1432 fn fatal_proc_rec(err: &str, proc_res: &ProcRes) -> ! {
1433     print!("\n\
1434 error: {}\n\
1435 status: {}\n\
1436 command: {}\n\
1437 stdout:\n\
1438 ------------------------------------------\n\
1439 {}\n\
1440 ------------------------------------------\n\
1441 stderr:\n\
1442 ------------------------------------------\n\
1443 {}\n\
1444 ------------------------------------------\n\
1445 \n",
1446              err, proc_res.status, proc_res.cmdline, proc_res.stdout,
1447              proc_res.stderr);
1448     panic!();
1449 }
1450
1451 fn _arm_exec_compiled_test(config: &Config,
1452                            props: &TestProps,
1453                            testfile: &Path,
1454                            env: Vec<(String, String)>)
1455                            -> ProcRes {
1456     let args = make_run_args(config, props, testfile);
1457     let cmdline = make_cmdline("",
1458                                args.prog.as_slice(),
1459                                args.args.as_slice());
1460
1461     // get bare program string
1462     let mut tvec: Vec<String> = args.prog
1463                                     .as_slice()
1464                                     .split('/')
1465                                     .map(|ts| ts.to_string())
1466                                     .collect();
1467     let prog_short = tvec.pop().unwrap();
1468
1469     // copy to target
1470     let copy_result = procsrv::run("",
1471                                    config.adb_path.as_slice(),
1472                                    None,
1473                                    &[
1474                                     "push".to_string(),
1475                                     args.prog.clone(),
1476                                     config.adb_test_dir.clone()
1477                                    ],
1478                                    vec!(("".to_string(), "".to_string())),
1479                                    Some("".to_string()))
1480         .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
1481
1482     if config.verbose {
1483         println!("push ({}) {} {} {}",
1484                  config.target,
1485                  args.prog,
1486                  copy_result.out,
1487                  copy_result.err);
1488     }
1489
1490     logv(config, format!("executing ({}) {}", config.target, cmdline));
1491
1492     let mut runargs = Vec::new();
1493
1494     // run test via adb_run_wrapper
1495     runargs.push("shell".to_string());
1496     for (key, val) in env.into_iter() {
1497         runargs.push(format!("{}={}", key, val));
1498     }
1499     runargs.push(format!("{}/adb_run_wrapper.sh", config.adb_test_dir));
1500     runargs.push(format!("{}", config.adb_test_dir));
1501     runargs.push(format!("{}", prog_short));
1502
1503     for tv in args.args.iter() {
1504         runargs.push(tv.to_string());
1505     }
1506     procsrv::run("",
1507                  config.adb_path.as_slice(),
1508                  None,
1509                  runargs.as_slice(),
1510                  vec!(("".to_string(), "".to_string())), Some("".to_string()))
1511         .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
1512
1513     // get exitcode of result
1514     runargs = Vec::new();
1515     runargs.push("shell".to_string());
1516     runargs.push("cat".to_string());
1517     runargs.push(format!("{}/{}.exitcode", config.adb_test_dir, prog_short));
1518
1519     let procsrv::Result{ out: exitcode_out, err: _, status: _ } =
1520         procsrv::run("",
1521                      config.adb_path.as_slice(),
1522                      None,
1523                      runargs.as_slice(),
1524                      vec!(("".to_string(), "".to_string())),
1525                      Some("".to_string()))
1526         .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
1527
1528     let mut exitcode: int = 0;
1529     for c in exitcode_out.as_slice().chars() {
1530         if !c.is_numeric() { break; }
1531         exitcode = exitcode * 10 + match c {
1532             '0' ... '9' => c as int - ('0' as int),
1533             _ => 101,
1534         }
1535     }
1536
1537     // get stdout of result
1538     runargs = Vec::new();
1539     runargs.push("shell".to_string());
1540     runargs.push("cat".to_string());
1541     runargs.push(format!("{}/{}.stdout", config.adb_test_dir, prog_short));
1542
1543     let procsrv::Result{ out: stdout_out, err: _, status: _ } =
1544         procsrv::run("",
1545                      config.adb_path.as_slice(),
1546                      None,
1547                      runargs.as_slice(),
1548                      vec!(("".to_string(), "".to_string())),
1549                      Some("".to_string()))
1550         .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
1551
1552     // get stderr of result
1553     runargs = Vec::new();
1554     runargs.push("shell".to_string());
1555     runargs.push("cat".to_string());
1556     runargs.push(format!("{}/{}.stderr", config.adb_test_dir, prog_short));
1557
1558     let procsrv::Result{ out: stderr_out, err: _, status: _ } =
1559         procsrv::run("",
1560                      config.adb_path.as_slice(),
1561                      None,
1562                      runargs.as_slice(),
1563                      vec!(("".to_string(), "".to_string())),
1564                      Some("".to_string()))
1565         .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
1566
1567     dump_output(config,
1568                 testfile,
1569                 stdout_out.as_slice(),
1570                 stderr_out.as_slice());
1571
1572     ProcRes {
1573         status: process::ProcessExit::ExitStatus(exitcode),
1574         stdout: stdout_out,
1575         stderr: stderr_out,
1576         cmdline: cmdline
1577     }
1578 }
1579
1580 fn _arm_push_aux_shared_library(config: &Config, testfile: &Path) {
1581     let tdir = aux_output_dir_name(config, testfile);
1582
1583     let dirs = fs::readdir(&tdir).unwrap();
1584     for file in dirs.iter() {
1585         if file.extension_str() == Some("so") {
1586             // FIXME (#9639): This needs to handle non-utf8 paths
1587             let copy_result = procsrv::run("",
1588                                            config.adb_path.as_slice(),
1589                                            None,
1590                                            &[
1591                                             "push".to_string(),
1592                                             file.as_str()
1593                                                 .unwrap()
1594                                                 .to_string(),
1595                                             config.adb_test_dir.to_string()
1596                                            ],
1597                                            vec!(("".to_string(),
1598                                                  "".to_string())),
1599                                            Some("".to_string()))
1600                 .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
1601
1602             if config.verbose {
1603                 println!("push ({}) {:?} {} {}",
1604                     config.target, file.display(),
1605                     copy_result.out, copy_result.err);
1606             }
1607         }
1608     }
1609 }
1610
1611 // codegen tests (vs. clang)
1612
1613 fn append_suffix_to_stem(p: &Path, suffix: &str) -> Path {
1614     if suffix.len() == 0 {
1615         (*p).clone()
1616     } else {
1617         let mut stem = p.filestem().unwrap().to_vec();
1618         stem.extend("-".bytes());
1619         stem.extend(suffix.bytes());
1620         p.with_filename(stem)
1621     }
1622 }
1623
1624 fn compile_test_and_save_bitcode(config: &Config, props: &TestProps,
1625                                  testfile: &Path) -> ProcRes {
1626     let aux_dir = aux_output_dir_name(config, testfile);
1627     // FIXME (#9639): This needs to handle non-utf8 paths
1628     let mut link_args = vec!("-L".to_string(),
1629                              aux_dir.as_str().unwrap().to_string());
1630     let llvm_args = vec!("--emit=llvm-bc,obj".to_string(),
1631                          "--crate-type=lib".to_string());
1632     link_args.extend(llvm_args.into_iter());
1633     let args = make_compile_args(config,
1634                                  props,
1635                                  link_args,
1636                                  |a, b| TargetLocation::ThisDirectory(
1637                                      output_base_name(a, b).dir_path()),
1638                                  testfile);
1639     compose_and_run_compiler(config, props, testfile, args, None)
1640 }
1641
1642 fn compile_cc_with_clang_and_save_bitcode(config: &Config, _props: &TestProps,
1643                                           testfile: &Path) -> ProcRes {
1644     let bitcodefile = output_base_name(config, testfile).with_extension("bc");
1645     let bitcodefile = append_suffix_to_stem(&bitcodefile, "clang");
1646     let testcc = testfile.with_extension("cc");
1647     let proc_args = ProcArgs {
1648         // FIXME (#9639): This needs to handle non-utf8 paths
1649         prog: config.clang_path.as_ref().unwrap().as_str().unwrap().to_string(),
1650         args: vec!("-c".to_string(),
1651                    "-emit-llvm".to_string(),
1652                    "-o".to_string(),
1653                    bitcodefile.as_str().unwrap().to_string(),
1654                    testcc.as_str().unwrap().to_string())
1655     };
1656     compose_and_run(config, testfile, proc_args, Vec::new(), "", None, None)
1657 }
1658
1659 fn extract_function_from_bitcode(config: &Config, _props: &TestProps,
1660                                  fname: &str, testfile: &Path,
1661                                  suffix: &str) -> ProcRes {
1662     let bitcodefile = output_base_name(config, testfile).with_extension("bc");
1663     let bitcodefile = append_suffix_to_stem(&bitcodefile, suffix);
1664     let extracted_bc = append_suffix_to_stem(&bitcodefile, "extract");
1665     let prog = config.llvm_bin_path.as_ref().unwrap().join("llvm-extract");
1666     let proc_args = ProcArgs {
1667         // FIXME (#9639): This needs to handle non-utf8 paths
1668         prog: prog.as_str().unwrap().to_string(),
1669         args: vec!(format!("-func={}", fname),
1670                    format!("-o={}", extracted_bc.as_str().unwrap()),
1671                    bitcodefile.as_str().unwrap().to_string())
1672     };
1673     compose_and_run(config, testfile, proc_args, Vec::new(), "", None, None)
1674 }
1675
1676 fn disassemble_extract(config: &Config, _props: &TestProps,
1677                        testfile: &Path, suffix: &str) -> ProcRes {
1678     let bitcodefile = output_base_name(config, testfile).with_extension("bc");
1679     let bitcodefile = append_suffix_to_stem(&bitcodefile, suffix);
1680     let extracted_bc = append_suffix_to_stem(&bitcodefile, "extract");
1681     let extracted_ll = extracted_bc.with_extension("ll");
1682     let prog = config.llvm_bin_path.as_ref().unwrap().join("llvm-dis");
1683     let proc_args = ProcArgs {
1684         // FIXME (#9639): This needs to handle non-utf8 paths
1685         prog: prog.as_str().unwrap().to_string(),
1686         args: vec!(format!("-o={}", extracted_ll.as_str().unwrap()),
1687                    extracted_bc.as_str().unwrap().to_string())
1688     };
1689     compose_and_run(config, testfile, proc_args, Vec::new(), "", None, None)
1690 }
1691
1692
1693 fn count_extracted_lines(p: &Path) -> uint {
1694     let x = File::open(&p.with_extension("ll")).read_to_end().unwrap();
1695     let x = str::from_utf8(x.as_slice()).unwrap();
1696     x.lines().count()
1697 }
1698
1699
1700 fn run_codegen_test(config: &Config, props: &TestProps,
1701                     testfile: &Path, mm: &mut MetricMap) {
1702
1703     if config.llvm_bin_path.is_none() {
1704         fatal("missing --llvm-bin-path");
1705     }
1706
1707     if config.clang_path.is_none() {
1708         fatal("missing --clang-path");
1709     }
1710
1711     let mut proc_res = compile_test_and_save_bitcode(config, props, testfile);
1712     if !proc_res.status.success() {
1713         fatal_proc_rec("compilation failed!", &proc_res);
1714     }
1715
1716     proc_res = extract_function_from_bitcode(config, props, "test", testfile, "");
1717     if !proc_res.status.success() {
1718         fatal_proc_rec("extracting 'test' function failed",
1719                       &proc_res);
1720     }
1721
1722     proc_res = disassemble_extract(config, props, testfile, "");
1723     if !proc_res.status.success() {
1724         fatal_proc_rec("disassembling extract failed", &proc_res);
1725     }
1726
1727
1728     let mut proc_res = compile_cc_with_clang_and_save_bitcode(config, props, testfile);
1729     if !proc_res.status.success() {
1730         fatal_proc_rec("compilation failed!", &proc_res);
1731     }
1732
1733     proc_res = extract_function_from_bitcode(config, props, "test", testfile, "clang");
1734     if !proc_res.status.success() {
1735         fatal_proc_rec("extracting 'test' function failed",
1736                       &proc_res);
1737     }
1738
1739     proc_res = disassemble_extract(config, props, testfile, "clang");
1740     if !proc_res.status.success() {
1741         fatal_proc_rec("disassembling extract failed", &proc_res);
1742     }
1743
1744     let base = output_base_name(config, testfile);
1745     let base_extract = append_suffix_to_stem(&base, "extract");
1746
1747     let base_clang = append_suffix_to_stem(&base, "clang");
1748     let base_clang_extract = append_suffix_to_stem(&base_clang, "extract");
1749
1750     let base_lines = count_extracted_lines(&base_extract);
1751     let clang_lines = count_extracted_lines(&base_clang_extract);
1752
1753     mm.insert_metric("clang-codegen-ratio",
1754                      (base_lines as f64) / (clang_lines as f64),
1755                      0.001);
1756 }