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