]> git.lizzy.rs Git - rust.git/blob - src/machine.rs
Fix merge conflicts
[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 location in memory. It is a 32-bit integer.
95     pub(crate) last_error: Option<MPlaceTy<'tcx, 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         args.next().expect_none("`exchange_malloc` lang item has more arguments than expected");
248         Ok(())
249     }
250
251     fn find_foreign_static(
252         tcx: TyCtxt<'tcx>,
253         def_id: DefId,
254     ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
255         let attrs = tcx.get_attrs(def_id);
256         let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
257             Some(name) => name.as_str(),
258             None => tcx.item_name(def_id).as_str(),
259         };
260
261         let alloc = match &*link_name {
262             "__cxa_thread_atexit_impl" => {
263                 // This should be all-zero, pointer-sized.
264                 let size = tcx.data_layout.pointer_size;
265                 let data = vec![0; size.bytes() as usize];
266                 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
267             }
268             _ => throw_unsup_format!("can't access foreign static: {}", link_name),
269         };
270         Ok(Cow::Owned(alloc))
271     }
272
273     #[inline(always)]
274     fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
275         // We are not interested in detecting loops.
276         Ok(())
277     }
278
279     fn tag_allocation<'b>(
280         memory_extra: &MemoryExtra,
281         id: AllocId,
282         alloc: Cow<'b, Allocation>,
283         kind: Option<MemoryKind<Self::MemoryKinds>>,
284     ) -> (
285         Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>,
286         Self::PointerTag,
287     ) {
288         let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
289         let alloc = alloc.into_owned();
290         let (stacks, base_tag) = if !memory_extra.validate {
291             (None, Tag::Untagged)
292         } else {
293             let (stacks, base_tag) = Stacks::new_allocation(
294                 id,
295                 alloc.size,
296                 Rc::clone(&memory_extra.stacked_borrows),
297                 kind,
298             );
299             (Some(stacks), base_tag)
300         };
301         let mut stacked_borrows = memory_extra.stacked_borrows.borrow_mut();
302         let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
303             |alloc| {
304                 if !memory_extra.validate {
305                     Tag::Untagged
306                 } else {
307                     // Only statics may already contain pointers at this point
308                     assert_eq!(kind, MiriMemoryKind::Static.into());
309                     stacked_borrows.static_base_ptr(alloc)
310                 }
311             },
312             AllocExtra {
313                 stacked_borrows: stacks,
314             },
315         );
316         (Cow::Owned(alloc), base_tag)
317     }
318
319     #[inline(always)]
320     fn tag_static_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
321         if !memory_extra.validate {
322             Tag::Untagged
323         } else {
324             memory_extra
325                 .stacked_borrows
326                 .borrow_mut()
327                 .static_base_ptr(id)
328         }
329     }
330
331     #[inline(always)]
332     fn retag(
333         ecx: &mut InterpCx<'mir, 'tcx, Self>,
334         kind: mir::RetagKind,
335         place: PlaceTy<'tcx, Tag>,
336     ) -> InterpResult<'tcx> {
337         if !Self::enforce_validity(ecx) {
338             // No tracking.
339             Ok(())
340         } else {
341             ecx.retag(kind, place)
342         }
343     }
344
345     #[inline(always)]
346     fn stack_push(
347         ecx: &mut InterpCx<'mir, 'tcx, Self>,
348     ) -> InterpResult<'tcx, stacked_borrows::CallId> {
349         Ok(ecx.memory.extra.stacked_borrows.borrow_mut().new_call())
350     }
351
352     #[inline(always)]
353     fn stack_pop(
354         ecx: &mut InterpCx<'mir, 'tcx, Self>,
355         extra: stacked_borrows::CallId,
356     ) -> InterpResult<'tcx> {
357         Ok(ecx
358             .memory
359             .extra
360             .stacked_borrows
361             .borrow_mut()
362             .end_call(extra))
363     }
364
365     #[inline(always)]
366     fn int_to_ptr(
367         memory: &Memory<'mir, 'tcx, Self>,
368         int: u64,
369     ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
370         intptrcast::GlobalState::int_to_ptr(int, memory)
371     }
372
373     #[inline(always)]
374     fn ptr_to_int(
375         memory: &Memory<'mir, 'tcx, Self>,
376         ptr: Pointer<Self::PointerTag>,
377     ) -> InterpResult<'tcx, u64> {
378         intptrcast::GlobalState::ptr_to_int(ptr, memory)
379     }
380 }
381
382 impl AllocationExtra<Tag> for AllocExtra {
383     #[inline(always)]
384     fn memory_read<'tcx>(
385         alloc: &Allocation<Tag, AllocExtra>,
386         ptr: Pointer<Tag>,
387         size: Size,
388     ) -> InterpResult<'tcx> {
389         if let Some(ref stacked_borrows) = alloc.extra.stacked_borrows {
390             stacked_borrows.memory_read(ptr, size)
391         } else {
392             Ok(())
393         }
394     }
395
396     #[inline(always)]
397     fn memory_written<'tcx>(
398         alloc: &mut Allocation<Tag, AllocExtra>,
399         ptr: Pointer<Tag>,
400         size: Size,
401     ) -> InterpResult<'tcx> {
402         if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
403             stacked_borrows.memory_written(ptr, size)
404         } else {
405             Ok(())
406         }
407     }
408
409     #[inline(always)]
410     fn memory_deallocated<'tcx>(
411         alloc: &mut Allocation<Tag, AllocExtra>,
412         ptr: Pointer<Tag>,
413         size: Size,
414     ) -> InterpResult<'tcx> {
415         if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
416             stacked_borrows.memory_deallocated(ptr, size)
417         } else {
418             Ok(())
419         }
420     }
421 }
422
423 impl MayLeak for MiriMemoryKind {
424     #[inline(always)]
425     fn may_leak(self) -> bool {
426         use self::MiriMemoryKind::*;
427         match self {
428             Rust | C | WinHeap => false,
429             Env | Static => true,
430         }
431     }
432 }