]> git.lizzy.rs Git - rust.git/blob - src/machine.rs
20fe2e055fb53887f8ddaac5066063e1dfc67b68
[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     /// Part of env var emulation.
29     Env,
30     /// Statics.
31     Static,
32 }
33
34 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
35     #[inline(always)]
36     fn into(self) -> MemoryKind<MiriMemoryKind> {
37         MemoryKind::Machine(self)
38     }
39 }
40
41 /// Extra per-allocation data
42 #[derive(Debug, Clone)]
43 pub struct AllocExtra {
44     pub stacked_borrows: stacked_borrows::AllocExtra,
45 }
46
47 /// Extra global memory data
48 #[derive(Default, Clone, Debug)]
49 pub struct MemoryExtra {
50     pub stacked_borrows: stacked_borrows::MemoryExtra,
51     pub intptrcast: intptrcast::MemoryExtra,
52     /// The random number generator to use if Miri is running in non-deterministic mode and to
53     /// enable intptrcast
54     pub(crate) rng: Option<RefCell<StdRng>>
55 }
56
57 impl MemoryExtra {
58     pub fn with_rng(rng: Option<StdRng>) -> Self {
59         MemoryExtra {
60             stacked_borrows: Default::default(),
61             intptrcast: Default::default(),
62             rng: rng.map(RefCell::new),
63         }
64     }
65 }
66
67 /// The machine itself.
68 pub struct Evaluator<'tcx> {
69     /// Environment variables set by `setenv`.
70     /// Miri does not expose env vars from the host to the emulated program.
71     pub(crate) env_vars: HashMap<Vec<u8>, Pointer<Tag>>,
72
73     /// Program arguments (`Option` because we can only initialize them after creating the ecx).
74     /// These are *pointers* to argc/argv because macOS.
75     /// We also need the full command line as one string because of Windows.
76     pub(crate) argc: Option<Pointer<Tag>>,
77     pub(crate) argv: Option<Pointer<Tag>>,
78     pub(crate) cmd_line: Option<Pointer<Tag>>,
79
80     /// Last OS error.
81     pub(crate) last_error: u32,
82
83     /// TLS state.
84     pub(crate) tls: TlsData<'tcx>,
85
86     /// Whether to enforce the validity invariant.
87     pub(crate) validate: bool,
88 }
89
90 impl<'tcx> Evaluator<'tcx> {
91     pub(crate) fn new(validate: bool) -> Self {
92         Evaluator {
93             env_vars: HashMap::default(),
94             argc: None,
95             argv: None,
96             cmd_line: None,
97             last_error: 0,
98             tls: TlsData::default(),
99             validate,
100         }
101     }
102 }
103
104 /// A rustc InterpretCx for Miri.
105 pub type MiriEvalContext<'mir, 'tcx> = InterpretCx<'mir, 'tcx, Evaluator<'tcx>>;
106
107 /// A little trait that's useful to be inherited by extension traits.
108 pub trait MiriEvalContextExt<'mir, 'tcx> {
109     fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx>;
110     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx>;
111 }
112 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
113     #[inline(always)]
114     fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
115         self
116     }
117     #[inline(always)]
118     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
119         self
120     }
121 }
122
123 /// Machine hook implementations.
124 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
125     type MemoryKinds = MiriMemoryKind;
126
127     type FrameExtra = stacked_borrows::CallId;
128     type MemoryExtra = MemoryExtra;
129     type AllocExtra = AllocExtra;
130     type PointerTag = Tag;
131
132     type MemoryMap = MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
133
134     const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
135
136     #[inline(always)]
137     fn enforce_validity(ecx: &InterpretCx<'mir, 'tcx, Self>) -> bool {
138         ecx.machine.validate
139     }
140
141     /// Returns `Ok()` when the function was handled; fail otherwise.
142     #[inline(always)]
143     fn find_fn(
144         ecx: &mut InterpretCx<'mir, 'tcx, Self>,
145         instance: ty::Instance<'tcx>,
146         args: &[OpTy<'tcx, Tag>],
147         dest: Option<PlaceTy<'tcx, Tag>>,
148         ret: Option<mir::BasicBlock>,
149     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
150         ecx.find_fn(instance, args, dest, ret)
151     }
152
153     #[inline(always)]
154     fn call_intrinsic(
155         ecx: &mut rustc_mir::interpret::InterpretCx<'mir, 'tcx, Self>,
156         instance: ty::Instance<'tcx>,
157         args: &[OpTy<'tcx, Tag>],
158         dest: PlaceTy<'tcx, Tag>,
159     ) -> InterpResult<'tcx> {
160         ecx.call_intrinsic(instance, args, dest)
161     }
162
163     #[inline(always)]
164     fn ptr_op(
165         ecx: &rustc_mir::interpret::InterpretCx<'mir, 'tcx, Self>,
166         bin_op: mir::BinOp,
167         left: ImmTy<'tcx, Tag>,
168         right: ImmTy<'tcx, Tag>,
169     ) -> InterpResult<'tcx, (Scalar<Tag>, bool)> {
170         ecx.ptr_op(bin_op, left, right)
171     }
172
173     fn box_alloc(
174         ecx: &mut InterpretCx<'mir, 'tcx, Self>,
175         dest: PlaceTy<'tcx, Tag>,
176     ) -> InterpResult<'tcx> {
177         trace!("box_alloc for {:?}", dest.layout.ty);
178         // Call the `exchange_malloc` lang item.
179         let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
180         let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
181         let malloc_mir = ecx.load_mir(malloc.def)?;
182         ecx.push_stack_frame(
183             malloc,
184             malloc_mir.span,
185             malloc_mir,
186             Some(dest),
187             // Don't do anything when we are done. The `statement()` function will increment
188             // the old stack frame's stmt counter to the next statement, which means that when
189             // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
190             StackPopCleanup::None { cleanup: true },
191         )?;
192
193         let mut args = ecx.frame().body.args_iter();
194         let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
195
196         // First argument: `size`.
197         // (`0` is allowed here -- this is expected to be handled by the lang item).
198         let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
199         let size = layout.size.bytes();
200         ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
201
202         // Second argument: `align`.
203         let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
204         let align = layout.align.abi.bytes();
205         ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
206
207         // No more arguments.
208         assert!(
209             args.next().is_none(),
210             "`exchange_malloc` lang item has more arguments than expected"
211         );
212         Ok(())
213     }
214
215     fn find_foreign_static(
216         def_id: DefId,
217         tcx: TyCtxtAt<'tcx>,
218     ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
219         let attrs = tcx.get_attrs(def_id);
220         let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
221             Some(name) => name.as_str(),
222             None => tcx.item_name(def_id).as_str(),
223         };
224
225         let alloc = match link_name.get() {
226             "__cxa_thread_atexit_impl" => {
227                 // This should be all-zero, pointer-sized.
228                 let size = tcx.data_layout.pointer_size;
229                 let data = vec![0; size.bytes() as usize];
230                 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
231             }
232             _ => return err!(Unimplemented(
233                     format!("can't access foreign static: {}", link_name),
234                 )),
235         };
236         Ok(Cow::Owned(alloc))
237     }
238
239     #[inline(always)]
240     fn before_terminator(_ecx: &mut InterpretCx<'mir, 'tcx, Self>) -> InterpResult<'tcx>
241     {
242         // We are not interested in detecting loops.
243         Ok(())
244     }
245
246     fn tag_allocation<'b>(
247         id: AllocId,
248         alloc: Cow<'b, Allocation>,
249         kind: Option<MemoryKind<Self::MemoryKinds>>,
250         memory: &Memory<'mir, 'tcx, Self>,
251     ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
252         let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
253         let alloc = alloc.into_owned();
254         let (stacks, base_tag) = Stacks::new_allocation(
255             id,
256             Size::from_bytes(alloc.bytes.len() as u64),
257             Rc::clone(&memory.extra.stacked_borrows),
258             kind,
259         );
260         if kind != MiriMemoryKind::Static.into() {
261             assert!(alloc.relocations.is_empty(), "Only statics can come initialized with inner pointers");
262             // Now we can rely on the inner pointers being static, too.
263         }
264         let mut memory_extra = memory.extra.stacked_borrows.borrow_mut();
265         let alloc: Allocation<Tag, Self::AllocExtra> = Allocation {
266             bytes: alloc.bytes,
267             relocations: Relocations::from_presorted(
268                 alloc.relocations.iter()
269                     // The allocations in the relocations (pointers stored *inside* this allocation)
270                     // all get the base pointer tag.
271                     .map(|&(offset, ((), alloc))| (offset, (memory_extra.static_base_ptr(alloc), alloc)))
272                     .collect()
273             ),
274             undef_mask: alloc.undef_mask,
275             align: alloc.align,
276             mutability: alloc.mutability,
277             extra: AllocExtra {
278                 stacked_borrows: stacks,
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 }