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