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