Skip to content

Commit 857305f

Browse files
committed
Merge remote-tracking branch 'ralf/machine' into rustup
2 parents 373a4ee + 67d3779 commit 857305f

File tree

11 files changed

+651
-637
lines changed

11 files changed

+651
-637
lines changed

miri

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ find_sysroot() {
8989

9090
# Determine command.
9191
COMMAND="$1"
92-
shift
92+
[ $# -gt 0 ] && shift
9393

9494
# Determine flags passed to all cargo invocations.
9595
# This is a bit more annoying that one would hope due to

src/eval.rs

Lines changed: 246 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,246 @@
1+
use rand::rngs::StdRng;
2+
use rand::SeedableRng;
3+
4+
use syntax::source_map::DUMMY_SP;
5+
use rustc::ty::{self, TyCtxt};
6+
use rustc::ty::layout::{LayoutOf, Size, Align};
7+
use rustc::hir::def_id::DefId;
8+
use rustc::mir;
9+
10+
use crate::{
11+
InterpResult, InterpError, InterpretCx, StackPopCleanup, struct_error,
12+
Scalar, Tag, Pointer,
13+
MemoryExtra, MiriMemoryKind, Evaluator, TlsEvalContextExt,
14+
};
15+
16+
/// Configuration needed to spawn a Miri instance.
17+
#[derive(Clone)]
18+
pub struct MiriConfig {
19+
pub validate: bool,
20+
pub args: Vec<String>,
21+
22+
// The seed to use when non-determinism is required (e.g. getrandom())
23+
pub seed: Option<u64>
24+
}
25+
26+
// Used by priroda.
27+
pub fn create_ecx<'mir, 'tcx: 'mir>(
28+
tcx: TyCtxt<'tcx>,
29+
main_id: DefId,
30+
config: MiriConfig,
31+
) -> InterpResult<'tcx, InterpretCx<'mir, 'tcx, Evaluator<'tcx>>> {
32+
let mut ecx = InterpretCx::new(
33+
tcx.at(syntax::source_map::DUMMY_SP),
34+
ty::ParamEnv::reveal_all(),
35+
Evaluator::new(config.validate),
36+
MemoryExtra::with_rng(config.seed.map(StdRng::seed_from_u64)),
37+
);
38+
39+
let main_instance = ty::Instance::mono(ecx.tcx.tcx, main_id);
40+
let main_mir = ecx.load_mir(main_instance.def)?;
41+
42+
if !main_mir.return_ty().is_unit() || main_mir.arg_count != 0 {
43+
return err!(Unimplemented(
44+
"miri does not support main functions without `fn()` type signatures"
45+
.to_owned(),
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+
return err!(AbiViolation(format!(
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(main_instance);
86+
let dest = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
87+
ecx.write_scalar(Scalar::Ptr(main_ptr), dest)?;
88+
89+
// Second argument (argc): `1`.
90+
let dest = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(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+
// FIXME: extract main source file path.
101+
// Third argument (`argv`): created from `config.args`.
102+
let dest = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
103+
// For Windows, construct a command string with all the aguments.
104+
let mut cmd = String::new();
105+
for arg in config.args.iter() {
106+
if !cmd.is_empty() {
107+
cmd.push(' ');
108+
}
109+
cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
110+
}
111+
// Don't forget `0` terminator.
112+
cmd.push(std::char::from_u32(0).unwrap());
113+
// Collect the pointers to the individual strings.
114+
let mut argvs = Vec::<Pointer<Tag>>::new();
115+
for arg in config.args {
116+
// Add `0` terminator.
117+
let mut arg = arg.into_bytes();
118+
arg.push(0);
119+
argvs.push(ecx.memory_mut().allocate_static_bytes(arg.as_slice(), MiriMemoryKind::Static.into()));
120+
}
121+
// Make an array with all these pointers, in the Miri memory.
122+
let argvs_layout = ecx.layout_of(ecx.tcx.mk_array(ecx.tcx.mk_imm_ptr(ecx.tcx.types.u8), argvs.len() as u64))?;
123+
let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Env.into());
124+
for (idx, arg) in argvs.into_iter().enumerate() {
125+
let place = ecx.mplace_field(argvs_place, idx as u64)?;
126+
ecx.write_scalar(Scalar::Ptr(arg), place.into())?;
127+
}
128+
ecx.memory_mut().mark_immutable(argvs_place.to_ptr()?.alloc_id)?;
129+
// Write a pointer to that place as the argument.
130+
let argv = argvs_place.ptr;
131+
ecx.write_scalar(argv, dest)?;
132+
// Store `argv` for macOS `_NSGetArgv`.
133+
{
134+
let argv_place = ecx.allocate(dest.layout, MiriMemoryKind::Env.into());
135+
ecx.write_scalar(argv, argv_place.into())?;
136+
ecx.machine.argv = Some(argv_place.ptr.to_ptr()?);
137+
}
138+
// Store command line as UTF-16 for Windows `GetCommandLineW`.
139+
{
140+
let tcx = &{ecx.tcx.tcx};
141+
let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
142+
let cmd_ptr = ecx.memory_mut().allocate(
143+
Size::from_bytes(cmd_utf16.len() as u64 * 2),
144+
Align::from_bytes(2).unwrap(),
145+
MiriMemoryKind::Env.into(),
146+
);
147+
ecx.machine.cmd_line = Some(cmd_ptr);
148+
// Store the UTF-16 string.
149+
let char_size = Size::from_bytes(2);
150+
let cmd_alloc = ecx.memory_mut().get_mut(cmd_ptr.alloc_id)?;
151+
let mut cur_ptr = cmd_ptr;
152+
for &c in cmd_utf16.iter() {
153+
cmd_alloc.write_scalar(
154+
tcx,
155+
cur_ptr,
156+
Scalar::from_uint(c, char_size).into(),
157+
char_size,
158+
)?;
159+
cur_ptr = cur_ptr.offset(char_size, tcx)?;
160+
}
161+
}
162+
163+
assert!(args.next().is_none(), "start lang item has more arguments than expected");
164+
165+
Ok(ecx)
166+
}
167+
168+
pub fn eval_main<'tcx>(
169+
tcx: TyCtxt<'tcx>,
170+
main_id: DefId,
171+
config: MiriConfig,
172+
) {
173+
let mut ecx = match create_ecx(tcx, main_id, config) {
174+
Ok(ecx) => ecx,
175+
Err(mut err) => {
176+
err.print_backtrace();
177+
panic!("Miri initialziation error: {}", err.kind)
178+
}
179+
};
180+
181+
// Perform the main execution.
182+
let res: InterpResult = (|| {
183+
ecx.run()?;
184+
ecx.run_tls_dtors()
185+
})();
186+
187+
// Process the result.
188+
match res {
189+
Ok(()) => {
190+
let leaks = ecx.memory().leak_report();
191+
// Disable the leak test on some platforms where we do not
192+
// correctly implement TLS destructors.
193+
let target_os = ecx.tcx.tcx.sess.target.target.target_os.to_lowercase();
194+
let ignore_leaks = target_os == "windows" || target_os == "macos";
195+
if !ignore_leaks && leaks != 0 {
196+
tcx.sess.err("the evaluated program leaked memory");
197+
}
198+
}
199+
Err(mut e) => {
200+
// Special treatment for some error kinds
201+
let msg = match e.kind {
202+
InterpError::Exit(code) => std::process::exit(code),
203+
InterpError::NoMirFor(..) =>
204+
format!("{}. Did you set `MIRI_SYSROOT` to a Miri-enabled sysroot? You can prepare one with `cargo miri setup`.", e),
205+
_ => e.to_string()
206+
};
207+
e.print_backtrace();
208+
if let Some(frame) = ecx.stack().last() {
209+
let block = &frame.body.basic_blocks()[frame.block];
210+
let span = if frame.stmt < block.statements.len() {
211+
block.statements[frame.stmt].source_info.span
212+
} else {
213+
block.terminator().source_info.span
214+
};
215+
216+
let msg = format!("Miri evaluation error: {}", msg);
217+
let mut err = struct_error(ecx.tcx.tcx.at(span), msg.as_str());
218+
let frames = ecx.generate_stacktrace(None);
219+
err.span_label(span, msg);
220+
// We iterate with indices because we need to look at the next frame (the caller).
221+
for idx in 0..frames.len() {
222+
let frame_info = &frames[idx];
223+
let call_site_is_local = frames.get(idx+1).map_or(false,
224+
|caller_info| caller_info.instance.def_id().is_local());
225+
if call_site_is_local {
226+
err.span_note(frame_info.call_site, &frame_info.to_string());
227+
} else {
228+
err.note(&frame_info.to_string());
229+
}
230+
}
231+
err.emit();
232+
} else {
233+
ecx.tcx.sess.err(&msg);
234+
}
235+
236+
for (i, frame) in ecx.stack().iter().enumerate() {
237+
trace!("-------------------");
238+
trace!("Frame {}", i);
239+
trace!(" return: {:?}", frame.return_place.map(|p| *p));
240+
for (i, local) in frame.locals.iter().enumerate() {
241+
trace!(" local {}: {:?}", i, local.value);
242+
}
243+
}
244+
}
245+
}
246+
}

src/helpers.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::mem;
22

3-
use rustc::ty::{self, layout};
3+
use rustc::ty::{self, layout::{self, Size}};
44
use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
55

66
use crate::*;

src/intptrcast.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ impl<'mir, 'tcx> GlobalState {
8989
}
9090
};
9191

92+
debug_assert_eq!(base_addr % alloc.align.bytes(), 0); // sanity check
9293
Ok(base_addr + ptr.offset.bytes())
9394
}
9495

0 commit comments

Comments
 (0)