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