]> git.lizzy.rs Git - rust.git/blob - src/machine.rs
Merge branch 'master' into rustup
[rust.git] / src / machine.rs
1 //! Global machine state as well as implementation of the interpreter engine
2 //! `Machine` trait.
3
4 use std::rc::Rc;
5 use std::borrow::Cow;
6 use std::collections::HashMap;
7 use std::cell::RefCell;
8
9 use rand::rngs::StdRng;
10
11 use syntax::attr;
12 use syntax::symbol::sym;
13 use rustc::hir::def_id::DefId;
14 use rustc::ty::{self, layout::{Size, LayoutOf}, query::TyCtxtAt};
15 use rustc::mir;
16
17 use crate::*;
18
19 /// Extra memory kinds
20 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
21 pub enum MiriMemoryKind {
22     /// `__rust_alloc` memory.
23     Rust,
24     /// `malloc` memory.
25     C,
26     /// Part of env var emulation.
27     Env,
28     /// Statics.
29     Static,
30 }
31
32 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
33     #[inline(always)]
34     fn into(self) -> MemoryKind<MiriMemoryKind> {
35         MemoryKind::Machine(self)
36     }
37 }
38
39 /// Extra per-allocation data
40 #[derive(Debug, Clone)]
41 pub struct AllocExtra {
42     pub stacked_borrows: stacked_borrows::AllocExtra,
43     pub intptrcast: intptrcast::AllocExtra,
44 }
45
46 /// Extra global memory data
47 #[derive(Clone, Debug)]
48 pub struct MemoryExtra {
49     pub stacked_borrows: stacked_borrows::MemoryExtra,
50     pub intptrcast: intptrcast::MemoryExtra,
51     /// The random number generator to use if Miri is running in non-deterministic mode and to
52     /// enable intptrcast
53     pub(crate) rng: Option<RefCell<StdRng>>
54 }
55
56 impl MemoryExtra {
57     pub fn with_rng(rng: Option<StdRng>) -> Self {
58         MemoryExtra {
59             stacked_borrows: Default::default(),
60             intptrcast: Default::default(),
61             rng: rng.map(RefCell::new),
62         }
63     }
64 }
65
66 /// The machine itself.
67 pub struct Evaluator<'tcx> {
68     /// Environment variables set by `setenv`.
69     /// Miri does not expose env vars from the host to the emulated program.
70     pub(crate) env_vars: HashMap<Vec<u8>, Pointer<Tag>>,
71
72     /// Program arguments (`Option` because we can only initialize them after creating the ecx).
73     /// These are *pointers* to argc/argv because macOS.
74     /// We also need the full command line as one string because of Windows.
75     pub(crate) argc: Option<Pointer<Tag>>,
76     pub(crate) argv: Option<Pointer<Tag>>,
77     pub(crate) cmd_line: Option<Pointer<Tag>>,
78
79     /// Last OS error.
80     pub(crate) last_error: u32,
81
82     /// TLS state.
83     pub(crate) tls: TlsData<'tcx>,
84
85     /// Whether to enforce the validity invariant.
86     pub(crate) validate: bool,
87 }
88
89 impl<'tcx> Evaluator<'tcx> {
90     pub(crate) fn new(validate: bool) -> Self {
91         Evaluator {
92             env_vars: HashMap::default(),
93             argc: None,
94             argv: None,
95             cmd_line: None,
96             last_error: 0,
97             tls: TlsData::default(),
98             validate,
99         }
100     }
101 }
102
103 /// A rustc InterpretCx for Miri.
104 pub type MiriEvalContext<'mir, 'tcx> = InterpretCx<'mir, 'tcx, Evaluator<'tcx>>;
105
106 /// A little trait that's useful to be inherited by extension traits.
107 pub trait MiriEvalContextExt<'mir, 'tcx> {
108     fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx>;
109     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx>;
110 }
111 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
112     #[inline(always)]
113     fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
114         self
115     }
116     #[inline(always)]
117     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
118         self
119     }
120 }
121
122 /// Machine hook implementations.
123 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
124     type MemoryKinds = MiriMemoryKind;
125
126     type FrameExtra = stacked_borrows::CallId;
127     type MemoryExtra = MemoryExtra;
128     type AllocExtra = AllocExtra;
129     type PointerTag = Tag;
130
131     type MemoryMap = MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
132
133     const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
134
135     #[inline(always)]
136     fn enforce_validity(ecx: &InterpretCx<'mir, 'tcx, Self>) -> bool {
137         ecx.machine.validate
138     }
139
140     /// Returns `Ok()` when the function was handled; fail otherwise.
141     #[inline(always)]
142     fn find_fn(
143         ecx: &mut InterpretCx<'mir, 'tcx, Self>,
144         instance: ty::Instance<'tcx>,
145         args: &[OpTy<'tcx, Tag>],
146         dest: Option<PlaceTy<'tcx, Tag>>,
147         ret: Option<mir::BasicBlock>,
148     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
149         ecx.find_fn(instance, args, dest, ret)
150     }
151
152     #[inline(always)]
153     fn call_intrinsic(
154         ecx: &mut rustc_mir::interpret::InterpretCx<'mir, 'tcx, Self>,
155         instance: ty::Instance<'tcx>,
156         args: &[OpTy<'tcx, Tag>],
157         dest: PlaceTy<'tcx, Tag>,
158     ) -> InterpResult<'tcx> {
159         ecx.call_intrinsic(instance, args, dest)
160     }
161
162     #[inline(always)]
163     fn ptr_op(
164         ecx: &rustc_mir::interpret::InterpretCx<'mir, 'tcx, Self>,
165         bin_op: mir::BinOp,
166         left: ImmTy<'tcx, Tag>,
167         right: ImmTy<'tcx, Tag>,
168     ) -> InterpResult<'tcx, (Scalar<Tag>, bool)> {
169         ecx.ptr_op(bin_op, left, right)
170     }
171
172     fn box_alloc(
173         ecx: &mut InterpretCx<'mir, 'tcx, Self>,
174         dest: PlaceTy<'tcx, Tag>,
175     ) -> InterpResult<'tcx> {
176         trace!("box_alloc for {:?}", dest.layout.ty);
177         // Call the `exchange_malloc` lang item.
178         let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
179         let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
180         let malloc_mir = ecx.load_mir(malloc.def)?;
181         ecx.push_stack_frame(
182             malloc,
183             malloc_mir.span,
184             malloc_mir,
185             Some(dest),
186             // Don't do anything when we are done. The `statement()` function will increment
187             // the old stack frame's stmt counter to the next statement, which means that when
188             // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
189             StackPopCleanup::None { cleanup: true },
190         )?;
191
192         let mut args = ecx.frame().body.args_iter();
193         let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
194
195         // First argument: `size`.
196         // (`0` is allowed here -- this is expected to be handled by the lang item).
197         let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
198         let size = layout.size.bytes();
199         ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
200
201         // Second argument: `align`.
202         let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
203         let align = layout.align.abi.bytes();
204         ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
205
206         // No more arguments.
207         assert!(
208             args.next().is_none(),
209             "`exchange_malloc` lang item has more arguments than expected"
210         );
211         Ok(())
212     }
213
214     fn find_foreign_static(
215         def_id: DefId,
216         tcx: TyCtxtAt<'tcx>,
217     ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
218         let attrs = tcx.get_attrs(def_id);
219         let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
220             Some(name) => name.as_str(),
221             None => tcx.item_name(def_id).as_str(),
222         };
223
224         let alloc = match link_name.get() {
225             "__cxa_thread_atexit_impl" => {
226                 // This should be all-zero, pointer-sized.
227                 let size = tcx.data_layout.pointer_size;
228                 let data = vec![0; size.bytes() as usize];
229                 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
230             }
231             _ => return err!(Unimplemented(
232                     format!("can't access foreign static: {}", link_name),
233                 )),
234         };
235         Ok(Cow::Owned(alloc))
236     }
237
238     #[inline(always)]
239     fn before_terminator(_ecx: &mut InterpretCx<'mir, 'tcx, Self>) -> InterpResult<'tcx>
240     {
241         // We are not interested in detecting loops.
242         Ok(())
243     }
244
245     fn tag_allocation<'b>(
246         id: AllocId,
247         alloc: Cow<'b, Allocation>,
248         kind: Option<MemoryKind<Self::MemoryKinds>>,
249         memory: &Memory<'mir, 'tcx, Self>,
250     ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
251         let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
252         let alloc = alloc.into_owned();
253         let (stacks, base_tag) = Stacks::new_allocation(
254             id,
255             Size::from_bytes(alloc.bytes.len() as u64),
256             Rc::clone(&memory.extra.stacked_borrows),
257             kind,
258         );
259         if kind != MiriMemoryKind::Static.into() {
260             assert!(alloc.relocations.is_empty(), "Only statics can come initialized with inner pointers");
261             // Now we can rely on the inner pointers being static, too.
262         }
263         let mut memory_extra = memory.extra.stacked_borrows.borrow_mut();
264         let alloc: Allocation<Tag, Self::AllocExtra> = Allocation {
265             bytes: alloc.bytes,
266             relocations: Relocations::from_presorted(
267                 alloc.relocations.iter()
268                     // The allocations in the relocations (pointers stored *inside* this allocation)
269                     // all get the base pointer tag.
270                     .map(|&(offset, ((), alloc))| (offset, (memory_extra.static_base_ptr(alloc), alloc)))
271                     .collect()
272             ),
273             undef_mask: alloc.undef_mask,
274             align: alloc.align,
275             mutability: alloc.mutability,
276             extra: AllocExtra {
277                 stacked_borrows: stacks,
278                 intptrcast: Default::default(),
279             },
280         };
281         (Cow::Owned(alloc), base_tag)
282     }
283
284     #[inline(always)]
285     fn tag_static_base_pointer(
286         id: AllocId,
287         memory: &Memory<'mir, 'tcx, Self>,
288     ) -> Self::PointerTag {
289         memory.extra.stacked_borrows.borrow_mut().static_base_ptr(id)
290     }
291
292     #[inline(always)]
293     fn retag(
294         ecx: &mut InterpretCx<'mir, 'tcx, Self>,
295         kind: mir::RetagKind,
296         place: PlaceTy<'tcx, Tag>,
297     ) -> InterpResult<'tcx> {
298         if !ecx.tcx.sess.opts.debugging_opts.mir_emit_retag || !Self::enforce_validity(ecx) {
299             // No tracking, or no retagging. The latter is possible because a dependency of ours
300             // might be called with different flags than we are, so there are `Retag`
301             // statements but we do not want to execute them.
302             // Also, honor the whitelist in `enforce_validity` because otherwise we might retag
303             // uninitialized data.
304              Ok(())
305         } else {
306             ecx.retag(kind, place)
307         }
308     }
309
310     #[inline(always)]
311     fn stack_push(
312         ecx: &mut InterpretCx<'mir, 'tcx, Self>,
313     ) -> InterpResult<'tcx, stacked_borrows::CallId> {
314         Ok(ecx.memory().extra.stacked_borrows.borrow_mut().new_call())
315     }
316
317     #[inline(always)]
318     fn stack_pop(
319         ecx: &mut InterpretCx<'mir, 'tcx, Self>,
320         extra: stacked_borrows::CallId,
321     ) -> InterpResult<'tcx> {
322         Ok(ecx.memory().extra.stacked_borrows.borrow_mut().end_call(extra))
323     }
324
325     fn int_to_ptr(
326         int: u64,
327         memory: &Memory<'mir, 'tcx, Self>,
328     ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
329         if int == 0 {
330             err!(InvalidNullPointerUsage)
331         } else if memory.extra.rng.is_none() {
332             err!(ReadBytesAsPointer)
333         } else {
334            intptrcast::GlobalState::int_to_ptr(int, memory)
335         }
336     }
337
338     fn ptr_to_int(
339         ptr: Pointer<Self::PointerTag>,
340         memory: &Memory<'mir, 'tcx, Self>,
341     ) -> InterpResult<'tcx, u64> {
342         if memory.extra.rng.is_none() {
343             err!(ReadPointerAsBytes)
344         } else {
345             intptrcast::GlobalState::ptr_to_int(ptr, memory)
346         }
347     }
348 }
349
350 impl AllocationExtra<Tag> for AllocExtra {
351     #[inline(always)]
352     fn memory_read<'tcx>(
353         alloc: &Allocation<Tag, AllocExtra>,
354         ptr: Pointer<Tag>,
355         size: Size,
356     ) -> InterpResult<'tcx> {
357         alloc.extra.stacked_borrows.memory_read(ptr, size)
358     }
359
360     #[inline(always)]
361     fn memory_written<'tcx>(
362         alloc: &mut Allocation<Tag, AllocExtra>,
363         ptr: Pointer<Tag>,
364         size: Size,
365     ) -> InterpResult<'tcx> {
366         alloc.extra.stacked_borrows.memory_written(ptr, size)
367     }
368
369     #[inline(always)]
370     fn memory_deallocated<'tcx>(
371         alloc: &mut Allocation<Tag, AllocExtra>,
372         ptr: Pointer<Tag>,
373         size: Size,
374     ) -> InterpResult<'tcx> {
375         alloc.extra.stacked_borrows.memory_deallocated(ptr, size)
376     }
377 }
378
379 impl MayLeak for MiriMemoryKind {
380     #[inline(always)]
381     fn may_leak(self) -> bool {
382         use self::MiriMemoryKind::*;
383         match self {
384             Rust | C => false,
385             Env | Static => true,
386         }
387     }
388 }