]> git.lizzy.rs Git - rust.git/blob - src/eval.rs
Tidy up comments and function layout, should fix most of the review notes.
[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 }
54
55 impl Default for MiriConfig {
56     fn default() -> MiriConfig {
57         MiriConfig {
58             validate: true,
59             stacked_borrows: true,
60             check_alignment: AlignmentCheck::Int,
61             communicate: false,
62             ignore_leaks: false,
63             excluded_env_vars: vec![],
64             args: vec![],
65             seed: None,
66             tracked_pointer_tag: None,
67             tracked_call_id: None,
68             tracked_alloc_id: None,
69             track_raw: false,
70             data_race_detector: true,
71         }
72     }
73 }
74
75 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
76 /// the location where the return value of the `start` lang item will be
77 /// written to.
78 /// Public because this is also used by `priroda`.
79 pub fn create_ecx<'mir, 'tcx: 'mir>(
80     tcx: TyCtxt<'tcx>,
81     main_id: DefId,
82     config: MiriConfig,
83 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>, MPlaceTy<'tcx, Tag>)> {
84     let param_env = ty::ParamEnv::reveal_all();
85     let layout_cx = LayoutCx { tcx, param_env };
86     let mut ecx = InterpCx::new(
87         tcx,
88         rustc_span::source_map::DUMMY_SP,
89         param_env,
90         Evaluator::new(config.communicate, config.validate, layout_cx),
91         MemoryExtra::new(&config),
92     );
93     // Complete initialization.
94     EnvVars::init(&mut ecx, config.excluded_env_vars)?;
95     MemoryExtra::init_extern_statics(&mut ecx)?;
96
97     // Setup first stack-frame
98     let main_instance = ty::Instance::mono(tcx, main_id);
99     let main_mir = ecx.load_mir(main_instance.def, None)?;
100     if main_mir.arg_count != 0 {
101         bug!("main function must not take any arguments");
102     }
103
104     let start_id = tcx.lang_items().start_fn().unwrap();
105     let main_ret_ty = tcx.fn_sig(main_id).output();
106     let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
107     let start_instance = ty::Instance::resolve(
108         tcx,
109         ty::ParamEnv::reveal_all(),
110         start_id,
111         tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
112     )
113     .unwrap()
114     .unwrap();
115
116     // First argument: pointer to `main()`.
117     let main_ptr = ecx.memory.create_fn_alloc(FnVal::Instance(main_instance));
118     // Second argument (argc): length of `config.args`.
119     let argc = Scalar::from_machine_usize(u64::try_from(config.args.len()).unwrap(), &ecx);
120     // Third argument (`argv`): created from `config.args`.
121     let argv = {
122         // Put each argument in memory, collect pointers.
123         let mut argvs = Vec::<Scalar<Tag>>::new();
124         for arg in config.args.iter() {
125             // Make space for `0` terminator.
126             let size = u64::try_from(arg.len()).unwrap().checked_add(1).unwrap();
127             let arg_type = tcx.mk_array(tcx.types.u8, size);
128             let arg_place = ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into());
129             ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
130             argvs.push(arg_place.ptr);
131         }
132         // Make an array with all these pointers, in the Miri memory.
133         let argvs_layout =
134             ecx.layout_of(tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), u64::try_from(argvs.len()).unwrap()))?;
135         let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into());
136         for (idx, arg) in argvs.into_iter().enumerate() {
137             let place = ecx.mplace_field(argvs_place, idx)?;
138             ecx.write_scalar(arg, place.into())?;
139         }
140         ecx.memory.mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
141         // A pointer to that place is the 3rd argument for main.
142         let argv = argvs_place.ptr;
143         // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
144         {
145             let argc_place =
146                 ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into());
147             ecx.write_scalar(argc, argc_place.into())?;
148             ecx.machine.argc = Some(argc_place.ptr);
149
150             let argv_place = ecx.allocate(
151                 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
152                 MiriMemoryKind::Machine.into(),
153             );
154             ecx.write_scalar(argv, argv_place.into())?;
155             ecx.machine.argv = Some(argv_place.ptr);
156         }
157         // Store command line as UTF-16 for Windows `GetCommandLineW`.
158         {
159             // Construct a command string with all the aguments.
160             let mut cmd = String::new();
161             for arg in config.args.iter() {
162                 if !cmd.is_empty() {
163                     cmd.push(' ');
164                 }
165                 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
166             }
167             // Don't forget `0` terminator.
168             cmd.push(std::char::from_u32(0).unwrap());
169
170             let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
171             let cmd_type = tcx.mk_array(tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
172             let cmd_place = ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into());
173             ecx.machine.cmd_line = Some(cmd_place.ptr);
174             // Store the UTF-16 string. We just allocated so we know the bounds are fine.
175             for (idx, &c) in cmd_utf16.iter().enumerate() {
176                 let place = ecx.mplace_field(cmd_place, idx)?;
177                 ecx.write_scalar(Scalar::from_u16(c), place.into())?;
178             }
179         }
180         argv
181     };
182
183     // Return place (in static memory so that it does not count as leak).
184     let ret_place = ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into());
185     // Call start function.
186     ecx.call_function(
187         start_instance,
188         &[main_ptr.into(), argc.into(), argv.into()],
189         Some(ret_place.into()),
190         StackPopCleanup::None { cleanup: true },
191     )?;
192
193     Ok((ecx, ret_place))
194 }
195
196 /// Evaluates the main function specified by `main_id`.
197 /// Returns `Some(return_code)` if program executed completed.
198 /// Returns `None` if an evaluation error occured.
199 pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) -> Option<i64> {
200     // Copy setting before we move `config`.
201     let ignore_leaks = config.ignore_leaks;
202
203     let (mut ecx, ret_place) = match create_ecx(tcx, main_id, config) {
204         Ok(v) => v,
205         Err(err) => {
206             err.print_backtrace();
207             panic!("Miri initialization error: {}", err.kind)
208         }
209     };
210
211     // Perform the main execution.
212     let res: InterpResult<'_, i64> = (|| {
213         // Main loop.
214         loop {
215             let info = ecx.preprocess_diagnostics();
216             match ecx.schedule()? {
217                 SchedulingAction::ExecuteStep => {
218                     assert!(ecx.step()?, "a terminated thread was scheduled for execution");
219                 }
220                 SchedulingAction::ExecuteTimeoutCallback => {
221                     assert!(ecx.machine.communicate,
222                         "scheduler callbacks require disabled isolation, but the code \
223                         that created the callback did not check it");
224                     ecx.run_timeout_callback()?;
225                 }
226                 SchedulingAction::ExecuteDtors => {
227                     // This will either enable the thread again (so we go back
228                     // to `ExecuteStep`), or determine that this thread is done
229                     // for good.
230                     ecx.schedule_next_tls_dtor_for_active_thread()?;
231                 }
232                 SchedulingAction::Stop => {
233                     break;
234                 }
235             }
236             ecx.process_diagnostics(info);
237         }
238         let return_code = ecx.read_scalar(ret_place.into())?.check_init()?.to_machine_isize(&ecx)?;
239         Ok(return_code)
240     })();
241
242     // Machine cleanup.
243     EnvVars::cleanup(&mut ecx).unwrap();
244
245     // Process the result.
246     match res {
247         Ok(return_code) => {
248             if !ignore_leaks {
249                 info!("Additonal static roots: {:?}", ecx.machine.static_roots);
250                 let leaks = ecx.memory.leak_report(&ecx.machine.static_roots);
251                 if leaks != 0 {
252                     tcx.sess.err("the evaluated program leaked memory");
253                     // Ignore the provided return code - let the reported error
254                     // determine the return code.
255                     return None;
256                 }
257             }
258             Some(return_code)
259         }
260         Err(e) => report_error(&ecx, e),
261     }
262 }