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