]> git.lizzy.rs Git - rust.git/blob - src/bin/miri.rs
Auto merge of #957 - christianpoveda:ptr-align-offset, r=RalfJung
[rust.git] / src / bin / miri.rs
1 #![feature(rustc_private)]
2
3 extern crate env_logger;
4 extern crate getopts;
5 #[macro_use]
6 extern crate log;
7 extern crate log_settings;
8 extern crate miri;
9 extern crate rustc;
10 extern crate rustc_metadata;
11 extern crate rustc_driver;
12 extern crate rustc_errors;
13 extern crate rustc_codegen_utils;
14 extern crate rustc_interface;
15 extern crate syntax;
16
17 use std::str::FromStr;
18 use std::env;
19
20 use hex::FromHexError;
21
22 use rustc_interface::interface;
23 use rustc::hir::def_id::LOCAL_CRATE;
24 use rustc_driver::Compilation;
25
26 struct MiriCompilerCalls {
27     miri_config: miri::MiriConfig,
28 }
29
30 impl rustc_driver::Callbacks for MiriCompilerCalls {
31     fn after_parsing(&mut self, compiler: &interface::Compiler) -> Compilation {
32         let attr = (
33             syntax::symbol::Symbol::intern("miri"),
34             syntax::feature_gate::AttributeType::Whitelisted,
35         );
36         compiler.session().plugin_attributes.borrow_mut().push(attr);
37
38         Compilation::Continue
39     }
40
41     fn after_analysis(&mut self, compiler: &interface::Compiler) -> Compilation {
42         init_late_loggers();
43         compiler.session().abort_if_errors();
44
45         compiler.global_ctxt().unwrap().peek_mut().enter(|tcx| {
46             let (entry_def_id, _) = tcx.entry_fn(LOCAL_CRATE).expect("no main function found!");
47             let mut config = self.miri_config.clone();
48
49             // Add filename to `miri` arguments.
50             config.args.insert(0, compiler.input().filestem().to_string());
51
52             miri::eval_main(tcx, entry_def_id, config);
53         });
54
55         compiler.session().abort_if_errors();
56
57         Compilation::Stop
58     }
59 }
60
61 fn init_early_loggers() {
62     // Note that our `extern crate log` is *not* the same as rustc's; as a result, we have to
63     // initialize them both, and we always initialize `miri`'s first.
64     let env = env_logger::Env::new().filter("MIRI_LOG").write_style("MIRI_LOG_STYLE");
65     env_logger::init_from_env(env);
66     // We only initialize `rustc` if the env var is set (so the user asked for it).
67     // If it is not set, we avoid initializing now so that we can initialize
68     // later with our custom settings, and *not* log anything for what happens before
69     // `miri` gets started.
70     if env::var("RUSTC_LOG").is_ok() {
71         rustc_driver::init_rustc_env_logger();
72     }
73 }
74
75 fn init_late_loggers() {
76     // We initialize loggers right before we start evaluation. We overwrite the `RUSTC_LOG`
77     // env var if it is not set, control it based on `MIRI_LOG`.
78     if let Ok(var) = env::var("MIRI_LOG") {
79         if env::var("RUSTC_LOG").is_err() {
80             // We try to be a bit clever here: if `MIRI_LOG` is just a single level
81             // used for everything, we only apply it to the parts of rustc that are
82             // CTFE-related. Otherwise, we use it verbatim for `RUSTC_LOG`.
83             // This way, if you set `MIRI_LOG=trace`, you get only the right parts of
84             // rustc traced, but you can also do `MIRI_LOG=miri=trace,rustc_mir::interpret=debug`.
85             if log::Level::from_str(&var).is_ok() {
86                 env::set_var("RUSTC_LOG",
87                     &format!("rustc::mir::interpret={0},rustc_mir::interpret={0}", var));
88             } else {
89                 env::set_var("RUSTC_LOG", &var);
90             }
91             rustc_driver::init_rustc_env_logger();
92         }
93     }
94
95     // If `MIRI_BACKTRACE` is set and `RUSTC_CTFE_BACKTRACE` is not, set `RUSTC_CTFE_BACKTRACE`.
96     // Do this late, so we ideally only apply this to Miri's errors.
97     if let Ok(var) = env::var("MIRI_BACKTRACE") {
98         if env::var("RUSTC_CTFE_BACKTRACE") == Err(env::VarError::NotPresent) {
99             env::set_var("RUSTC_CTFE_BACKTRACE", &var);
100         }
101     }
102 }
103
104 /// Returns the "default sysroot" that Miri will use if no `--sysroot` flag is set.
105 /// Should be a compile-time constant.
106 fn compile_time_sysroot() -> Option<String> {
107     if option_env!("RUSTC_STAGE").is_some() {
108         // This is being built as part of rustc, and gets shipped with rustup.
109         // We can rely on the sysroot computation in librustc.
110         return None;
111     }
112     // For builds outside rustc, we need to ensure that we got a sysroot
113     // that gets used as a default.  The sysroot computation in librustc would
114     // end up somewhere in the build dir.
115     // Taken from PR <https://github.com/Manishearth/rust-clippy/pull/911>.
116     let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
117     let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
118     Some(match (home, toolchain) {
119         (Some(home), Some(toolchain)) => format!("{}/toolchains/{}", home, toolchain),
120         _ => {
121             option_env!("RUST_SYSROOT")
122                 .expect("To build Miri without rustup, set the `RUST_SYSROOT` env var at build time")
123                 .to_owned()
124         }
125     })
126 }
127
128 fn main() {
129     init_early_loggers();
130
131     // Parse our arguments and split them across `rustc` and `miri`.
132     let mut validate = true;
133     let mut communicate = false;
134     let mut seed: Option<u64> = None;
135     let mut rustc_args = vec![];
136     let mut miri_args = vec![];
137     let mut after_dashdash = false;
138     let mut excluded_env_vars = vec![];
139     for arg in std::env::args() {
140         if rustc_args.is_empty() {
141             // Very first arg: for `rustc`.
142             rustc_args.push(arg);
143         }
144         else if after_dashdash {
145             // Everything that comes after are `miri` args.
146             miri_args.push(arg);
147         } else {
148             match arg.as_str() {
149                 "-Zmiri-disable-validation" => {
150                     validate = false;
151                 },
152                 "-Zmiri-disable-isolation" => {
153                     communicate = true;
154                 },
155                 "--" => {
156                     after_dashdash = true;
157                 }
158                 arg if arg.starts_with("-Zmiri-seed=") => {
159                     if seed.is_some() {
160                         panic!("Cannot specify -Zmiri-seed multiple times!");
161                     }
162                     let seed_raw = hex::decode(arg.trim_start_matches("-Zmiri-seed="))
163                         .unwrap_or_else(|err| match err {
164                             FromHexError::InvalidHexCharacter { .. } => panic!(
165                                 "-Zmiri-seed should only contain valid hex digits [0-9a-fA-F]"
166                             ),
167                             FromHexError::OddLength => panic!("-Zmiri-seed should have an even number of digits"),
168                             err => panic!("Unknown error decoding -Zmiri-seed as hex: {:?}", err),
169                         });
170                     if seed_raw.len() > 8 {
171                         panic!(format!("-Zmiri-seed must be at most 8 bytes, was {}", seed_raw.len()));
172                     }
173
174                     let mut bytes = [0; 8];
175                     bytes[..seed_raw.len()].copy_from_slice(&seed_raw);
176                     seed = Some(u64::from_be_bytes(bytes));
177
178                 },
179                 arg if arg.starts_with("-Zmiri-env-exclude=") => {
180                     excluded_env_vars.push(arg.trim_start_matches("-Zmiri-env-exclude=").to_owned());
181                 },
182                 _ => {
183                     rustc_args.push(arg);
184                 }
185             }
186         }
187     }
188
189     // Determine sysroot if needed.  Make sure we always call `compile_time_sysroot`
190     // as that also does some sanity-checks of the environment we were built in.
191     // FIXME: Ideally we'd turn a bad build env into a compile-time error, but
192     // CTFE does not seem powerful enough for that yet.
193     if let Some(sysroot) = compile_time_sysroot() {
194         let sysroot_flag = "--sysroot";
195         if !rustc_args.iter().any(|e| e == sysroot_flag) {
196             // We need to overwrite the default that librustc would compute.
197             rustc_args.push(sysroot_flag.to_owned());
198             rustc_args.push(sysroot);
199         }
200     }
201
202     // Finally, add the default flags all the way in the beginning, but after the binary name.
203     rustc_args.splice(1..1, miri::miri_default_args().iter().map(ToString::to_string));
204
205     debug!("rustc arguments: {:?}", rustc_args);
206     debug!("miri arguments: {:?}", miri_args);
207     let miri_config = miri::MiriConfig {
208         validate,
209         communicate,
210         excluded_env_vars,
211         seed,
212         args: miri_args,
213     };
214     rustc_driver::install_ice_hook();
215     let result = rustc_driver::catch_fatal_errors(move || {
216         rustc_driver::run_compiler(&rustc_args, &mut MiriCompilerCalls { miri_config }, None, None)
217     }).and_then(|result| result);
218     std::process::exit(result.is_err() as i32);
219 }