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