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