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