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