]> git.lizzy.rs Git - rust.git/blob - src/bin/miri.rs
fix some comments, and run_compiler return type
[rust.git] / src / bin / miri.rs
1 #![feature(rustc_private)]
2
3 extern crate rustc_middle;
4 extern crate rustc_driver;
5 extern crate rustc_hir;
6 extern crate rustc_interface;
7 extern crate rustc_session;
8
9 use std::convert::TryFrom;
10 use std::env;
11 use std::str::FromStr;
12
13 use hex::FromHexError;
14 use log::debug;
15
16 use rustc_session::CtfeBacktrace;
17 use rustc_driver::Compilation;
18 use rustc_hir::def_id::LOCAL_CRATE;
19 use rustc_middle::ty::TyCtxt;
20
21 struct MiriCompilerCalls {
22     miri_config: miri::MiriConfig,
23 }
24
25 impl rustc_driver::Callbacks for MiriCompilerCalls {
26     fn after_analysis<'tcx>(
27         &mut self,
28         compiler: &rustc_interface::interface::Compiler,
29         queries: &'tcx rustc_interface::Queries<'tcx>,
30     ) -> Compilation {
31         compiler.session().abort_if_errors();
32
33         queries.global_ctxt().unwrap().peek_mut().enter(|tcx| {
34             init_late_loggers(tcx);
35             let (entry_def_id, _) = tcx.entry_fn(LOCAL_CRATE).expect("no main function found!");
36             let mut config = self.miri_config.clone();
37
38             // Add filename to `miri` arguments.
39             config.args.insert(0, compiler.input().filestem().to_string());
40
41             if let Some(return_code) = miri::eval_main(tcx, entry_def_id.to_def_id(), config) {
42                 std::process::exit(
43                     i32::try_from(return_code).expect("Return value was too large!"),
44                 );
45             }
46         });
47
48         compiler.session().abort_if_errors();
49
50         Compilation::Stop
51     }
52 }
53
54 fn init_early_loggers() {
55     // Note that our `extern crate log` is *not* the same as rustc's; as a result, we have to
56     // initialize them both, and we always initialize `miri`'s first.
57     let env = env_logger::Env::new().filter("MIRI_LOG").write_style("MIRI_LOG_STYLE");
58     env_logger::init_from_env(env);
59     // We only initialize `rustc` if the env var is set (so the user asked for it).
60     // If it is not set, we avoid initializing now so that we can initialize
61     // later with our custom settings, and *not* log anything for what happens before
62     // `miri` gets started.
63     if env::var_os("RUSTC_LOG").is_some() {
64         rustc_driver::init_rustc_env_logger();
65     }
66 }
67
68 fn init_late_loggers(tcx: TyCtxt<'_>) {
69     // We initialize loggers right before we start evaluation. We overwrite the `RUSTC_LOG`
70     // env var if it is not set, control it based on `MIRI_LOG`.
71     // (FIXME: use `var_os`, but then we need to manually concatenate instead of `format!`.)
72     if let Ok(var) = env::var("MIRI_LOG") {
73         if env::var_os("RUSTC_LOG").is_none() {
74             // We try to be a bit clever here: if `MIRI_LOG` is just a single level
75             // used for everything, we only apply it to the parts of rustc that are
76             // CTFE-related. Otherwise, we use it verbatim for `RUSTC_LOG`.
77             // This way, if you set `MIRI_LOG=trace`, you get only the right parts of
78             // rustc traced, but you can also do `MIRI_LOG=miri=trace,rustc_mir::interpret=debug`.
79             if log::Level::from_str(&var).is_ok() {
80                 env::set_var(
81                     "RUSTC_LOG",
82                     &format!("rustc_middle::mir::interpret={0},rustc_mir::interpret={0}", var),
83                 );
84             } else {
85                 env::set_var("RUSTC_LOG", &var);
86             }
87             rustc_driver::init_rustc_env_logger();
88         }
89     }
90
91     // If `MIRI_BACKTRACE` is set and `RUSTC_CTFE_BACKTRACE` is not, set `RUSTC_CTFE_BACKTRACE`.
92     // Do this late, so we ideally only apply this to Miri's errors.
93     if let Some(val) = env::var_os("MIRI_BACKTRACE") {
94         let ctfe_backtrace = match &*val.to_string_lossy() {
95             "immediate" => CtfeBacktrace::Immediate,
96             "0" => CtfeBacktrace::Disabled,
97             _ => CtfeBacktrace::Capture,
98         };
99         *tcx.sess.ctfe_backtrace.borrow_mut() = ctfe_backtrace;
100     }
101 }
102
103 /// Returns the "default sysroot" that Miri will use if no `--sysroot` flag is set.
104 /// Should be a compile-time constant.
105 fn compile_time_sysroot() -> Option<String> {
106     if option_env!("RUSTC_STAGE").is_some() {
107         // This is being built as part of rustc, and gets shipped with rustup.
108         // We can rely on the sysroot computation in librustc_session.
109         return None;
110     }
111     // For builds outside rustc, we need to ensure that we got a sysroot
112     // that gets used as a default.  The sysroot computation in librustc_session would
113     // end up somewhere in the build dir (see `get_or_default_sysroot`).
114     // Taken from PR <https://github.com/Manishearth/rust-clippy/pull/911>.
115     let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
116     let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
117     Some(match (home, toolchain) {
118         (Some(home), Some(toolchain)) => format!("{}/toolchains/{}", home, toolchain),
119         _ => option_env!("RUST_SYSROOT")
120             .expect("To build Miri without rustup, set the `RUST_SYSROOT` env var at build time")
121             .to_owned(),
122     })
123 }
124
125 /// Execute a compiler with the given CLI arguments and callbacks.
126 fn run_compiler(mut args: Vec<String>, callbacks: &mut (dyn rustc_driver::Callbacks + Send)) -> ! {
127     // Make sure we use the right default sysroot. The default sysroot is wrong,
128     // because `get_or_default_sysroot` in `librustc_session` bases that on `current_exe`.
129     //
130     // Make sure we always call `compile_time_sysroot` as that also does some sanity-checks
131     // of the environment we were built in.
132     // FIXME: Ideally we'd turn a bad build env into a compile-time error via CTFE or so.
133     if let Some(sysroot) = compile_time_sysroot() {
134         let sysroot_flag = "--sysroot";
135         if !args.iter().any(|e| e == sysroot_flag) {
136             // We need to overwrite the default that librustc_session would compute.
137             args.push(sysroot_flag.to_owned());
138             args.push(sysroot);
139         }
140     }
141
142     // Some options have different defaults in Miri than in plain rustc; apply those by making
143     // them the first arguments after the binary name (but later arguments can overwrite them).
144     args.splice(1..1, miri::miri_default_args().iter().map(ToString::to_string));
145
146     // Invoke compiler, and handle return code.
147     let result = rustc_driver::catch_fatal_errors(move || {
148         rustc_driver::run_compiler(&args, callbacks, None, None)
149     })
150     .and_then(|result| result);
151     let exit_code = match result {
152         Ok(()) => rustc_driver::EXIT_SUCCESS,
153         Err(_) => rustc_driver::EXIT_FAILURE,
154     };
155     std::process::exit(exit_code)
156 }
157
158 fn main() {
159     rustc_driver::install_ice_hook();
160
161     // If the environment asks us to actually be rustc, then do that.
162     if env::var_os("MIRI_BE_RUSTC").is_some() {
163         rustc_driver::init_rustc_env_logger();
164         // We cannot use `rustc_driver::main` as we need to adjust the CLI arguments.
165         let mut callbacks = rustc_driver::TimePassesCallbacks::default();
166         run_compiler(env::args().collect(), &mut callbacks)
167     }
168
169     // Init loggers the Miri way.
170     init_early_loggers();
171
172     // Parse our arguments and split them across `rustc` and `miri`.
173     let mut validate = true;
174     let mut stacked_borrows = true;
175     let mut check_alignment = true;
176     let mut communicate = false;
177     let mut ignore_leaks = false;
178     let mut seed: Option<u64> = None;
179     let mut tracked_pointer_tag: Option<miri::PtrId> = None;
180     let mut tracked_alloc_id: Option<miri::AllocId> = None;
181     let mut rustc_args = vec![];
182     let mut crate_args = vec![];
183     let mut after_dashdash = false;
184     let mut excluded_env_vars = vec![];
185     for arg in env::args() {
186         if rustc_args.is_empty() {
187             // Very first arg: binary name.
188             rustc_args.push(arg);
189         } else if after_dashdash {
190             // Everything that comes after `--` is forwarded to the interpreted crate.
191             crate_args.push(arg);
192         } else {
193             match arg.as_str() {
194                 "-Zmiri-disable-validation" => {
195                     validate = false;
196                 }
197                 "-Zmiri-disable-stacked-borrows" => {
198                     stacked_borrows = false;
199                 }
200                 "-Zmiri-disable-alignment-check" => {
201                     check_alignment = false;
202                 }
203                 "-Zmiri-disable-isolation" => {
204                     communicate = true;
205                 }
206                 "-Zmiri-ignore-leaks" => {
207                     ignore_leaks = true;
208                 }
209                 "--" => {
210                     after_dashdash = true;
211                 }
212                 arg if arg.starts_with("-Zmiri-seed=") => {
213                     if seed.is_some() {
214                         panic!("Cannot specify -Zmiri-seed multiple times!");
215                     }
216                     let seed_raw = hex::decode(arg.trim_start_matches("-Zmiri-seed="))
217                         .unwrap_or_else(|err| match err {
218                             FromHexError::InvalidHexCharacter { .. } => panic!(
219                                 "-Zmiri-seed should only contain valid hex digits [0-9a-fA-F]"
220                             ),
221                             FromHexError::OddLength =>
222                                 panic!("-Zmiri-seed should have an even number of digits"),
223                             err => panic!("Unknown error decoding -Zmiri-seed as hex: {:?}", err),
224                         });
225                     if seed_raw.len() > 8 {
226                         panic!(format!(
227                             "-Zmiri-seed must be at most 8 bytes, was {}",
228                             seed_raw.len()
229                         ));
230                     }
231
232                     let mut bytes = [0; 8];
233                     bytes[..seed_raw.len()].copy_from_slice(&seed_raw);
234                     seed = Some(u64::from_be_bytes(bytes));
235                 }
236                 arg if arg.starts_with("-Zmiri-env-exclude=") => {
237                     excluded_env_vars
238                         .push(arg.trim_start_matches("-Zmiri-env-exclude=").to_owned());
239                 }
240                 arg if arg.starts_with("-Zmiri-track-pointer-tag=") => {
241                     let id: u64 = match arg.trim_start_matches("-Zmiri-track-pointer-tag=").parse()
242                     {
243                         Ok(id) => id,
244                         Err(err) => panic!(
245                             "-Zmiri-track-pointer-tag requires a valid `u64` as the argument: {}",
246                             err
247                         ),
248                     };
249                     if let Some(id) = miri::PtrId::new(id) {
250                         tracked_pointer_tag = Some(id);
251                     } else {
252                         panic!("-Zmiri-track-pointer-tag must be a nonzero id");
253                     }
254                 }
255                 arg if arg.starts_with("-Zmiri-track-alloc-id=") => {
256                     let id: u64 = match arg.trim_start_matches("-Zmiri-track-alloc-id=").parse()
257                     {
258                         Ok(id) => id,
259                         Err(err) => panic!(
260                             "-Zmiri-track-alloc-id requires a valid `u64` as the argument: {}",
261                             err
262                         ),
263                     };
264                     tracked_alloc_id = Some(miri::AllocId(id));
265                 }
266                 _ => {
267                     // Forward to rustc.
268                     rustc_args.push(arg);
269                 }
270             }
271         }
272     }
273
274     debug!("rustc arguments: {:?}", rustc_args);
275     debug!("crate arguments: {:?}", crate_args);
276     let miri_config = miri::MiriConfig {
277         validate,
278         stacked_borrows,
279         check_alignment,
280         communicate,
281         ignore_leaks,
282         excluded_env_vars,
283         seed,
284         args: crate_args,
285         tracked_pointer_tag,
286         tracked_alloc_id,
287     };
288     run_compiler(rustc_args, &mut MiriCompilerCalls { miri_config })
289 }