]> git.lizzy.rs Git - rust.git/blob - src/bin/miri-rustc-tests.rs
Add -Zmiri-env-exclude flag
[rust.git] / src / bin / miri-rustc-tests.rs
1 #![feature(rustc_private)]
2 extern crate miri;
3 extern crate getopts;
4 extern crate rustc;
5 extern crate rustc_metadata;
6 extern crate rustc_driver;
7 extern crate rustc_errors;
8 extern crate rustc_codegen_utils;
9 extern crate rustc_interface;
10 extern crate syntax;
11
12 use std::path::Path;
13 use std::io::Write;
14 use std::sync::{Mutex, Arc};
15 use std::io;
16
17
18 use rustc_interface::interface;
19 use rustc::hir::{self, itemlikevisit};
20 use rustc::ty::TyCtxt;
21 use rustc::hir::def_id::LOCAL_CRATE;
22 use rustc_driver::Compilation;
23
24 use miri::MiriConfig;
25
26 struct MiriCompilerCalls {
27     /// whether we are building for the host
28     host_target: bool,
29 }
30
31 impl rustc_driver::Callbacks for MiriCompilerCalls {
32     fn after_parsing(&mut self, compiler: &interface::Compiler) -> Compilation {
33         let attr = (
34             syntax::symbol::Symbol::intern("miri"),
35             syntax::feature_gate::AttributeType::Whitelisted,
36         );
37         compiler.session().plugin_attributes.borrow_mut().push(attr);
38
39         Compilation::Continue
40     }
41
42     fn after_analysis(&mut self, compiler: &interface::Compiler) -> Compilation {
43         compiler.session().abort_if_errors();
44         compiler.global_ctxt().unwrap().peek_mut().enter(|tcx| {
45             if std::env::args().any(|arg| arg == "--test") {
46                 struct Visitor<'tcx>(TyCtxt<'tcx>);
47                 impl<'tcx, 'hir> itemlikevisit::ItemLikeVisitor<'hir> for Visitor<'tcx> {
48                     fn visit_item(&mut self, i: &'hir hir::Item) {
49                         if let hir::ItemKind::Fn(.., body_id) = i.node {
50                             if i.attrs.iter().any(|attr| attr.check_name(syntax::symbol::sym::test)) {
51                                 let config = MiriConfig {
52                                     validate: true,
53                                     communicate: false,
54                                     excluded_env_vars: vec![],
55                                     args: vec![],
56                                     seed: None,
57                                 };
58                                 let did = self.0.hir().body_owner_def_id(body_id);
59                                 println!("running test: {}", self.0.def_path_debug_str(did));
60                                 miri::eval_main(self.0, did, config);
61                                 self.0.sess.abort_if_errors();
62                             }
63                         }
64                     }
65                     fn visit_trait_item(&mut self, _trait_item: &'hir hir::TraitItem) {}
66                     fn visit_impl_item(&mut self, _impl_item: &'hir hir::ImplItem) {}
67                 }
68                 tcx.hir().krate().visit_all_item_likes(&mut Visitor(tcx));
69             } else if let Some((entry_def_id, _)) = tcx.entry_fn(LOCAL_CRATE) {
70                 let config = MiriConfig {
71                     validate: true,
72                     communicate: false,
73                     args: vec![],
74                     seed: None
75                 };
76                 miri::eval_main(tcx, entry_def_id, config);
77
78                 compiler.session().abort_if_errors();
79             } else {
80                 println!("no main function found, assuming auxiliary build");
81             }
82         });
83
84         // Continue execution on host target
85         if self.host_target { Compilation::Continue } else { Compilation::Stop }
86     }
87 }
88
89 fn main() {
90     let path = option_env!("MIRI_RUSTC_TEST")
91         .map(String::from)
92         .unwrap_or_else(|| {
93             std::env::var("MIRI_RUSTC_TEST")
94                 .expect("need to set MIRI_RUSTC_TEST to path of rustc tests")
95         });
96
97     let mut mir_not_found = Vec::new();
98     let mut crate_not_found = Vec::new();
99     let mut success = 0;
100     let mut failed = Vec::new();
101     let mut c_abi_fns = Vec::new();
102     let mut abi = Vec::new();
103     let mut unsupported = Vec::new();
104     let mut unimplemented_intrinsic = Vec::new();
105     let mut limits = Vec::new();
106     let mut files: Vec<_> = std::fs::read_dir(path).unwrap().collect();
107     while let Some(file) = files.pop() {
108         let file = file.unwrap();
109         let path = file.path();
110         if file.metadata().unwrap().is_dir() {
111             if !path.to_str().unwrap().ends_with("auxiliary") {
112                 // add subdirs recursively
113                 files.extend(std::fs::read_dir(path).unwrap());
114             }
115             continue;
116         }
117         if !file.metadata().unwrap().is_file() || !path.to_str().unwrap().ends_with(".rs") {
118             continue;
119         }
120         let stderr = std::io::stderr();
121         write!(stderr.lock(), "test [miri-pass] {} ... ", path.display()).unwrap();
122         let mut host_target = false;
123         let mut args: Vec<String> = std::env::args().filter(|arg| {
124             if arg == "--miri_host_target" {
125                 host_target = true;
126                 false // remove the flag, rustc doesn't know it
127             } else {
128                 true
129             }
130         }).collect();
131         args.splice(1..1, miri::miri_default_args().iter().map(ToString::to_string));
132         // file to process
133         args.push(path.display().to_string());
134
135         let sysroot_flag = String::from("--sysroot");
136         if !args.contains(&sysroot_flag) {
137             args.push(sysroot_flag);
138             args.push(Path::new(&std::env::var("HOME").unwrap()).join(".xargo").join("HOST").display().to_string());
139         }
140
141         // A threadsafe buffer for writing.
142         #[derive(Default, Clone)]
143         struct BufWriter(Arc<Mutex<Vec<u8>>>);
144
145         impl Write for BufWriter {
146             fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
147                 self.0.lock().unwrap().write(buf)
148             }
149             fn flush(&mut self) -> io::Result<()> {
150                 self.0.lock().unwrap().flush()
151             }
152         }
153         let buf = BufWriter::default();
154         let output = buf.clone();
155         let result = std::panic::catch_unwind(|| {
156             let _ = rustc_driver::run_compiler(&args, &mut MiriCompilerCalls { host_target }, None, Some(Box::new(buf)));
157         });
158
159         match result {
160             Ok(()) => {
161                 success += 1;
162                 writeln!(stderr.lock(), "ok").unwrap()
163             },
164             Err(_) => {
165                 let output = output.0.lock().unwrap();
166                 let output_err = std::str::from_utf8(&output).unwrap();
167                 if let Some(text) = output_err.splitn(2, "no mir for `").nth(1) {
168                     let end = text.find('`').unwrap();
169                     mir_not_found.push(text[..end].to_string());
170                     writeln!(stderr.lock(), "NO MIR FOR `{}`", &text[..end]).unwrap();
171                 } else if let Some(text) = output_err.splitn(2, "can't find crate for `").nth(1) {
172                     let end = text.find('`').unwrap();
173                     crate_not_found.push(text[..end].to_string());
174                     writeln!(stderr.lock(), "CAN'T FIND CRATE FOR `{}`", &text[..end]).unwrap();
175                 } else {
176                     for text in output_err.split("error: ").skip(1) {
177                         let end = text.find('\n').unwrap_or(text.len());
178                         let c_abi = "can't call C ABI function: ";
179                         let unimplemented_intrinsic_s = "unimplemented intrinsic: ";
180                         let unsupported_s = "miri does not support ";
181                         let abi_s = "can't handle function with ";
182                         let limit_s = "reached the configured maximum ";
183                         if text.starts_with(c_abi) {
184                             c_abi_fns.push(text[c_abi.len()..end].to_string());
185                         } else if text.starts_with(unimplemented_intrinsic_s) {
186                             unimplemented_intrinsic.push(text[unimplemented_intrinsic_s.len()..end].to_string());
187                         } else if text.starts_with(unsupported_s) {
188                             unsupported.push(text[unsupported_s.len()..end].to_string());
189                         } else if text.starts_with(abi_s) {
190                             abi.push(text[abi_s.len()..end].to_string());
191                         } else if text.starts_with(limit_s) {
192                             limits.push(text[limit_s.len()..end].to_string());
193                         } else if text.find("aborting").is_none() {
194                             failed.push(text[..end].to_string());
195                         }
196                     }
197                     writeln!(stderr.lock(), "stderr: \n {}", output_err).unwrap();
198                 }
199             }
200         }
201     }
202     let stderr = std::io::stderr();
203     let mut stderr = stderr.lock();
204     writeln!(stderr, "{} success, {} no mir, {} crate not found, {} failed, \
205                         {} C fn, {} ABI, {} unsupported, {} intrinsic",
206                         success, mir_not_found.len(), crate_not_found.len(), failed.len(),
207                         c_abi_fns.len(), abi.len(), unsupported.len(), unimplemented_intrinsic.len()).unwrap();
208     writeln!(stderr, "# The \"other reasons\" errors").unwrap();
209     writeln!(stderr, "(sorted, deduplicated)").unwrap();
210     print_vec(&mut stderr, failed);
211
212     writeln!(stderr, "# can't call C ABI function").unwrap();
213     print_vec(&mut stderr, c_abi_fns);
214
215     writeln!(stderr, "# unsupported ABI").unwrap();
216     print_vec(&mut stderr, abi);
217
218     writeln!(stderr, "# unsupported").unwrap();
219     print_vec(&mut stderr, unsupported);
220
221     writeln!(stderr, "# unimplemented intrinsics").unwrap();
222     print_vec(&mut stderr, unimplemented_intrinsic);
223
224     writeln!(stderr, "# mir not found").unwrap();
225     print_vec(&mut stderr, mir_not_found);
226
227     writeln!(stderr, "# crate not found").unwrap();
228     print_vec(&mut stderr, crate_not_found);
229 }
230
231 fn print_vec<W: std::io::Write>(stderr: &mut W, v: Vec<String>) {
232     writeln!(stderr, "```").unwrap();
233     for (n, s) in vec_to_hist(v).into_iter().rev() {
234         writeln!(stderr, "{:4} {}", n, s).unwrap();
235     }
236     writeln!(stderr, "```").unwrap();
237 }
238
239 fn vec_to_hist<T: PartialEq + Ord>(mut v: Vec<T>) -> Vec<(usize, T)> {
240     v.sort();
241     let mut v = v.into_iter();
242     let mut result = Vec::new();
243     let mut current = v.next();
244     'outer: while let Some(current_val) = current {
245         let mut n = 1;
246         for next in &mut v {
247             if next == current_val {
248                 n += 1;
249             } else {
250                 result.push((n, current_val));
251                 current = Some(next);
252                 continue 'outer;
253             }
254         }
255         result.push((n, current_val));
256         break;
257     }
258     result.sort();
259     result
260 }