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