]> git.lizzy.rs Git - rust.git/blob - src/eval.rs
6646783d349cae3358cba1b66c2c84dada45c163
[rust.git] / src / eval.rs
1 //! Main evaluator loop and setting up the initial stack frame.
2
3 use std::convert::TryFrom;
4 use std::ffi::OsStr;
5
6 use log::info;
7
8 use rustc_hir::def_id::DefId;
9 use rustc_middle::ty::{self, layout::LayoutCx, TyCtxt};
10 use rustc_target::abi::LayoutOf;
11 use rustc_target::spec::abi::Abi;
12
13 use crate::*;
14
15 #[derive(Copy, Clone, Debug, PartialEq)]
16 pub enum AlignmentCheck {
17     /// Do not check alignment.
18     None,
19     /// Check alignment "symbolically", i.e., using only the requested alignment for an allocation and not its real base address.
20     Symbolic,
21     /// Check alignment on the actual physical integer address.
22     Int,
23 }
24
25 /// Configuration needed to spawn a Miri instance.
26 #[derive(Clone)]
27 pub struct MiriConfig {
28     /// Determine if validity checking is enabled.
29     pub validate: bool,
30     /// Determines if Stacked Borrows is enabled.
31     pub stacked_borrows: bool,
32     /// Controls alignment checking.
33     pub check_alignment: AlignmentCheck,
34     /// Controls function [ABI](Abi) checking.
35     pub check_abi: bool,
36     /// Determines if communication with the host environment is enabled.
37     pub communicate: bool,
38     /// Determines if memory leaks should be ignored.
39     pub ignore_leaks: bool,
40     /// Environment variables that should always be isolated from the host.
41     pub excluded_env_vars: Vec<String>,
42     /// Command-line arguments passed to the interpreted program.
43     pub args: Vec<String>,
44     /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
45     pub seed: Option<u64>,
46     /// The stacked borrows pointer id to report about
47     pub tracked_pointer_tag: Option<PtrId>,
48     /// The stacked borrows call ID to report about
49     pub tracked_call_id: Option<CallId>,
50     /// The allocation id to report about.
51     pub tracked_alloc_id: Option<AllocId>,
52     /// Whether to track raw pointers in stacked borrows.
53     pub track_raw: bool,
54     /// Determine if data race detection should be enabled
55     pub data_race_detector: bool,
56     /// Rate of spurious failures for compare_exchange_weak atomic operations,
57     /// between 0.0 and 1.0, defaulting to 0.8 (80% chance of failure).
58     pub cmpxchg_weak_failure_rate: f64,
59     /// If `Some`, enable the `measureme` profiler, writing results to a file
60     /// with the specified prefix.
61     pub measureme_out: Option<String>,
62 }
63
64 impl Default for MiriConfig {
65     fn default() -> MiriConfig {
66         MiriConfig {
67             validate: true,
68             stacked_borrows: true,
69             check_alignment: AlignmentCheck::Int,
70             check_abi: true,
71             communicate: false,
72             ignore_leaks: false,
73             excluded_env_vars: vec![],
74             args: vec![],
75             seed: None,
76             tracked_pointer_tag: None,
77             tracked_call_id: None,
78             tracked_alloc_id: None,
79             track_raw: false,
80             data_race_detector: true,
81             cmpxchg_weak_failure_rate: 0.8,
82             measureme_out: None,
83         }
84     }
85 }
86
87 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
88 /// the location where the return value of the `start` lang item will be
89 /// written to.
90 /// Public because this is also used by `priroda`.
91 pub fn create_ecx<'mir, 'tcx: 'mir>(
92     tcx: TyCtxt<'tcx>,
93     main_id: DefId,
94     config: MiriConfig,
95 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>, MPlaceTy<'tcx, Tag>)> {
96     let param_env = ty::ParamEnv::reveal_all();
97     let layout_cx = LayoutCx { tcx, param_env };
98     let mut ecx = InterpCx::new(
99         tcx,
100         rustc_span::source_map::DUMMY_SP,
101         param_env,
102         Evaluator::new(&config, layout_cx),
103         MemoryExtra::new(&config),
104     );
105     // Complete initialization.
106     EnvVars::init(&mut ecx, config.excluded_env_vars)?;
107     MemoryExtra::init_extern_statics(&mut ecx)?;
108
109     // Setup first stack-frame
110     let main_instance = ty::Instance::mono(tcx, main_id);
111     let main_mir = ecx.load_mir(main_instance.def, None)?;
112     if main_mir.arg_count != 0 {
113         bug!("main function must not take any arguments");
114     }
115
116     let start_id = tcx.lang_items().start_fn().unwrap();
117     let main_ret_ty = tcx.fn_sig(main_id).output();
118     let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
119     let start_instance = ty::Instance::resolve(
120         tcx,
121         ty::ParamEnv::reveal_all(),
122         start_id,
123         tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
124     )
125     .unwrap()
126     .unwrap();
127
128     // First argument: pointer to `main()`.
129     let main_ptr = ecx.memory.create_fn_alloc(FnVal::Instance(main_instance));
130     // Second argument (argc): length of `config.args`.
131     let argc = Scalar::from_machine_usize(u64::try_from(config.args.len()).unwrap(), &ecx);
132     // Third argument (`argv`): created from `config.args`.
133     let argv = {
134         // Put each argument in memory, collect pointers.
135         let mut argvs = Vec::<Scalar<Tag>>::new();
136         for arg in config.args.iter() {
137             // Make space for `0` terminator.
138             let size = u64::try_from(arg.len()).unwrap().checked_add(1).unwrap();
139             let arg_type = tcx.mk_array(tcx.types.u8, size);
140             let arg_place = ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into());
141             ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
142             argvs.push(arg_place.ptr);
143         }
144         // Make an array with all these pointers, in the Miri memory.
145         let argvs_layout = ecx.layout_of(
146             tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), u64::try_from(argvs.len()).unwrap()),
147         )?;
148         let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into());
149         for (idx, arg) in argvs.into_iter().enumerate() {
150             let place = ecx.mplace_field(&argvs_place, idx)?;
151             ecx.write_scalar(arg, &place.into())?;
152         }
153         ecx.memory.mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
154         // A pointer to that place is the 3rd argument for main.
155         let argv = argvs_place.ptr;
156         // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
157         {
158             let argc_place =
159                 ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into());
160             ecx.write_scalar(argc, &argc_place.into())?;
161             ecx.machine.argc = Some(argc_place.ptr);
162
163             let argv_place = ecx.allocate(
164                 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
165                 MiriMemoryKind::Machine.into(),
166             );
167             ecx.write_scalar(argv, &argv_place.into())?;
168             ecx.machine.argv = Some(argv_place.ptr);
169         }
170         // Store command line as UTF-16 for Windows `GetCommandLineW`.
171         {
172             // Construct a command string with all the aguments.
173             let mut cmd = String::new();
174             for arg in config.args.iter() {
175                 if !cmd.is_empty() {
176                     cmd.push(' ');
177                 }
178                 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
179             }
180             // Don't forget `0` terminator.
181             cmd.push(std::char::from_u32(0).unwrap());
182
183             let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
184             let cmd_type = tcx.mk_array(tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
185             let cmd_place = ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into());
186             ecx.machine.cmd_line = Some(cmd_place.ptr);
187             // Store the UTF-16 string. We just allocated so we know the bounds are fine.
188             for (idx, &c) in cmd_utf16.iter().enumerate() {
189                 let place = ecx.mplace_field(&cmd_place, idx)?;
190                 ecx.write_scalar(Scalar::from_u16(c), &place.into())?;
191             }
192         }
193         argv
194     };
195
196     // Return place (in static memory so that it does not count as leak).
197     let ret_place = ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into());
198     // Call start function.
199     ecx.call_function(
200         start_instance,
201         Abi::Rust,
202         &[main_ptr.into(), argc.into(), argv.into()],
203         Some(&ret_place.into()),
204         StackPopCleanup::None { cleanup: true },
205     )?;
206
207     Ok((ecx, ret_place))
208 }
209
210 /// Evaluates the main function specified by `main_id`.
211 /// Returns `Some(return_code)` if program executed completed.
212 /// Returns `None` if an evaluation error occured.
213 pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) -> Option<i64> {
214     // Copy setting before we move `config`.
215     let ignore_leaks = config.ignore_leaks;
216
217     let (mut ecx, ret_place) = match create_ecx(tcx, main_id, config) {
218         Ok(v) => v,
219         Err(err) => {
220             err.print_backtrace();
221             panic!("Miri initialization error: {}", err.kind())
222         }
223     };
224
225     // Perform the main execution.
226     let res: InterpResult<'_, i64> = (|| {
227         // Main loop.
228         loop {
229             let info = ecx.preprocess_diagnostics();
230             match ecx.schedule()? {
231                 SchedulingAction::ExecuteStep => {
232                     assert!(ecx.step()?, "a terminated thread was scheduled for execution");
233                 }
234                 SchedulingAction::ExecuteTimeoutCallback => {
235                     assert!(
236                         ecx.machine.communicate,
237                         "scheduler callbacks require disabled isolation, but the code \
238                         that created the callback did not check it"
239                     );
240                     ecx.run_timeout_callback()?;
241                 }
242                 SchedulingAction::ExecuteDtors => {
243                     // This will either enable the thread again (so we go back
244                     // to `ExecuteStep`), or determine that this thread is done
245                     // for good.
246                     ecx.schedule_next_tls_dtor_for_active_thread()?;
247                 }
248                 SchedulingAction::Stop => {
249                     break;
250                 }
251             }
252             ecx.process_diagnostics(info);
253         }
254         let return_code =
255             ecx.read_scalar(&ret_place.into())?.check_init()?.to_machine_isize(&ecx)?;
256         Ok(return_code)
257     })();
258
259     // Machine cleanup.
260     EnvVars::cleanup(&mut ecx).unwrap();
261
262     // Process the result.
263     match res {
264         Ok(return_code) => {
265             if !ignore_leaks {
266                 info!("Additonal static roots: {:?}", ecx.machine.static_roots);
267                 let leaks = ecx.memory.leak_report(&ecx.machine.static_roots);
268                 if leaks != 0 {
269                     tcx.sess.err("the evaluated program leaked memory");
270                     // Ignore the provided return code - let the reported error
271                     // determine the return code.
272                     return None;
273                 }
274             }
275             Some(return_code)
276         }
277         Err(e) => report_error(&ecx, e),
278     }
279 }