]> git.lizzy.rs Git - rust.git/blob - src/eval.rs
Add -Zmiri-env-exclude flag
[rust.git] / src / eval.rs
1 //! Main evaluator loop and setting up the initial stack frame.
2
3 use rand::rngs::StdRng;
4 use rand::SeedableRng;
5
6 use syntax::source_map::DUMMY_SP;
7 use rustc::ty::{self, TyCtxt};
8 use rustc::ty::layout::{LayoutOf, Size, Align};
9 use rustc::hir::def_id::DefId;
10
11 use crate::{
12     InterpResult, InterpError, InterpCx, StackPopCleanup, struct_error,
13     Scalar, Tag, Pointer, FnVal,
14     MemoryExtra, MiriMemoryKind, Evaluator, TlsEvalContextExt, HelpersEvalContextExt,
15     EnvVars,
16 };
17
18 /// Configuration needed to spawn a Miri instance.
19 #[derive(Clone)]
20 pub struct MiriConfig {
21     /// Determine if validity checking and Stacked Borrows are enabled.
22     pub validate: bool,
23     /// Determines if communication with the host environment is enabled.
24     pub communicate: bool,
25     /// Environment variables that should always be isolated from the host.
26     pub excluded_env_vars: Vec<String>,
27     pub args: Vec<String>,
28     /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
29     pub seed: Option<u64>,
30 }
31
32 // Used by priroda.
33 pub fn create_ecx<'mir, 'tcx: 'mir>(
34     tcx: TyCtxt<'tcx>,
35     main_id: DefId,
36     config: MiriConfig,
37 ) -> InterpResult<'tcx, InterpCx<'mir, 'tcx, Evaluator<'tcx>>> {
38     let mut ecx = InterpCx::new(
39         tcx.at(syntax::source_map::DUMMY_SP),
40         ty::ParamEnv::reveal_all(),
41         Evaluator::new(config.communicate),
42         MemoryExtra::new(StdRng::seed_from_u64(config.seed.unwrap_or(0)), config.validate),
43     );
44     // Complete initialization.
45     EnvVars::init(&mut ecx);
46
47     // Setup first stack-frame
48     let main_instance = ty::Instance::mono(ecx.tcx.tcx, main_id);
49     let main_mir = ecx.load_mir(main_instance.def, None)?;
50
51     if !main_mir.return_ty().is_unit() || main_mir.arg_count != 0 {
52         throw_unsup_format!(
53             "miri does not support main functions without `fn()` type signatures"
54         );
55     }
56
57     let start_id = tcx.lang_items().start_fn().unwrap();
58     let main_ret_ty = tcx.fn_sig(main_id).output();
59     let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
60     let start_instance = ty::Instance::resolve(
61         ecx.tcx.tcx,
62         ty::ParamEnv::reveal_all(),
63         start_id,
64         ecx.tcx.mk_substs(
65             ::std::iter::once(ty::subst::Kind::from(main_ret_ty)))
66         ).unwrap();
67     let start_mir = ecx.load_mir(start_instance.def, None)?;
68
69     if start_mir.arg_count != 3 {
70         bug!(
71             "'start' lang item should have three arguments, but has {}",
72             start_mir.arg_count
73         );
74     }
75
76     // Return value (in static memory so that it does not count as leak).
77     let ret = ecx.layout_of(start_mir.return_ty())?;
78     let ret_ptr = ecx.allocate(ret, MiriMemoryKind::Static.into());
79
80     // Push our stack frame.
81     ecx.push_stack_frame(
82         start_instance,
83         // There is no call site.
84         DUMMY_SP,
85         start_mir,
86         Some(ret_ptr.into()),
87         StackPopCleanup::None { cleanup: true },
88     )?;
89
90     let mut args = ecx.frame().body.args_iter();
91
92     // First argument: pointer to `main()`.
93     let main_ptr = ecx.memory_mut().create_fn_alloc(FnVal::Instance(main_instance));
94     let dest = ecx.local_place(args.next().unwrap())?;
95     ecx.write_scalar(Scalar::Ptr(main_ptr), dest)?;
96
97     // Second argument (argc): `1`.
98     let dest = ecx.local_place(args.next().unwrap())?;
99     let argc = Scalar::from_uint(config.args.len() as u128, dest.layout.size);
100     ecx.write_scalar(argc, dest)?;
101     // Store argc for macOS's `_NSGetArgc`.
102     {
103         let argc_place = ecx.allocate(dest.layout, MiriMemoryKind::Env.into());
104         ecx.write_scalar(argc, argc_place.into())?;
105         ecx.machine.argc = Some(argc_place.ptr.to_ptr()?);
106     }
107
108     // Third argument (`argv`): created from `config.args`.
109     let dest = ecx.local_place(args.next().unwrap())?;
110     // For Windows, construct a command string with all the aguments.
111     let mut cmd = String::new();
112     for arg in config.args.iter() {
113         if !cmd.is_empty() {
114             cmd.push(' ');
115         }
116         cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
117     }
118     // Don't forget `0` terminator.
119     cmd.push(std::char::from_u32(0).unwrap());
120     // Collect the pointers to the individual strings.
121     let mut argvs = Vec::<Pointer<Tag>>::new();
122     for arg in config.args {
123         // Add `0` terminator.
124         let mut arg = arg.into_bytes();
125         arg.push(0);
126         argvs.push(ecx.memory_mut().allocate_static_bytes(arg.as_slice(), MiriMemoryKind::Static.into()));
127     }
128     // Make an array with all these pointers, in the Miri memory.
129     let argvs_layout = ecx.layout_of(ecx.tcx.mk_array(ecx.tcx.mk_imm_ptr(ecx.tcx.types.u8), argvs.len() as u64))?;
130     let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Env.into());
131     for (idx, arg) in argvs.into_iter().enumerate() {
132         let place = ecx.mplace_field(argvs_place, idx as u64)?;
133         ecx.write_scalar(Scalar::Ptr(arg), place.into())?;
134     }
135     ecx.memory_mut().mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
136     // Write a pointer to that place as the argument.
137     let argv = argvs_place.ptr;
138     ecx.write_scalar(argv, dest)?;
139     // Store `argv` for macOS `_NSGetArgv`.
140     {
141         let argv_place = ecx.allocate(dest.layout, MiriMemoryKind::Env.into());
142         ecx.write_scalar(argv, argv_place.into())?;
143         ecx.machine.argv = Some(argv_place.ptr.to_ptr()?);
144     }
145     // Store command line as UTF-16 for Windows `GetCommandLineW`.
146     {
147         let tcx = &{ecx.tcx.tcx};
148         let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
149         let cmd_ptr = ecx.memory_mut().allocate(
150             Size::from_bytes(cmd_utf16.len() as u64 * 2),
151             Align::from_bytes(2).unwrap(),
152             MiriMemoryKind::Env.into(),
153         );
154         ecx.machine.cmd_line = Some(cmd_ptr);
155         // Store the UTF-16 string.
156         let char_size = Size::from_bytes(2);
157         let cmd_alloc = ecx.memory_mut().get_mut(cmd_ptr.alloc_id)?;
158         let mut cur_ptr = cmd_ptr;
159         for &c in cmd_utf16.iter() {
160             cmd_alloc.write_scalar(
161                 tcx,
162                 cur_ptr,
163                 Scalar::from_uint(c, char_size).into(),
164                 char_size,
165             )?;
166             cur_ptr = cur_ptr.offset(char_size, tcx)?;
167         }
168     }
169
170     assert!(args.next().is_none(), "start lang item has more arguments than expected");
171
172     Ok(ecx)
173 }
174
175 pub fn eval_main<'tcx>(
176     tcx: TyCtxt<'tcx>,
177     main_id: DefId,
178     config: MiriConfig,
179 ) {
180     let mut ecx = match create_ecx(tcx, main_id, config) {
181         Ok(ecx) => ecx,
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<'_> = (|| {
190         ecx.run()?;
191         ecx.run_tls_dtors()
192     })();
193
194     // Process the result.
195     match res {
196         Ok(()) => {
197             let leaks = ecx.memory().leak_report();
198             // Disable the leak test on some platforms where we do not
199             // correctly implement TLS destructors.
200             let target_os = ecx.tcx.tcx.sess.target.target.target_os.to_lowercase();
201             let ignore_leaks = target_os == "windows" || target_os == "macos";
202             if !ignore_leaks && leaks != 0 {
203                 tcx.sess.err("the evaluated program leaked memory");
204             }
205         }
206         Err(mut e) => {
207             // Special treatment for some error kinds
208             let msg = match e.kind {
209                 InterpError::Exit(code) => std::process::exit(code),
210                 err_unsup!(NoMirFor(..)) =>
211                     format!("{}. Did you set `MIRI_SYSROOT` to a Miri-enabled sysroot? You can prepare one with `cargo miri setup`.", e),
212                 _ => e.to_string()
213             };
214             e.print_backtrace();
215             if let Some(frame) = ecx.stack().last() {
216                 let block = &frame.body.basic_blocks()[frame.block];
217                 let span = if frame.stmt < block.statements.len() {
218                     block.statements[frame.stmt].source_info.span
219                 } else {
220                     block.terminator().source_info.span
221                 };
222
223                 let msg = format!("Miri evaluation error: {}", msg);
224                 let mut err = struct_error(ecx.tcx.tcx.at(span), msg.as_str());
225                 let frames = ecx.generate_stacktrace(None);
226                 err.span_label(span, msg);
227                 // We iterate with indices because we need to look at the next frame (the caller).
228                 for idx in 0..frames.len() {
229                     let frame_info = &frames[idx];
230                     let call_site_is_local = frames.get(idx+1).map_or(false,
231                         |caller_info| caller_info.instance.def_id().is_local());
232                     if call_site_is_local {
233                         err.span_note(frame_info.call_site, &frame_info.to_string());
234                     } else {
235                         err.note(&frame_info.to_string());
236                     }
237                 }
238                 err.emit();
239             } else {
240                 ecx.tcx.sess.err(&msg);
241             }
242
243             for (i, frame) in ecx.stack().iter().enumerate() {
244                 trace!("-------------------");
245                 trace!("Frame {}", i);
246                 trace!("    return: {:?}", frame.return_place.map(|p| *p));
247                 for (i, local) in frame.locals.iter().enumerate() {
248                     trace!("    local {}: {:?}", i, local.value);
249                 }
250             }
251         }
252     }
253 }