]> git.lizzy.rs Git - rust.git/blob - src/machine.rs
update the environ shim when environment changes
[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::num::NonZeroU64;
7 use std::rc::Rc;
8
9 use rand::rngs::StdRng;
10
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc::mir;
13 use rustc::ty::{
14     self,
15     layout::{LayoutOf, Size},
16     Ty,
17 };
18 use rustc_ast::attr;
19 use rustc_span::{source_map::Span, symbol::{sym, Symbol}};
20
21 use crate::*;
22
23 // Some global facts about the emulated machine.
24 pub const PAGE_SIZE: u64 = 4 * 1024; // FIXME: adjust to target architecture
25 pub const STACK_ADDR: u64 = 32 * PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
26 pub const STACK_SIZE: u64 = 16 * PAGE_SIZE; // whatever
27 pub const NUM_CPUS: u64 = 1;
28
29 /// Extra data stored with each stack frame
30 #[derive(Debug)]
31 pub struct FrameData<'tcx> {
32     /// Extra data for Stacked Borrows.
33     pub call_id: stacked_borrows::CallId,
34
35     /// If this is Some(), then this is a special "catch unwind" frame (the frame of the closure
36     /// called by `__rustc_maybe_catch_panic`). When this frame is popped during unwinding a panic,
37     /// we stop unwinding, use the `CatchUnwindData` to
38     /// store the panic payload, and continue execution in the parent frame.
39     pub catch_panic: Option<CatchUnwindData<'tcx>>,
40 }
41
42 /// Extra memory kinds
43 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
44 pub enum MiriMemoryKind {
45     /// `__rust_alloc` memory.
46     Rust,
47     /// `malloc` memory.
48     C,
49     /// Windows `HeapAlloc` memory.
50     WinHeap,
51     /// Memory for env vars and args, errno, extern statics and other parts of the machine-managed environment.
52     Machine,
53     /// Rust statics.
54     Static,
55 }
56
57 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
58     #[inline(always)]
59     fn into(self) -> MemoryKind<MiriMemoryKind> {
60         MemoryKind::Machine(self)
61     }
62 }
63
64 /// Extra per-allocation data
65 #[derive(Debug, Clone)]
66 pub struct AllocExtra {
67     /// Stacked Borrows state is only added if it is enabled.
68     pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
69 }
70
71 /// Extra global memory data
72 #[derive(Clone, Debug)]
73 pub struct MemoryExtra<'tcx> {
74     pub stacked_borrows: Option<stacked_borrows::MemoryExtra>,
75     pub intptrcast: intptrcast::MemoryExtra,
76
77     /// Mapping extern static names to their canonical allocation.
78     extern_statics: FxHashMap<Symbol, AllocId>,
79
80     /// The random number generator used for resolving non-determinism.
81     /// Needs to be queried by ptr_to_int, hence needs interior mutability.
82     pub(crate) rng: RefCell<StdRng>,
83
84     /// An allocation ID to report when it is being allocated
85     /// (helps for debugging memory leaks).
86     tracked_alloc_id: Option<AllocId>,
87
88     /// Place where the `environ` static is stored.
89     pub(crate) environ: Option<MPlaceTy<'tcx, Tag>>,
90 }
91
92 impl<'tcx> MemoryExtra<'tcx> {
93     pub fn new(rng: StdRng, stacked_borrows: bool, tracked_pointer_tag: Option<PtrId>, tracked_alloc_id: Option<AllocId>) -> Self {
94         let stacked_borrows = if stacked_borrows {
95             Some(Rc::new(RefCell::new(stacked_borrows::GlobalState::new(tracked_pointer_tag))))
96         } else {
97             None
98         };
99         MemoryExtra {
100             stacked_borrows,
101             intptrcast: Default::default(),
102             extern_statics: FxHashMap::default(),
103             rng: RefCell::new(rng),
104             tracked_alloc_id,
105             environ: None,
106         }
107     }
108
109     /// Sets up the "extern statics" for this machine.
110     pub fn init_extern_statics<'mir>(
111         this: &mut MiriEvalContext<'mir, 'tcx>,
112     ) -> InterpResult<'tcx> {
113         match this.tcx.sess.target.target.target_os.as_str() {
114             "linux" => {
115                 // "__cxa_thread_atexit_impl"
116                 // This should be all-zero, pointer-sized.
117                 let layout = this.layout_of(this.tcx.types.usize)?;
118                 let place = this.allocate(layout, MiriMemoryKind::Machine.into());
119                 this.write_scalar(Scalar::from_machine_usize(0, &*this.tcx), place.into())?;
120                 this.memory
121                     .extra
122                     .extern_statics
123                     .insert(Symbol::intern("__cxa_thread_atexit_impl"), place.ptr.assert_ptr().alloc_id)
124                     .unwrap_none();
125
126                 // "environ"
127                 let layout = this.layout_of(this.tcx.types.usize)?;
128                 let place = this.allocate(layout, MiriMemoryKind::Machine.into());
129                 this.write_scalar(Scalar::from_machine_usize(0, &*this.tcx), place.into())?;
130                 this.memory
131                     .extra
132                     .extern_statics
133                     .insert(Symbol::intern("environ"), place.ptr.assert_ptr().alloc_id)
134                     .unwrap_none();
135                 this.memory.extra.environ = Some(place);
136             }
137             _ => {} // No "extern statics" supported on this platform
138         }
139         Ok(())
140     }
141 }
142
143 /// The machine itself.
144 pub struct Evaluator<'tcx> {
145     /// Environment variables set by `setenv`.
146     /// Miri does not expose env vars from the host to the emulated program.
147     pub(crate) env_vars: EnvVars,
148
149     /// Program arguments (`Option` because we can only initialize them after creating the ecx).
150     /// These are *pointers* to argc/argv because macOS.
151     /// We also need the full command line as one string because of Windows.
152     pub(crate) argc: Option<Scalar<Tag>>,
153     pub(crate) argv: Option<Scalar<Tag>>,
154     pub(crate) cmd_line: Option<Scalar<Tag>>,
155
156     /// Last OS error location in memory. It is a 32-bit integer.
157     pub(crate) last_error: Option<MPlaceTy<'tcx, Tag>>,
158
159     /// TLS state.
160     pub(crate) tls: TlsData<'tcx>,
161
162     /// If enabled, the `env_vars` field is populated with the host env vars during initialization
163     /// and random number generation is delegated to the host.
164     pub(crate) communicate: bool,
165
166     /// Whether to enforce the validity invariant.
167     pub(crate) validate: bool,
168
169     pub(crate) file_handler: FileHandler,
170     pub(crate) dir_handler: DirHandler,
171
172     /// The temporary used for storing the argument of
173     /// the call to `miri_start_panic` (the panic payload) when unwinding.
174     pub(crate) panic_payload: Option<ImmTy<'tcx, Tag>>,
175 }
176
177 impl<'tcx> Evaluator<'tcx> {
178     pub(crate) fn new(communicate: bool, validate: bool) -> Self {
179         Evaluator {
180             // `env_vars` could be initialized properly here if `Memory` were available before
181             // calling this method.
182             env_vars: EnvVars::default(),
183             argc: None,
184             argv: None,
185             cmd_line: None,
186             last_error: None,
187             tls: TlsData::default(),
188             communicate,
189             validate,
190             file_handler: Default::default(),
191             dir_handler: Default::default(),
192             panic_payload: None,
193         }
194     }
195 }
196
197 /// A rustc InterpCx for Miri.
198 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'tcx>>;
199
200 /// A little trait that's useful to be inherited by extension traits.
201 pub trait MiriEvalContextExt<'mir, 'tcx> {
202     fn eval_context_ref<'a>(&'a self) -> &'a MiriEvalContext<'mir, 'tcx>;
203     fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriEvalContext<'mir, 'tcx>;
204 }
205 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
206     #[inline(always)]
207     fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
208         self
209     }
210     #[inline(always)]
211     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
212         self
213     }
214 }
215
216 /// Machine hook implementations.
217 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
218     type MemoryKinds = MiriMemoryKind;
219
220     type FrameExtra = FrameData<'tcx>;
221     type MemoryExtra = MemoryExtra<'tcx>;
222     type AllocExtra = AllocExtra;
223     type PointerTag = Tag;
224     type ExtraFnVal = Dlsym;
225
226     type MemoryMap =
227         MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
228
229     const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
230
231     const CHECK_ALIGN: bool = true;
232
233     #[inline(always)]
234     fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
235         ecx.machine.validate
236     }
237
238     #[inline(always)]
239     fn find_mir_or_eval_fn(
240         ecx: &mut InterpCx<'mir, 'tcx, Self>,
241         _span: Span,
242         instance: ty::Instance<'tcx>,
243         args: &[OpTy<'tcx, Tag>],
244         ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
245         unwind: Option<mir::BasicBlock>,
246     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
247         ecx.find_mir_or_eval_fn(instance, args, ret, unwind)
248     }
249
250     #[inline(always)]
251     fn call_extra_fn(
252         ecx: &mut InterpCx<'mir, 'tcx, Self>,
253         fn_val: Dlsym,
254         args: &[OpTy<'tcx, Tag>],
255         ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
256         _unwind: Option<mir::BasicBlock>,
257     ) -> InterpResult<'tcx> {
258         ecx.call_dlsym(fn_val, args, ret)
259     }
260
261     #[inline(always)]
262     fn call_intrinsic(
263         ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
264         span: Span,
265         instance: ty::Instance<'tcx>,
266         args: &[OpTy<'tcx, Tag>],
267         ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
268         unwind: Option<mir::BasicBlock>,
269     ) -> InterpResult<'tcx> {
270         ecx.call_intrinsic(span, instance, args, ret, unwind)
271     }
272
273     #[inline(always)]
274     fn assert_panic(
275         ecx: &mut InterpCx<'mir, 'tcx, Self>,
276         span: Span,
277         msg: &mir::AssertMessage<'tcx>,
278         unwind: Option<mir::BasicBlock>,
279     ) -> InterpResult<'tcx> {
280         ecx.assert_panic(span, msg, unwind)
281     }
282
283     #[inline(always)]
284     fn binary_ptr_op(
285         ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
286         bin_op: mir::BinOp,
287         left: ImmTy<'tcx, Tag>,
288         right: ImmTy<'tcx, Tag>,
289     ) -> InterpResult<'tcx, (Scalar<Tag>, bool, Ty<'tcx>)> {
290         ecx.binary_ptr_op(bin_op, left, right)
291     }
292
293     fn box_alloc(
294         ecx: &mut InterpCx<'mir, 'tcx, Self>,
295         dest: PlaceTy<'tcx, Tag>,
296     ) -> InterpResult<'tcx> {
297         trace!("box_alloc for {:?}", dest.layout.ty);
298         let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
299         // First argument: `size`.
300         // (`0` is allowed here -- this is expected to be handled by the lang item).
301         let size = Scalar::from_uint(layout.size.bytes(), ecx.pointer_size());
302
303         // Second argument: `align`.
304         let align = Scalar::from_uint(layout.align.abi.bytes(), ecx.pointer_size());
305
306         // Call the `exchange_malloc` lang item.
307         let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
308         let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
309         ecx.call_function(
310             malloc,
311             &[size.into(), align.into()],
312             Some(dest),
313             // Don't do anything when we are done. The `statement()` function will increment
314             // the old stack frame's stmt counter to the next statement, which means that when
315             // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
316             StackPopCleanup::None { cleanup: true },
317         )?;
318         Ok(())
319     }
320
321     fn canonical_alloc_id(mem: &Memory<'mir, 'tcx, Self>, id: AllocId) -> AllocId {
322         let tcx = mem.tcx;
323         // Figure out if this is an extern static, and if yes, which one.
324         let def_id = match tcx.alloc_map.lock().get(id) {
325             Some(GlobalAlloc::Static(def_id)) if tcx.is_foreign_item(def_id) => def_id,
326             _ => {
327                 // No need to canonicalize anything.
328                 return id;
329             }
330         };
331         let attrs = tcx.get_attrs(def_id);
332         let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
333             Some(name) => name,
334             None => tcx.item_name(def_id),
335         };
336         // Check if we know this one.
337         if let Some(canonical_id) = mem.extra.extern_statics.get(&link_name) {
338             trace!("canonical_alloc_id: {:?} ({}) -> {:?}", id, link_name, canonical_id);
339             *canonical_id
340         } else {
341             // Return original id; `Memory::get_static_alloc` will throw an error.
342             id
343         }
344     }
345
346     fn init_allocation_extra<'b>(
347         memory_extra: &MemoryExtra<'tcx>,
348         id: AllocId,
349         alloc: Cow<'b, Allocation>,
350         kind: Option<MemoryKind<Self::MemoryKinds>>,
351     ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
352         if Some(id) == memory_extra.tracked_alloc_id {
353             register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
354         }
355
356         let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
357         let alloc = alloc.into_owned();
358         let (stacks, base_tag) =
359             if let Some(stacked_borrows) = memory_extra.stacked_borrows.as_ref() {
360                 let (stacks, base_tag) =
361                     Stacks::new_allocation(id, alloc.size, Rc::clone(stacked_borrows), kind);
362                 (Some(stacks), base_tag)
363             } else {
364                 // No stacks, no tag.
365                 (None, Tag::Untagged)
366             };
367         let mut stacked_borrows = memory_extra.stacked_borrows.as_ref().map(|sb| sb.borrow_mut());
368         let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
369             |alloc| {
370                 if let Some(stacked_borrows) = stacked_borrows.as_mut() {
371                     // Only statics may already contain pointers at this point
372                     assert_eq!(kind, MiriMemoryKind::Static.into());
373                     stacked_borrows.static_base_ptr(alloc)
374                 } else {
375                     Tag::Untagged
376                 }
377             },
378             AllocExtra { stacked_borrows: stacks },
379         );
380         (Cow::Owned(alloc), base_tag)
381     }
382
383     #[inline(always)]
384     fn tag_static_base_pointer(memory_extra: &MemoryExtra<'tcx>, id: AllocId) -> Self::PointerTag {
385         if let Some(stacked_borrows) = memory_extra.stacked_borrows.as_ref() {
386             stacked_borrows.borrow_mut().static_base_ptr(id)
387         } else {
388             Tag::Untagged
389         }
390     }
391
392     #[inline(always)]
393     fn retag(
394         ecx: &mut InterpCx<'mir, 'tcx, Self>,
395         kind: mir::RetagKind,
396         place: PlaceTy<'tcx, Tag>,
397     ) -> InterpResult<'tcx> {
398         if ecx.memory.extra.stacked_borrows.is_none() {
399             // No tracking.
400             Ok(())
401         } else {
402             ecx.retag(kind, place)
403         }
404     }
405
406     #[inline(always)]
407     fn stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx, FrameData<'tcx>> {
408         let stacked_borrows = ecx.memory.extra.stacked_borrows.as_ref();
409         let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
410             stacked_borrows.borrow_mut().new_call()
411         });
412         Ok(FrameData { call_id, catch_panic: None })
413     }
414
415     #[inline(always)]
416     fn stack_pop(
417         ecx: &mut InterpCx<'mir, 'tcx, Self>,
418         extra: FrameData<'tcx>,
419         unwinding: bool,
420     ) -> InterpResult<'tcx, StackPopInfo> {
421         ecx.handle_stack_pop(extra, unwinding)
422     }
423
424     #[inline(always)]
425     fn int_to_ptr(
426         memory: &Memory<'mir, 'tcx, Self>,
427         int: u64,
428     ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
429         intptrcast::GlobalState::int_to_ptr(int, memory)
430     }
431
432     #[inline(always)]
433     fn ptr_to_int(
434         memory: &Memory<'mir, 'tcx, Self>,
435         ptr: Pointer<Self::PointerTag>,
436     ) -> InterpResult<'tcx, u64> {
437         intptrcast::GlobalState::ptr_to_int(ptr, memory)
438     }
439 }
440
441 impl AllocationExtra<Tag> for AllocExtra {
442     #[inline(always)]
443     fn memory_read<'tcx>(
444         alloc: &Allocation<Tag, AllocExtra>,
445         ptr: Pointer<Tag>,
446         size: Size,
447     ) -> InterpResult<'tcx> {
448         if let Some(ref stacked_borrows) = alloc.extra.stacked_borrows {
449             stacked_borrows.memory_read(ptr, size)
450         } else {
451             Ok(())
452         }
453     }
454
455     #[inline(always)]
456     fn memory_written<'tcx>(
457         alloc: &mut Allocation<Tag, AllocExtra>,
458         ptr: Pointer<Tag>,
459         size: Size,
460     ) -> InterpResult<'tcx> {
461         if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
462             stacked_borrows.memory_written(ptr, size)
463         } else {
464             Ok(())
465         }
466     }
467
468     #[inline(always)]
469     fn memory_deallocated<'tcx>(
470         alloc: &mut Allocation<Tag, AllocExtra>,
471         ptr: Pointer<Tag>,
472         size: Size,
473     ) -> InterpResult<'tcx> {
474         if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
475             stacked_borrows.memory_deallocated(ptr, size)
476         } else {
477             Ok(())
478         }
479     }
480 }
481
482 impl MayLeak for MiriMemoryKind {
483     #[inline(always)]
484     fn may_leak(self) -> bool {
485         use self::MiriMemoryKind::*;
486         match self {
487             Rust | C | WinHeap => false,
488             Machine | Static => true,
489         }
490     }
491 }