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