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