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