]> git.lizzy.rs Git - rust.git/blob - src/eval.rs
Use names that actually represent what's going on
[rust.git] / src / eval.rs
1 //! Main evaluator loop and setting up the initial stack frame.
2
3 use std::ffi::OsStr;
4
5 use rand::rngs::StdRng;
6 use rand::SeedableRng;
7
8 use rustc_hir::def_id::DefId;
9 use rustc::ty::layout::{LayoutOf, Size};
10 use rustc::ty::{self, TyCtxt};
11
12 use crate::*;
13
14 /// Configuration needed to spawn a Miri instance.
15 #[derive(Clone)]
16 pub struct MiriConfig {
17     /// Determine if validity checking and Stacked Borrows are enabled.
18     pub validate: bool,
19     /// Determines if communication with the host environment is enabled.
20     pub communicate: bool,
21     /// Determines if memory leaks should be ignored.
22     pub ignore_leaks: bool,
23     /// Environment variables that should always be isolated from the host.
24     pub excluded_env_vars: Vec<String>,
25     /// Command-line arguments passed to the interpreted program.
26     pub args: Vec<String>,
27     /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
28     pub seed: Option<u64>,
29     /// The stacked borrow id to report about
30     pub tracked_pointer_tag: Option<PtrId>,
31 }
32
33 /// Details of premature program termination.
34 pub enum TerminationInfo {
35     Exit(i64),
36     Abort,
37 }
38
39 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
40 /// the location where the return value of the `start` lang item will be
41 /// written to.
42 /// Public because this is also used by `priroda`.
43 pub fn create_ecx<'mir, 'tcx: 'mir>(
44     tcx: TyCtxt<'tcx>,
45     main_id: DefId,
46     config: MiriConfig,
47 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'tcx>>, MPlaceTy<'tcx, Tag>)> {
48     let mut ecx = InterpCx::new(
49         tcx.at(rustc_span::source_map::DUMMY_SP),
50         ty::ParamEnv::reveal_all(),
51         Evaluator::new(config.communicate),
52         MemoryExtra::new(
53             StdRng::seed_from_u64(config.seed.unwrap_or(0)),
54             config.validate,
55             config.tracked_pointer_tag,
56         ),
57     );
58     // Complete initialization.
59     EnvVars::init(&mut ecx, config.excluded_env_vars);
60
61     // Setup first stack-frame
62     let main_instance = ty::Instance::mono(tcx, main_id);
63     let main_mir = ecx.load_mir(main_instance.def, None)?;
64     if main_mir.arg_count != 0 {
65         bug!("main function must not take any arguments");
66     }
67
68     let start_id = tcx.lang_items().start_fn().unwrap();
69     let main_ret_ty = tcx.fn_sig(main_id).output();
70     let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
71     let start_instance = ty::Instance::resolve(
72         tcx,
73         ty::ParamEnv::reveal_all(),
74         start_id,
75         tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
76     )
77     .unwrap();
78
79     // First argument: pointer to `main()`.
80     let main_ptr = ecx.memory.create_fn_alloc(FnVal::Instance(main_instance));
81     // Second argument (argc): length of `config.args`.
82     let argc = Scalar::from_uint(config.args.len() as u128, ecx.pointer_size());
83     // Third argument (`argv`): created from `config.args`.
84     let argv = {
85         // Put each argument in memory, collect pointers.
86         let mut argvs = Vec::<Scalar<Tag>>::new();
87         for arg in config.args.iter() {
88             // Make space for `0` terminator.
89             let size = arg.len() as u64 + 1;
90             let arg_type = tcx.mk_array(tcx.types.u8, size);
91             let arg_place = ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Env.into());
92             ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
93             argvs.push(arg_place.ptr);
94         }
95         // Make an array with all these pointers, in the Miri memory.
96         let argvs_layout =
97             ecx.layout_of(tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), argvs.len() as u64))?;
98         let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Env.into());
99         for (idx, arg) in argvs.into_iter().enumerate() {
100             let place = ecx.mplace_field(argvs_place, idx as u64)?;
101             ecx.write_scalar(arg, place.into())?;
102         }
103         ecx.memory.mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
104         // A pointer to that place is the 3rd argument for main.
105         let argv = argvs_place.ptr;
106         // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
107         {
108             let argc_place =
109                 ecx.allocate(ecx.layout_of(tcx.types.isize)?, MiriMemoryKind::Env.into());
110             ecx.write_scalar(argc, argc_place.into())?;
111             ecx.machine.argc = Some(argc_place.ptr);
112
113             let argv_place = ecx.allocate(
114                 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
115                 MiriMemoryKind::Env.into(),
116             );
117             ecx.write_scalar(argv, argv_place.into())?;
118             ecx.machine.argv = Some(argv_place.ptr);
119         }
120         // Store command line as UTF-16 for Windows `GetCommandLineW`.
121         {
122             // Construct a command string with all the aguments.
123             let mut cmd = String::new();
124             for arg in config.args.iter() {
125                 if !cmd.is_empty() {
126                     cmd.push(' ');
127                 }
128                 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
129             }
130             // Don't forget `0` terminator.
131             cmd.push(std::char::from_u32(0).unwrap());
132
133             let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
134             let cmd_type = tcx.mk_array(tcx.types.u16, cmd_utf16.len() as u64);
135             let cmd_place = ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Env.into());
136             ecx.machine.cmd_line = Some(cmd_place.ptr);
137             // Store the UTF-16 string. We just allocated so we know the bounds are fine.
138             let char_size = Size::from_bytes(2);
139             for (idx, &c) in cmd_utf16.iter().enumerate() {
140                 let place = ecx.mplace_field(cmd_place, idx as u64)?;
141                 ecx.write_scalar(Scalar::from_uint(c, char_size), place.into())?;
142             }
143         }
144         argv
145     };
146
147     // Return place (in static memory so that it does not count as leak).
148     let ret_place = ecx.allocate(ecx.layout_of(tcx.types.isize)?, MiriMemoryKind::Env.into());
149     // Call start function.
150     ecx.call_function(
151         start_instance,
152         &[main_ptr.into(), argc.into(), argv.into()],
153         Some(ret_place.into()),
154         StackPopCleanup::None { cleanup: true },
155     )?;
156
157     // Set the last_error to 0
158     let errno_layout = ecx.layout_of(tcx.types.u32)?;
159     let errno_place = ecx.allocate(errno_layout, MiriMemoryKind::Env.into());
160     ecx.write_scalar(Scalar::from_u32(0), errno_place.into())?;
161     ecx.machine.last_error = Some(errno_place);
162
163     Ok((ecx, ret_place))
164 }
165
166 /// Evaluates the main function specified by `main_id`.
167 /// Returns `Some(return_code)` if program executed completed.
168 /// Returns `None` if an evaluation error occured.
169 pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) -> Option<i64> {
170     // FIXME: We always ignore leaks on some platforms where we do not
171     // correctly implement TLS destructors.
172     let target_os = tcx.sess.target.target.target_os.to_lowercase();
173     let ignore_leaks = config.ignore_leaks || target_os == "windows" || target_os == "macos";
174
175     let (mut ecx, ret_place) = match create_ecx(tcx, main_id, config) {
176         Ok(v) => v,
177         Err(mut err) => {
178             err.print_backtrace();
179             panic!("Miri initialziation error: {}", err.kind)
180         }
181     };
182
183     // Perform the main execution.
184     let res: InterpResult<'_, i64> = (|| {
185         while ecx.step()? {
186             ecx.process_diagnostics();
187         }
188         // Read the return code pointer *before* we run TLS destructors, to assert
189         // that it was written to by the time that `start` lang item returned.
190         let return_code = ecx.read_scalar(ret_place.into())?.not_undef()?.to_machine_isize(&ecx)?;
191         ecx.run_tls_dtors()?;
192         Ok(return_code)
193     })();
194
195     // Process the result.
196     match res {
197         Ok(return_code) => {
198             if !ignore_leaks {
199                 let leaks = ecx.memory.leak_report();
200                 if leaks != 0 {
201                     tcx.sess.err("the evaluated program leaked memory");
202                     // Ignore the provided return code - let the reported error
203                     // determine the return code.
204                     return None;
205                 }
206             }
207             Some(return_code)
208         }
209         Err(e) => report_err(&ecx, e),
210     }
211 }