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