-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathruntest.rs
2665 lines (2308 loc) · 101 KB
/
runtest.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use common::{Config, TestPaths};
use common::{CompileFail, ParseFail, Pretty, RunFail, RunPass, RunPassValgrind};
use common::{Codegen, DebugInfoLldb, DebugInfoGdb, Rustdoc, CodegenUnits};
use common::{Incremental, RunMake, Ui, MirOpt};
use diff;
use errors::{self, ErrorKind, Error};
use filetime::FileTime;
use json;
use regex::Regex;
use header::TestProps;
use util::logv;
use std::collections::HashMap;
use std::collections::HashSet;
use std::env;
use std::ffi::OsString;
use std::fs::{self, File, create_dir_all};
use std::fmt;
use std::io::prelude::*;
use std::io::{self, BufReader};
use std::path::{Path, PathBuf};
use std::process::{Command, Output, ExitStatus, Stdio, Child};
use std::str;
use extract_gdb_version;
/// The name of the environment variable that holds dynamic library locations.
pub fn dylib_env_var() -> &'static str {
if cfg!(windows) {
"PATH"
} else if cfg!(target_os = "macos") {
"DYLD_LIBRARY_PATH"
} else if cfg!(target_os = "haiku") {
"LIBRARY_PATH"
} else {
"LD_LIBRARY_PATH"
}
}
pub fn run(config: Config, testpaths: &TestPaths) {
match &*config.target {
"arm-linux-androideabi" | "armv7-linux-androideabi" | "aarch64-linux-android" => {
if !config.adb_device_status {
panic!("android device not available");
}
}
_ => {
// android has its own gdb handling
if config.mode == DebugInfoGdb && config.gdb.is_none() {
panic!("gdb not available but debuginfo gdb debuginfo test requested");
}
}
}
if config.verbose {
// We're going to be dumping a lot of info. Start on a new line.
print!("\n\n");
}
debug!("running {:?}", testpaths.file.display());
let base_props = TestProps::from_file(&testpaths.file, None, &config);
let base_cx = TestCx { config: &config,
props: &base_props,
testpaths,
revision: None };
base_cx.init_all();
if base_props.revisions.is_empty() {
base_cx.run_revision()
} else {
for revision in &base_props.revisions {
let revision_props = TestProps::from_file(&testpaths.file,
Some(revision),
&config);
let rev_cx = TestCx {
config: &config,
props: &revision_props,
testpaths,
revision: Some(revision)
};
rev_cx.run_revision();
}
}
base_cx.complete_all();
File::create(::stamp(&config, testpaths)).unwrap();
}
struct TestCx<'test> {
config: &'test Config,
props: &'test TestProps,
testpaths: &'test TestPaths,
revision: Option<&'test str>
}
struct DebuggerCommands {
commands: Vec<String>,
check_lines: Vec<String>,
breakpoint_lines: Vec<usize>,
}
impl<'test> TestCx<'test> {
/// invoked once before any revisions have been processed
fn init_all(&self) {
assert!(self.revision.is_none(), "init_all invoked for a revision");
if let Incremental = self.config.mode {
self.init_incremental_test()
}
}
/// Code executed for each revision in turn (or, if there are no
/// revisions, exactly once, with revision == None).
fn run_revision(&self) {
match self.config.mode {
CompileFail |
ParseFail => self.run_cfail_test(),
RunFail => self.run_rfail_test(),
RunPass => self.run_rpass_test(),
RunPassValgrind => self.run_valgrind_test(),
Pretty => self.run_pretty_test(),
DebugInfoGdb => self.run_debuginfo_gdb_test(),
DebugInfoLldb => self.run_debuginfo_lldb_test(),
Codegen => self.run_codegen_test(),
Rustdoc => self.run_rustdoc_test(),
CodegenUnits => self.run_codegen_units_test(),
Incremental => self.run_incremental_test(),
RunMake => self.run_rmake_test(),
Ui => self.run_ui_test(),
MirOpt => self.run_mir_opt_test(),
}
}
/// Invoked after all revisions have executed.
fn complete_all(&self) {
assert!(self.revision.is_none(), "init_all invoked for a revision");
}
fn run_cfail_test(&self) {
let proc_res = self.compile_test();
if self.props.must_compile_successfully {
if !proc_res.status.success() {
self.fatal_proc_rec(
"test compilation failed although it shouldn't!",
&proc_res);
}
} else {
if proc_res.status.success() {
self.fatal_proc_rec(
&format!("{} test compiled successfully!", self.config.mode)[..],
&proc_res);
}
self.check_correct_failure_status(&proc_res);
}
let output_to_check = self.get_output(&proc_res);
let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
if !expected_errors.is_empty() {
if !self.props.error_patterns.is_empty() {
self.fatal("both error pattern and expected errors specified");
}
self.check_expected_errors(expected_errors, &proc_res);
} else {
self.check_error_patterns(&output_to_check, &proc_res);
}
self.check_no_compiler_crash(&proc_res);
self.check_forbid_output(&output_to_check, &proc_res);
}
fn run_rfail_test(&self) {
let proc_res = self.compile_test();
if !proc_res.status.success() {
self.fatal_proc_rec("compilation failed!", &proc_res);
}
let proc_res = self.exec_compiled_test();
// The value our Makefile configures valgrind to return on failure
const VALGRIND_ERR: i32 = 100;
if proc_res.status.code() == Some(VALGRIND_ERR) {
self.fatal_proc_rec("run-fail test isn't valgrind-clean!", &proc_res);
}
let output_to_check = self.get_output(&proc_res);
self.check_correct_failure_status(&proc_res);
self.check_error_patterns(&output_to_check, &proc_res);
}
fn get_output(&self, proc_res: &ProcRes) -> String {
if self.props.check_stdout {
format!("{}{}", proc_res.stdout, proc_res.stderr)
} else {
proc_res.stderr.clone()
}
}
fn check_correct_failure_status(&self, proc_res: &ProcRes) {
// The value the rust runtime returns on failure
const RUST_ERR: i32 = 1;
if proc_res.status.code() != Some(RUST_ERR) {
self.fatal_proc_rec(
&format!("failure produced the wrong error: {}",
proc_res.status),
proc_res);
}
}
fn run_rpass_test(&self) {
let proc_res = self.compile_test();
if !proc_res.status.success() {
self.fatal_proc_rec("compilation failed!", &proc_res);
}
// FIXME(#41968): Move this check to tidy?
let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
assert!(expected_errors.is_empty(),
"run-pass tests with expected warnings should be moved to ui/");
let proc_res = self.exec_compiled_test();
if !proc_res.status.success() {
self.fatal_proc_rec("test run failed!", &proc_res);
}
}
fn run_valgrind_test(&self) {
assert!(self.revision.is_none(), "revisions not relevant here");
if self.config.valgrind_path.is_none() {
assert!(!self.config.force_valgrind);
return self.run_rpass_test();
}
let mut proc_res = self.compile_test();
if !proc_res.status.success() {
self.fatal_proc_rec("compilation failed!", &proc_res);
}
let mut new_config = self.config.clone();
new_config.runtool = new_config.valgrind_path.clone();
let new_cx = TestCx { config: &new_config, ..*self };
proc_res = new_cx.exec_compiled_test();
if !proc_res.status.success() {
self.fatal_proc_rec("test run failed!", &proc_res);
}
}
#[cfg(feature = "stable")]
fn run_pretty_test(&self) {
self.fatal("pretty-printing tests can only be used with nightly Rust".into());
}
#[cfg(not(feature = "stable"))]
fn run_pretty_test(&self) {
if self.props.pp_exact.is_some() {
logv(self.config, "testing for exact pretty-printing".to_owned());
} else {
logv(self.config, "testing for converging pretty-printing".to_owned());
}
let rounds = match self.props.pp_exact { Some(_) => 1, None => 2 };
let mut src = String::new();
File::open(&self.testpaths.file).unwrap().read_to_string(&mut src).unwrap();
let mut srcs = vec![src];
let mut round = 0;
while round < rounds {
logv(self.config, format!("pretty-printing round {} revision {:?}",
round, self.revision));
let proc_res = self.print_source(srcs[round].to_owned(), &self.props.pretty_mode);
if !proc_res.status.success() {
self.fatal_proc_rec(&format!("pretty-printing failed in round {} revision {:?}",
round, self.revision),
&proc_res);
}
let ProcRes{ stdout, .. } = proc_res;
srcs.push(stdout);
round += 1;
}
let mut expected = match self.props.pp_exact {
Some(ref file) => {
let filepath = self.testpaths.file.parent().unwrap().join(file);
let mut s = String::new();
File::open(&filepath).unwrap().read_to_string(&mut s).unwrap();
s
}
None => { srcs[srcs.len() - 2].clone() }
};
let mut actual = srcs[srcs.len() - 1].clone();
if self.props.pp_exact.is_some() {
// Now we have to care about line endings
let cr = "\r".to_owned();
actual = actual.replace(&cr, "").to_owned();
expected = expected.replace(&cr, "").to_owned();
}
self.compare_source(&expected, &actual);
// If we're only making sure that the output matches then just stop here
if self.props.pretty_compare_only { return; }
// Finally, let's make sure it actually appears to remain valid code
let proc_res = self.typecheck_source(actual);
if !proc_res.status.success() {
self.fatal_proc_rec("pretty-printed source does not typecheck", &proc_res);
}
if !self.props.pretty_expanded { return }
// additionally, run `--pretty expanded` and try to build it.
let proc_res = self.print_source(srcs[round].clone(), "expanded");
if !proc_res.status.success() {
self.fatal_proc_rec("pretty-printing (expanded) failed", &proc_res);
}
let ProcRes{ stdout: expanded_src, .. } = proc_res;
let proc_res = self.typecheck_source(expanded_src);
if !proc_res.status.success() {
self.fatal_proc_rec(
"pretty-printed source (expanded) does not typecheck",
&proc_res);
}
}
#[cfg(not(feature = "stable"))]
fn print_source(&self, src: String, pretty_type: &str) -> ProcRes {
let aux_dir = self.aux_output_dir_name();
let mut rustc = Command::new(&self.config.rustc_path);
rustc.arg("-")
.args(&["-Z", &format!("unpretty={}", pretty_type)])
.args(&["--target", &self.config.target])
.arg("-L").arg(&aux_dir)
.args(self.split_maybe_args(&self.config.target_rustcflags))
.args(&self.props.compile_flags)
.envs(self.props.exec_env.clone());
self.compose_and_run(rustc,
self.config.compile_lib_path.to_str().unwrap(),
Some(aux_dir.to_str().unwrap()),
Some(src))
}
#[cfg(not(feature = "stable"))]
fn compare_source(&self,
expected: &str,
actual: &str) {
if expected != actual {
self.error("pretty-printed source does not match expected source");
println!("\n\
expected:\n\
------------------------------------------\n\
{}\n\
------------------------------------------\n\
actual:\n\
------------------------------------------\n\
{}\n\
------------------------------------------\n\
\n",
expected, actual);
panic!();
}
}
#[cfg(not(feature = "stable"))]
fn typecheck_source(&self, src: String) -> ProcRes {
let mut rustc = Command::new(&self.config.rustc_path);
let out_dir = self.output_base_name().with_extension("pretty-out");
let _ = fs::remove_dir_all(&out_dir);
create_dir_all(&out_dir).unwrap();
let target = if self.props.force_host {
&*self.config.host
} else {
&*self.config.target
};
let aux_dir = self.aux_output_dir_name();
rustc.arg("-")
.arg("-Zno-trans")
.arg("--out-dir").arg(&out_dir)
.arg(&format!("--target={}", target))
.arg("-L").arg(&self.config.build_base)
.arg("-L").arg(aux_dir);
if let Some(revision) = self.revision {
rustc.args(&["--cfg", revision]);
}
rustc.args(self.split_maybe_args(&self.config.target_rustcflags));
rustc.args(&self.props.compile_flags);
self.compose_and_run_compiler(rustc, Some(src))
}
fn run_debuginfo_gdb_test(&self) {
assert!(self.revision.is_none(), "revisions not relevant here");
let config = Config {
target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
.. self.config.clone()
};
let test_cx = TestCx {
config: &config,
..*self
};
test_cx.run_debuginfo_gdb_test_no_opt();
}
fn run_debuginfo_gdb_test_no_opt(&self) {
let prefixes = if self.config.gdb_native_rust {
// GDB with Rust
static PREFIXES: &'static [&'static str] = &["gdb", "gdbr"];
println!("NOTE: compiletest thinks it is using GDB with native rust support");
PREFIXES
} else {
// Generic GDB
static PREFIXES: &'static [&'static str] = &["gdb", "gdbg"];
println!("NOTE: compiletest thinks it is using GDB without native rust support");
PREFIXES
};
let DebuggerCommands {
commands,
check_lines,
breakpoint_lines
} = self.parse_debugger_commands(prefixes);
let mut cmds = commands.join("\n");
// compile test file (it should have 'compile-flags:-g' in the header)
let compiler_run_result = self.compile_test();
if !compiler_run_result.status.success() {
self.fatal_proc_rec("compilation failed!", &compiler_run_result);
}
let exe_file = self.make_exe_name();
let debugger_run_result;
match &*self.config.target {
"arm-linux-androideabi" |
"armv7-linux-androideabi" |
"aarch64-linux-android" => {
cmds = cmds.replace("run", "continue");
let tool_path = match self.config.android_cross_path.to_str() {
Some(x) => x.to_owned(),
None => self.fatal("cannot find android cross path")
};
// write debugger script
let mut script_str = String::with_capacity(2048);
script_str.push_str(&format!("set charset {}\n", Self::charset()));
script_str.push_str(&format!("set sysroot {}\n", tool_path));
script_str.push_str(&format!("file {}\n", exe_file.to_str().unwrap()));
script_str.push_str("target remote :5039\n");
script_str.push_str(&format!("set solib-search-path \
./{}/stage2/lib/rustlib/{}/lib/\n",
self.config.host, self.config.target));
for line in &breakpoint_lines {
script_str.push_str(&format!("break {:?}:{}\n",
self.testpaths.file.file_name()
.unwrap()
.to_string_lossy(),
*line)[..]);
}
script_str.push_str(&cmds);
script_str.push_str("\nquit\n");
debug!("script_str = {}", script_str);
self.dump_output_file(&script_str, "debugger.script");
let adb_path = &self.config.adb_path;
Command::new(adb_path)
.arg("push")
.arg(&exe_file)
.arg(&self.config.adb_test_dir)
.status()
.expect(&format!("failed to exec `{:?}`", adb_path));
Command::new(adb_path)
.args(&["forward", "tcp:5039", "tcp:5039"])
.status()
.expect(&format!("failed to exec `{:?}`", adb_path));
let adb_arg = format!("export LD_LIBRARY_PATH={}; \
gdbserver{} :5039 {}/{}",
self.config.adb_test_dir.clone(),
if self.config.target.contains("aarch64")
{"64"} else {""},
self.config.adb_test_dir.clone(),
exe_file.file_name().unwrap().to_str()
.unwrap());
debug!("adb arg: {}", adb_arg);
let mut adb = Command::new(adb_path)
.args(&["shell", &adb_arg])
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.expect(&format!("failed to exec `{:?}`", adb_path));
// Wait for the gdbserver to print out "Listening on port ..."
// at which point we know that it's started and then we can
// execute the debugger below.
let mut stdout = BufReader::new(adb.stdout.take().unwrap());
let mut line = String::new();
loop {
line.truncate(0);
stdout.read_line(&mut line).unwrap();
if line.starts_with("Listening on port 5039") {
break
}
}
drop(stdout);
let debugger_script = self.make_out_name("debugger.script");
// FIXME (#9639): This needs to handle non-utf8 paths
let debugger_opts =
vec!["-quiet".to_owned(),
"-batch".to_owned(),
"-nx".to_owned(),
format!("-command={}", debugger_script.to_str().unwrap())];
let mut gdb_path = tool_path;
gdb_path.push_str("/bin/gdb");
let Output {
status,
stdout,
stderr
} = Command::new(&gdb_path)
.args(&debugger_opts)
.output()
.expect(&format!("failed to exec `{:?}`", gdb_path));
let cmdline = {
let mut gdb = Command::new(&format!("{}-gdb", self.config.target));
gdb.args(&debugger_opts);
let cmdline = self.make_cmdline(&gdb, "");
logv(self.config, format!("executing {}", cmdline));
cmdline
};
debugger_run_result = ProcRes {
status,
stdout: String::from_utf8(stdout).unwrap(),
stderr: String::from_utf8(stderr).unwrap(),
cmdline,
};
if adb.kill().is_err() {
println!("Adb process is already finished.");
}
}
_ => {
let rust_src_root = self.config.find_rust_src_root().expect(
"Could not find Rust source root",
);
let rust_pp_module_rel_path = Path::new("./src/etc");
let rust_pp_module_abs_path = rust_src_root.join(rust_pp_module_rel_path)
.to_str()
.unwrap()
.to_owned();
// write debugger script
let mut script_str = String::with_capacity(2048);
script_str.push_str(&format!("set charset {}\n", Self::charset()));
script_str.push_str("show version\n");
match self.config.gdb_version {
Some(version) => {
println!("NOTE: compiletest thinks it is using GDB version {}",
version);
if version > extract_gdb_version("7.4").unwrap() {
// Add the directory containing the pretty printers to
// GDB's script auto loading safe path
script_str.push_str(
&format!("add-auto-load-safe-path {}\n",
rust_pp_module_abs_path.replace(r"\", r"\\"))
);
}
}
_ => {
println!("NOTE: compiletest does not know which version of \
GDB it is using");
}
}
// The following line actually doesn't have to do anything with
// pretty printing, it just tells GDB to print values on one line:
script_str.push_str("set print pretty off\n");
// Add the pretty printer directory to GDB's source-file search path
script_str.push_str(&format!("directory {}\n",
rust_pp_module_abs_path));
// Load the target executable
script_str.push_str(&format!("file {}\n",
exe_file.to_str().unwrap()
.replace(r"\", r"\\")));
// Force GDB to print values in the Rust format.
if self.config.gdb_native_rust {
script_str.push_str("set language rust\n");
}
// Add line breakpoints
for line in &breakpoint_lines {
script_str.push_str(&format!("break '{}':{}\n",
self.testpaths.file.file_name().unwrap()
.to_string_lossy(),
*line));
}
script_str.push_str(&cmds);
script_str.push_str("\nquit\n");
debug!("script_str = {}", script_str);
self.dump_output_file(&script_str, "debugger.script");
let debugger_script = self.make_out_name("debugger.script");
// FIXME (#9639): This needs to handle non-utf8 paths
let debugger_opts =
vec!["-quiet".to_owned(),
"-batch".to_owned(),
"-nx".to_owned(),
format!("-command={}", debugger_script.to_str().unwrap())];
let mut gdb = Command::new(self.config.gdb.as_ref().unwrap());
gdb.args(&debugger_opts)
.env("PYTHONPATH", rust_pp_module_abs_path);
debugger_run_result =
self.compose_and_run(gdb,
self.config.run_lib_path.to_str().unwrap(),
None,
None);
}
}
if !debugger_run_result.status.success() {
self.fatal_proc_rec("gdb failed to execute", &debugger_run_result);
}
self.check_debugger_output(&debugger_run_result, &check_lines);
}
fn run_debuginfo_lldb_test(&self) {
assert!(self.revision.is_none(), "revisions not relevant here");
if self.config.lldb_python_dir.is_none() {
self.fatal("Can't run LLDB test because LLDB's python path is not set.");
}
let config = Config {
target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
.. self.config.clone()
};
let test_cx = TestCx {
config: &config,
..*self
};
test_cx.run_debuginfo_lldb_test_no_opt();
}
fn run_debuginfo_lldb_test_no_opt(&self) {
// compile test file (it should have 'compile-flags:-g' in the header)
let compile_result = self.compile_test();
if !compile_result.status.success() {
self.fatal_proc_rec("compilation failed!", &compile_result);
}
let exe_file = self.make_exe_name();
match self.config.lldb_version {
Some(ref version) => {
println!("NOTE: compiletest thinks it is using LLDB version {}",
version);
}
_ => {
println!("NOTE: compiletest does not know which version of \
LLDB it is using");
}
}
// Parse debugger commands etc from test files
let DebuggerCommands {
commands,
check_lines,
breakpoint_lines,
..
} = self.parse_debugger_commands(&["lldb"]);
// Write debugger script:
// We don't want to hang when calling `quit` while the process is still running
let mut script_str = String::from("settings set auto-confirm true\n");
// Make LLDB emit its version, so we have it documented in the test output
script_str.push_str("version\n");
// Switch LLDB into "Rust mode"
let rust_src_root = self.config.find_rust_src_root().expect(
"Could not find Rust source root",
);
let rust_pp_module_rel_path = Path::new("./src/etc/lldb_rust_formatters.py");
let rust_pp_module_abs_path = rust_src_root.join(rust_pp_module_rel_path)
.to_str()
.unwrap()
.to_owned();
script_str.push_str(&format!("command script import {}\n",
&rust_pp_module_abs_path[..])[..]);
script_str.push_str("type summary add --no-value ");
script_str.push_str("--python-function lldb_rust_formatters.print_val ");
script_str.push_str("-x \".*\" --category Rust\n");
script_str.push_str("type category enable Rust\n");
// Set breakpoints on every line that contains the string "#break"
let source_file_name = self.testpaths.file.file_name().unwrap().to_string_lossy();
for line in &breakpoint_lines {
script_str.push_str(&format!("breakpoint set --file '{}' --line {}\n",
source_file_name,
line));
}
// Append the other commands
for line in &commands {
script_str.push_str(line);
script_str.push_str("\n");
}
// Finally, quit the debugger
script_str.push_str("\nquit\n");
// Write the script into a file
debug!("script_str = {}", script_str);
self.dump_output_file(&script_str, "debugger.script");
let debugger_script = self.make_out_name("debugger.script");
// Let LLDB execute the script via lldb_batchmode.py
let debugger_run_result = self.run_lldb(&exe_file,
&debugger_script,
&rust_src_root);
if !debugger_run_result.status.success() {
self.fatal_proc_rec("Error while running LLDB", &debugger_run_result);
}
self.check_debugger_output(&debugger_run_result, &check_lines);
}
fn run_lldb(&self,
test_executable: &Path,
debugger_script: &Path,
rust_src_root: &Path)
-> ProcRes {
// Prepare the lldb_batchmode which executes the debugger script
let lldb_script_path = rust_src_root.join("src/etc/lldb_batchmode.py");
self.cmd2procres(Command::new(&self.config.lldb_python)
.arg(&lldb_script_path)
.arg(test_executable)
.arg(debugger_script)
.env("PYTHONPATH",
self.config.lldb_python_dir.as_ref().unwrap()))
}
fn cmd2procres(&self, cmd: &mut Command) -> ProcRes {
let (status, out, err) = match cmd.output() {
Ok(Output { status, stdout, stderr }) => {
(status,
String::from_utf8(stdout).unwrap(),
String::from_utf8(stderr).unwrap())
},
Err(e) => {
self.fatal(&format!("Failed to setup Python process for \
LLDB script: {}", e))
}
};
self.dump_output(&out, &err);
ProcRes {
status,
stdout: out,
stderr: err,
cmdline: format!("{:?}", cmd)
}
}
fn parse_debugger_commands(&self, debugger_prefixes: &[&str]) -> DebuggerCommands {
let directives = debugger_prefixes.iter().map(|prefix| (
format!("{}-command", prefix),
format!("{}-check", prefix),
)).collect::<Vec<_>>();
let mut breakpoint_lines = vec![];
let mut commands = vec![];
let mut check_lines = vec![];
let mut counter = 1;
let reader = BufReader::new(File::open(&self.testpaths.file).unwrap());
for line in reader.lines() {
match line {
Ok(line) => {
if line.contains("#break") {
breakpoint_lines.push(counter);
}
for &(ref command_directive, ref check_directive) in &directives {
self.config.parse_name_value_directive(
&line,
command_directive).map(|cmd| {
commands.push(cmd)
});
self.config.parse_name_value_directive(
&line,
check_directive).map(|cmd| {
check_lines.push(cmd)
});
}
}
Err(e) => {
self.fatal(&format!("Error while parsing debugger commands: {}", e))
}
}
counter += 1;
}
DebuggerCommands {
commands,
check_lines,
breakpoint_lines,
}
}
fn cleanup_debug_info_options(&self, options: &Option<String>) -> Option<String> {
if options.is_none() {
return None;
}
// Remove options that are either unwanted (-O) or may lead to duplicates due to RUSTFLAGS.
let options_to_remove = [
"-O".to_owned(),
"-g".to_owned(),
"--debuginfo".to_owned()
];
let new_options =
self.split_maybe_args(options).into_iter()
.filter(|x| !options_to_remove.contains(x))
.collect::<Vec<String>>();
Some(new_options.join(" "))
}
fn check_debugger_output(&self, debugger_run_result: &ProcRes, check_lines: &[String]) {
let num_check_lines = check_lines.len();
let mut check_line_index = 0;
for line in debugger_run_result.stdout.lines() {
if check_line_index >= num_check_lines {
break;
}
if check_single_line(line, &(check_lines[check_line_index])[..]) {
check_line_index += 1;
}
}
if check_line_index != num_check_lines && num_check_lines > 0 {
self.fatal_proc_rec(&format!("line not found in debugger output: {}",
check_lines[check_line_index]),
debugger_run_result);
}
fn check_single_line(line: &str, check_line: &str) -> bool {
// Allow check lines to leave parts unspecified (e.g., uninitialized
// bits in the wrong case of an enum) with the notation "[...]".
let line = line.trim();
let check_line = check_line.trim();
let can_start_anywhere = check_line.starts_with("[...]");
let can_end_anywhere = check_line.ends_with("[...]");
let check_fragments: Vec<&str> = check_line.split("[...]")
.filter(|frag| !frag.is_empty())
.collect();
if check_fragments.is_empty() {
return true;
}
let (mut rest, first_fragment) = if can_start_anywhere {
match line.find(check_fragments[0]) {
Some(pos) => (&line[pos + check_fragments[0].len() ..], 1),
None => return false
}
} else {
(line, 0)
};
for current_fragment in &check_fragments[first_fragment..] {
match rest.find(current_fragment) {
Some(pos) => {
rest = &rest[pos + current_fragment.len() .. ];
}
None => return false
}
}
if !can_end_anywhere && !rest.is_empty() {
return false;
}
true
}
}
fn check_error_patterns(&self,
output_to_check: &str,
proc_res: &ProcRes) {
if self.props.error_patterns.is_empty() {
if self.props.must_compile_successfully {
return
} else {
self.fatal(&format!("no error pattern specified in {:?}",
self.testpaths.file.display()));
}
}
let mut next_err_idx = 0;
let mut next_err_pat = self.props.error_patterns[next_err_idx].trim();
let mut done = false;
for line in output_to_check.lines() {
if line.contains(next_err_pat) {
debug!("found error pattern {}", next_err_pat);
next_err_idx += 1;
if next_err_idx == self.props.error_patterns.len() {
debug!("found all error patterns");
done = true;
break;
}
next_err_pat = self.props.error_patterns[next_err_idx].trim();
}
}
if done { return; }
let missing_patterns = &self.props.error_patterns[next_err_idx..];
if missing_patterns.len() == 1 {
self.fatal_proc_rec(
&format!("error pattern '{}' not found!", missing_patterns[0]),
proc_res);
} else {
for pattern in missing_patterns {
self.error(&format!("error pattern '{}' not found!", *pattern));
}
self.fatal_proc_rec("multiple error patterns not found", proc_res);
}
}
fn check_no_compiler_crash(&self, proc_res: &ProcRes) {
for line in proc_res.stderr.lines() {
if line.contains("error: internal compiler error") {
self.fatal_proc_rec("compiler encountered internal error", proc_res);
}
}
}
fn check_forbid_output(&self,
output_to_check: &str,
proc_res: &ProcRes) {
for pat in &self.props.forbid_output {