rust/miri/lib.rs

389 lines
12 KiB
Rust
Raw Normal View History

2017-07-21 10:25:30 -05:00
#![feature(
i128_type,
rustc_private,
2017-12-14 04:03:55 -06:00
conservative_impl_trait,
catch_expr,
2017-07-21 10:25:30 -05:00
)]
#[macro_use]
extern crate log;
2018-01-06 09:21:24 -06:00
// From rustc.
#[macro_use]
2017-07-21 10:25:30 -05:00
extern crate rustc;
2017-12-14 04:03:55 -06:00
extern crate rustc_mir;
extern crate rustc_data_structures;
2017-07-21 10:25:30 -05:00
extern crate syntax;
2017-12-14 04:03:55 -06:00
extern crate regex;
#[macro_use]
extern crate lazy_static;
2017-07-21 10:25:30 -05:00
2017-07-24 08:19:32 -05:00
use rustc::ty::{self, TyCtxt};
2017-12-06 08:03:24 -06:00
use rustc::ty::layout::{TyLayout, LayoutOf};
2017-07-24 08:19:32 -05:00
use rustc::hir::def_id::DefId;
2017-07-21 10:25:30 -05:00
use rustc::mir;
use rustc::traits;
use syntax::ast::Mutability;
use syntax::codemap::Span;
use std::collections::{HashMap, BTreeMap};
2017-07-21 10:25:30 -05:00
pub use rustc::mir::interpret::*;
2017-12-14 04:03:55 -06:00
pub use rustc_mir::interpret::*;
2017-07-21 10:25:30 -05:00
mod fn_call;
mod operator;
mod intrinsic;
mod helpers;
mod memory;
2017-07-31 06:30:44 -05:00
mod tls;
2017-12-14 04:03:55 -06:00
mod locks;
mod range_map;
mod validation;
2017-07-24 08:19:32 -05:00
use fn_call::EvalContextExt as MissingFnsEvalContextExt;
use operator::EvalContextExt as OperatorEvalContextExt;
use intrinsic::EvalContextExt as IntrinsicEvalContextExt;
2017-08-01 04:11:57 -05:00
use tls::EvalContextExt as TlsEvalContextExt;
2017-12-14 04:03:55 -06:00
use locks::LockInfo;
use locks::MemoryExt as LockMemoryExt;
use validation::EvalContextExt as ValidationEvalContextExt;
use range_map::RangeMap;
use validation::{ValidationQuery, AbsPlace};
2017-07-24 08:19:32 -05:00
2017-07-21 10:25:30 -05:00
pub fn eval_main<'a, 'tcx: 'a>(
tcx: TyCtxt<'a, 'tcx, 'tcx>,
main_id: DefId,
start_wrapper: Option<DefId>,
limits: ResourceLimits,
) {
fn run_main<'a, 'tcx: 'a>(
2017-12-14 04:03:55 -06:00
ecx: &mut rustc_mir::interpret::EvalContext<'a, 'tcx, Evaluator<'tcx>>,
2017-07-21 10:25:30 -05:00
main_id: DefId,
start_wrapper: Option<DefId>,
) -> EvalResult<'tcx> {
let main_instance = ty::Instance::mono(ecx.tcx, main_id);
let main_mir = ecx.load_mir(main_instance.def)?;
let mut cleanup_ptr = None; // Pointer to be deallocated when we are done
2017-11-21 06:32:40 -06:00
if !main_mir.return_ty().is_nil() || main_mir.arg_count != 0 {
return err!(Unimplemented(
"miri does not support main functions without `fn()` type signatures"
.to_owned(),
));
2017-07-21 10:25:30 -05:00
}
if let Some(start_id) = start_wrapper {
let start_instance = ty::Instance::mono(ecx.tcx, start_id);
let start_mir = ecx.load_mir(start_instance.def)?;
if start_mir.arg_count != 3 {
return err!(AbiViolation(format!(
"'start' lang item should have three arguments, but has {}",
start_mir.arg_count
)));
2017-07-21 10:25:30 -05:00
}
// Return value
let size = ecx.tcx.data_layout.pointer_size.bytes();
2018-01-02 16:43:03 -06:00
let align = ecx.tcx.data_layout.pointer_align;
let ret_ptr = ecx.memory_mut().allocate(size, align, Some(MemoryKind::Stack))?;
2017-07-21 10:25:30 -05:00
cleanup_ptr = Some(ret_ptr);
// Push our stack frame
ecx.push_stack_frame(
start_instance,
start_mir.span,
start_mir,
2018-01-02 16:43:03 -06:00
Place::from_ptr(ret_ptr, align),
2017-07-21 10:25:30 -05:00
StackPopCleanup::None,
)?;
let mut args = ecx.frame().mir.args_iter();
// First argument: pointer to main()
let main_ptr = ecx.memory_mut().create_fn_alloc(main_instance);
2017-12-06 01:39:31 -06:00
let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
let main_ty = main_instance.ty(ecx.tcx);
2017-07-21 10:25:30 -05:00
let main_ptr_ty = ecx.tcx.mk_fn_ptr(main_ty.fn_sig(ecx.tcx));
ecx.write_value(
ValTy {
value: Value::ByVal(PrimVal::Ptr(main_ptr)),
ty: main_ptr_ty,
},
dest,
)?;
2017-07-21 10:25:30 -05:00
// Second argument (argc): 1
2017-12-06 01:39:31 -06:00
let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
2017-07-21 10:25:30 -05:00
let ty = ecx.tcx.types.isize;
ecx.write_primval(dest, PrimVal::Bytes(1), ty)?;
2017-07-21 10:25:30 -05:00
// FIXME: extract main source file path
// Third argument (argv): &[b"foo"]
2017-12-06 01:39:31 -06:00
let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
2017-07-21 10:25:30 -05:00
let ty = ecx.tcx.mk_imm_ptr(ecx.tcx.mk_imm_ptr(ecx.tcx.types.u8));
let foo = ecx.memory.allocate_cached(b"foo\0");
let ptr_size = ecx.memory.pointer_size();
2018-01-02 16:43:03 -06:00
let ptr_align = ecx.tcx.data_layout.pointer_align;
let foo_ptr = ecx.memory.allocate(ptr_size, ptr_align, None)?;
ecx.memory.write_primval(foo_ptr, ptr_align, PrimVal::Ptr(foo.into()), ptr_size, false)?;
ecx.memory.mark_static_initalized(foo_ptr.alloc_id, Mutability::Immutable)?;
ecx.write_ptr(dest, foo_ptr.into(), ty)?;
assert!(args.next().is_none(), "start lang item has more arguments than expected");
2017-07-21 10:25:30 -05:00
} else {
ecx.push_stack_frame(
main_instance,
main_mir.span,
main_mir,
2017-12-06 01:39:31 -06:00
Place::undef(),
2017-07-21 10:25:30 -05:00
StackPopCleanup::None,
)?;
// No arguments
let mut args = ecx.frame().mir.args_iter();
assert!(args.next().is_none(), "main function must not have arguments");
2017-07-21 10:25:30 -05:00
}
while ecx.step()? {}
2017-08-01 04:11:57 -05:00
ecx.run_tls_dtors()?;
2017-07-21 10:25:30 -05:00
if let Some(cleanup_ptr) = cleanup_ptr {
ecx.memory_mut().deallocate(
cleanup_ptr,
None,
MemoryKind::Stack,
)?;
2017-07-21 10:25:30 -05:00
}
Ok(())
}
2018-01-02 16:43:03 -06:00
let mut ecx = EvalContext::new(tcx, ty::ParamEnv::empty(traits::Reveal::All), limits, Default::default(), Default::default());
2017-07-21 10:25:30 -05:00
match run_main(&mut ecx, main_id, start_wrapper) {
Ok(()) => {
let leaks = ecx.memory().leak_report();
if leaks != 0 {
tcx.sess.err("the evaluated program leaked memory");
}
}
Err(mut e) => {
ecx.report(&mut e);
2017-07-21 10:25:30 -05:00
}
}
}
#[derive(Default)]
2017-12-14 04:03:55 -06:00
pub struct Evaluator<'tcx> {
2017-07-21 10:25:30 -05:00
/// Environment variables set by `setenv`
/// Miri does not expose env vars from the host to the emulated program
pub(crate) env_vars: HashMap<Vec<u8>, MemoryPointer>,
2017-12-14 04:03:55 -06:00
/// Places that were suspended by the validation subsystem, and will be recovered later
pub(crate) suspended: HashMap<DynamicLifetime, Vec<ValidationQuery<'tcx>>>,
2017-07-21 10:25:30 -05:00
}
pub type TlsKey = usize;
#[derive(Copy, Clone, Debug)]
pub struct TlsEntry<'tcx> {
data: Pointer, // Will eventually become a map from thread IDs to `Pointer`s, if we ever support more than one thread.
dtor: Option<ty::Instance<'tcx>>,
}
#[derive(Default)]
pub struct MemoryData<'tcx> {
2017-07-21 10:25:30 -05:00
/// The Key to use for the next thread-local allocation.
next_thread_local: TlsKey,
/// pthreads-style thread-local storage.
thread_local: BTreeMap<TlsKey, TlsEntry<'tcx>>,
2017-12-14 04:03:55 -06:00
/// Memory regions that are locked by some function
///
/// Only mutable (static mut, heap, stack) allocations have an entry in this map.
/// The entry is created when allocating the memory and deleted after deallocation.
locks: HashMap<u64, RangeMap<LockInfo<'tcx>>>,
2017-07-21 10:25:30 -05:00
}
2017-12-14 04:03:55 -06:00
impl<'tcx> Machine<'tcx> for Evaluator<'tcx> {
2017-07-21 10:25:30 -05:00
type MemoryData = MemoryData<'tcx>;
type MemoryKinds = memory::MemoryKind;
2017-07-21 10:25:30 -05:00
/// Returns Ok() when the function was handled, fail otherwise
fn eval_fn_call<'a>(
2017-07-21 10:25:30 -05:00
ecx: &mut EvalContext<'a, 'tcx, Self>,
instance: ty::Instance<'tcx>,
2017-12-06 01:39:31 -06:00
destination: Option<(Place, mir::BasicBlock)>,
args: &[ValTy<'tcx>],
span: Span,
2017-07-21 10:25:30 -05:00
sig: ty::FnSig<'tcx>,
) -> EvalResult<'tcx, bool> {
ecx.eval_fn_call(instance, destination, args, span, sig)
2017-07-21 10:25:30 -05:00
}
fn call_intrinsic<'a>(
2017-12-14 04:03:55 -06:00
ecx: &mut rustc_mir::interpret::EvalContext<'a, 'tcx, Self>,
instance: ty::Instance<'tcx>,
args: &[ValTy<'tcx>],
2017-12-06 01:39:31 -06:00
dest: Place,
2017-11-21 06:32:40 -06:00
dest_layout: TyLayout<'tcx>,
target: mir::BasicBlock,
) -> EvalResult<'tcx> {
2017-11-21 06:32:40 -06:00
ecx.call_intrinsic(instance, args, dest, dest_layout, target)
}
2017-08-01 04:11:57 -05:00
fn try_ptr_op<'a>(
2017-12-14 04:03:55 -06:00
ecx: &rustc_mir::interpret::EvalContext<'a, 'tcx, Self>,
bin_op: mir::BinOp,
left: PrimVal,
left_ty: ty::Ty<'tcx>,
right: PrimVal,
right_ty: ty::Ty<'tcx>,
) -> EvalResult<'tcx, Option<(PrimVal, bool)>> {
ecx.ptr_op(bin_op, left, left_ty, right, right_ty)
}
fn mark_static_initialized(m: memory::MemoryKind) -> EvalResult<'tcx> {
use memory::MemoryKind::*;
match m {
// FIXME: This could be allowed, but not for env vars set during miri execution
2017-08-02 09:59:01 -05:00
Env => err!(Unimplemented("statics can't refer to env vars".to_owned())),
_ => Ok(()),
}
}
fn box_alloc<'a>(
ecx: &mut EvalContext<'a, 'tcx, Self>,
ty: ty::Ty<'tcx>,
2017-12-06 01:39:31 -06:00
dest: Place,
) -> EvalResult<'tcx> {
2017-12-06 08:03:24 -06:00
let layout = ecx.layout_of(ty)?;
// Call the `exchange_malloc` lang item
let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
let malloc = ty::Instance::mono(ecx.tcx, malloc);
let malloc_mir = ecx.load_mir(malloc.def)?;
ecx.push_stack_frame(
malloc,
malloc_mir.span,
malloc_mir,
dest,
// Don't do anything when we are done. The statement() function will increment
// the old stack frame's stmt counter to the next statement, which means that when
// exchange_malloc returns, we go on evaluating exactly where we want to be.
StackPopCleanup::None,
)?;
let mut args = ecx.frame().mir.args_iter();
let usize = ecx.tcx.types.usize;
// First argument: size
2017-12-06 01:39:31 -06:00
let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
ecx.write_value(
ValTy {
2017-12-06 08:03:24 -06:00
value: Value::ByVal(PrimVal::Bytes(layout.size.bytes().into())),
ty: usize,
},
dest,
)?;
// Second argument: align
2017-12-06 01:39:31 -06:00
let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
ecx.write_value(
ValTy {
2017-12-06 08:03:24 -06:00
value: Value::ByVal(PrimVal::Bytes(layout.align.abi().into())),
ty: usize,
},
dest,
)?;
// No more arguments
assert!(args.next().is_none(), "exchange_malloc lang item has more arguments than expected");
Ok(())
}
fn global_item_with_linkage<'a>(
ecx: &mut EvalContext<'a, 'tcx, Self>,
instance: ty::Instance<'tcx>,
mutability: Mutability,
) -> EvalResult<'tcx> {
// FIXME: check that it's `#[linkage = "extern_weak"]`
trace!("Initializing an extern global with NULL");
let ptr_size = ecx.memory.pointer_size();
2018-01-02 16:43:03 -06:00
let ptr_align = ecx.tcx.data_layout.pointer_align;
let ptr = ecx.memory.allocate(
ptr_size,
2018-01-02 16:43:03 -06:00
ptr_align,
None,
)?;
2018-01-02 16:43:03 -06:00
ecx.memory.write_ptr_sized_unsigned(ptr, ptr_align, PrimVal::Bytes(0))?;
ecx.memory.mark_static_initalized(ptr.alloc_id, mutability)?;
2017-11-02 05:15:50 -05:00
ecx.tcx.interpret_interner.borrow_mut().cache(
GlobalId {
instance,
promoted: None,
},
2018-01-02 16:43:03 -06:00
ptr.into(),
);
Ok(())
}
2017-12-14 04:03:55 -06:00
fn check_locks<'a>(
mem: &Memory<'a, 'tcx, Self>,
ptr: MemoryPointer,
size: u64,
access: AccessKind,
) -> EvalResult<'tcx> {
mem.check_locks(ptr, size, access)
}
fn add_lock<'a>(
mem: &mut Memory<'a, 'tcx, Self>,
id: u64,
) {
mem.data.locks.insert(id, RangeMap::new());
}
fn free_lock<'a>(
mem: &mut Memory<'a, 'tcx, Self>,
id: u64,
len: u64,
) -> EvalResult<'tcx> {
mem.data.locks
.remove(&id)
.expect("allocation has no corresponding locks")
.check(
Some(mem.cur_frame),
0,
len,
AccessKind::Read,
)
.map_err(|lock| {
EvalErrorKind::DeallocatedLockedMemory {
//ptr, FIXME
ptr: MemoryPointer {
alloc_id: AllocId(0),
offset: 0,
},
lock: lock.active,
}.into()
})
}
fn end_region<'a>(
ecx: &mut EvalContext<'a, 'tcx, Self>,
reg: Option<::rustc::middle::region::Scope>,
) -> EvalResult<'tcx> {
ecx.end_region(reg)
}
fn validation_op<'a>(
ecx: &mut EvalContext<'a, 'tcx, Self>,
op: ::rustc::mir::ValidationOp,
operand: &::rustc::mir::ValidationOperand<'tcx, ::rustc::mir::Place<'tcx>>,
) -> EvalResult<'tcx> {
ecx.validation_op(op, operand)
}
2017-07-21 10:25:30 -05:00
}