]> git.lizzy.rs Git - rust.git/blob - src/eval.rs
adjust for rustc changes; normalize mplace before doing freeze-sensitive visit
[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     // FIXME: extract main source file path.
112     // Third argument (`argv`): created from `config.args`.
113     let dest = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
114     // For Windows, construct a command string with all the aguments.
115     let mut cmd = String::new();
116     for arg in config.args.iter() {
117         if !cmd.is_empty() {
118             cmd.push(' ');
119         }
120         cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
121     }
122     // Don't forget `0` terminator.
123     cmd.push(std::char::from_u32(0).unwrap());
124     // Collect the pointers to the individual strings.
125     let mut argvs = Vec::<Pointer<Tag>>::new();
126     for arg in config.args {
127         // Add `0` terminator.
128         let mut arg = arg.into_bytes();
129         arg.push(0);
130         argvs.push(ecx.memory_mut().allocate_static_bytes(arg.as_slice(), MiriMemoryKind::Static.into()));
131     }
132     // Make an array with all these pointers, in the Miri memory.
133     let argvs_layout = ecx.layout_of(ecx.tcx.mk_array(ecx.tcx.mk_imm_ptr(ecx.tcx.types.u8), argvs.len() as u64))?;
134     let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Env.into());
135     for (idx, arg) in argvs.into_iter().enumerate() {
136         let place = ecx.mplace_field(argvs_place, idx as u64)?;
137         ecx.write_scalar(Scalar::Ptr(arg), place.into())?;
138     }
139     ecx.memory_mut().mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
140     // Write a pointer to that place as the argument.
141     let argv = argvs_place.ptr;
142     ecx.write_scalar(argv, dest)?;
143     // Store `argv` for macOS `_NSGetArgv`.
144     {
145         let argv_place = ecx.allocate(dest.layout, MiriMemoryKind::Env.into());
146         ecx.write_scalar(argv, argv_place.into())?;
147         ecx.machine.argv = Some(argv_place.ptr.to_ptr()?);
148     }
149     // Store command line as UTF-16 for Windows `GetCommandLineW`.
150     {
151         let tcx = &{ecx.tcx.tcx};
152         let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
153         let cmd_ptr = ecx.memory_mut().allocate(
154             Size::from_bytes(cmd_utf16.len() as u64 * 2),
155             Align::from_bytes(2).unwrap(),
156             MiriMemoryKind::Env.into(),
157         );
158         ecx.machine.cmd_line = Some(cmd_ptr);
159         // Store the UTF-16 string.
160         let char_size = Size::from_bytes(2);
161         let cmd_alloc = ecx.memory_mut().get_mut(cmd_ptr.alloc_id)?;
162         let mut cur_ptr = cmd_ptr;
163         for &c in cmd_utf16.iter() {
164             cmd_alloc.write_scalar(
165                 tcx,
166                 cur_ptr,
167                 Scalar::from_uint(c, char_size).into(),
168                 char_size,
169             )?;
170             cur_ptr = cur_ptr.offset(char_size, tcx)?;
171         }
172     }
173  
174     assert!(args.next().is_none(), "start lang item has more arguments than expected");
175
176     Ok(ecx)
177 }
178
179 pub fn eval_main<'tcx>(
180     tcx: TyCtxt<'tcx>,
181     main_id: DefId,
182     config: MiriConfig,
183 ) {
184     let mut ecx = match create_ecx(tcx, main_id, config) {
185         Ok(ecx) => ecx,
186         Err(mut err) => {
187             err.print_backtrace();
188             panic!("Miri initialziation error: {}", err.kind)
189         }
190     };
191
192     // Perform the main execution.
193     let res: InterpResult = (|| {
194         ecx.run()?;
195         ecx.run_tls_dtors()
196     })();
197
198     // Process the result.
199     match res {
200         Ok(()) => {
201             let leaks = ecx.memory().leak_report();
202             // Disable the leak test on some platforms where we do not
203             // correctly implement TLS destructors.
204             let target_os = ecx.tcx.tcx.sess.target.target.target_os.to_lowercase();
205             let ignore_leaks = target_os == "windows" || target_os == "macos";
206             if !ignore_leaks && leaks != 0 {
207                 tcx.sess.err("the evaluated program leaked memory");
208             }
209         }
210         Err(mut e) => {
211             // Special treatment for some error kinds
212             let msg = match e.kind {
213                 InterpError::Exit(code) => std::process::exit(code),
214                 InterpError::NoMirFor(..) =>
215                     format!("{}. Did you set `MIRI_SYSROOT` to a Miri-enabled sysroot? You can prepare one with `cargo miri setup`.", e),
216                 _ => e.to_string()
217             };
218             e.print_backtrace();
219             if let Some(frame) = ecx.stack().last() {
220                 let block = &frame.body.basic_blocks()[frame.block];
221                 let span = if frame.stmt < block.statements.len() {
222                     block.statements[frame.stmt].source_info.span
223                 } else {
224                     block.terminator().source_info.span
225                 };
226
227                 let msg = format!("Miri evaluation error: {}", msg);
228                 let mut err = struct_error(ecx.tcx.tcx.at(span), msg.as_str());
229                 let frames = ecx.generate_stacktrace(None);
230                 err.span_label(span, msg);
231                 // We iterate with indices because we need to look at the next frame (the caller).
232                 for idx in 0..frames.len() {
233                     let frame_info = &frames[idx];
234                     let call_site_is_local = frames.get(idx+1).map_or(false,
235                         |caller_info| caller_info.instance.def_id().is_local());
236                     if call_site_is_local {
237                         err.span_note(frame_info.call_site, &frame_info.to_string());
238                     } else {
239                         err.note(&frame_info.to_string());
240                     }
241                 }
242                 err.emit();
243             } else {
244                 ecx.tcx.sess.err(&msg);
245             }
246
247             for (i, frame) in ecx.stack().iter().enumerate() {
248                 trace!("-------------------");
249                 trace!("Frame {}", i);
250                 trace!("    return: {:?}", frame.return_place.map(|p| *p));
251                 for (i, local) in frame.locals.iter().enumerate() {
252                     trace!("    local {}: {:?}", i, local.value);
253                 }
254             }
255         }
256     }
257 }