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