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