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