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