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