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