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