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