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