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