]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/memory.rs
19d6c3ed66d00d83112514e50930aa672c3be455
[rust.git] / src / librustc_mir / interpret / memory.rs
1 use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian, BigEndian};
2 use std::collections::{btree_map, BTreeMap, HashMap, HashSet, VecDeque};
3 use std::{fmt, iter, ptr, mem, io, ops};
4
5 use rustc::ty;
6 use rustc::ty::layout::{self, TargetDataLayout, HasDataLayout};
7 use syntax::ast::Mutability;
8 use rustc::middle::region::CodeExtent;
9
10 use error::{EvalError, EvalResult};
11 use value::{PrimVal, Pointer};
12 use eval_context::EvalContext;
13
14 ////////////////////////////////////////////////////////////////////////////////
15 // Locks
16 ////////////////////////////////////////////////////////////////////////////////
17
18 mod range {
19     use super::*;
20
21     // The derived `Ord` impl sorts first by the first field, then, if the fields are the same,
22     // by the second field.
23     // This is exactly what we need for our purposes, since a range query on a BTReeSet/BTreeMap will give us all
24     // `MemoryRange`s whose `start` is <= than the one we're looking for, but not > the end of the range we're checking.
25     // At the same time the `end` is irrelevant for the sorting and range searching, but used for the check.
26     // This kind of search breaks, if `end < start`, so don't do that!
27     #[derive(Eq, PartialEq, Ord, PartialOrd, Debug)]
28     pub struct MemoryRange {
29         start: u64,
30         end: u64,
31     }
32
33     impl MemoryRange {
34         pub fn new(offset: u64, len: u64) -> MemoryRange {
35             assert!(len > 0);
36             MemoryRange {
37                 start: offset,
38                 end: offset + len,
39             }
40         }
41
42         pub fn offset(&self) -> u64 {
43             self.start
44         }
45
46         pub fn len(&self) -> u64 {
47             self.end - self.start
48         }
49
50         pub fn range(offset: u64, len: u64) -> ops::Range<MemoryRange> {
51             assert!(len > 0);
52             // We select all elements that are within
53             // the range given by the offset into the allocation and the length.
54             // This is sound if "self.contains() || self.overlaps() == true" implies that self is in-range.
55             let left = MemoryRange {
56                 start: 0,
57                 end: offset,
58             };
59             let right = MemoryRange {
60                 start: offset + len + 1,
61                 end: 0,
62             };
63             left..right
64         }
65
66         pub fn contains(&self, offset: u64, len: u64) -> bool {
67             assert!(len > 0);
68             self.start <= offset && (offset + len) <= self.end
69         }
70
71         pub fn overlaps(&self, offset: u64, len: u64) -> bool {
72             assert!(len > 0);
73             //let non_overlap = (offset + len) <= self.start || self.end <= offset;
74             (offset + len) > self.start && self.end > offset
75         }
76     }
77 }
78 use self::range::*;
79
80 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
81 pub enum AccessKind {
82     Read,
83     Write,
84 }
85
86 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
87 struct DynamicLifetime {
88     pub frame: usize,
89     pub region: Option<CodeExtent>, // "None" indicates "until the function ends"
90 }
91
92 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
93 enum LockStatus {
94     Held,
95     RecoverAfter(CodeExtent), // the frame is given by the surrounding LockInfo's lifetime.
96 }
97
98 /// Information about a lock that is or will be held.
99 #[derive(Copy, Clone, Debug)]
100 pub struct LockInfo {
101     kind: AccessKind,
102     lifetime: DynamicLifetime,
103     status: LockStatus,
104 }
105
106 impl LockInfo {
107     fn access_permitted(&self, frame: usize, access: AccessKind) -> bool {
108         use self::AccessKind::*;
109         match (self.kind, access) {
110             (Read, Read) => true, // Read access to read-locked region is okay, no matter who's holding the read lock.
111             (Write, _) if self.lifetime.frame == frame => true, // All access is okay when we hold the write lock.
112             _ => false, // Somebody else holding the write lock is not okay
113         }
114     }
115 }
116
117 ////////////////////////////////////////////////////////////////////////////////
118 // Allocations and pointers
119 ////////////////////////////////////////////////////////////////////////////////
120
121 #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
122 pub struct AllocId(pub u64);
123
124 impl fmt::Display for AllocId {
125     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
126         write!(f, "{}", self.0)
127     }
128 }
129
130 #[derive(Debug)]
131 pub struct Allocation {
132     /// The actual bytes of the allocation.
133     /// Note that the bytes of a pointer represent the offset of the pointer
134     pub bytes: Vec<u8>,
135     /// Maps from byte addresses to allocations.
136     /// Only the first byte of a pointer is inserted into the map.
137     pub relocations: BTreeMap<u64, AllocId>,
138     /// Denotes undefined memory. Reading from undefined memory is forbidden in miri
139     pub undef_mask: UndefMask,
140     /// The alignment of the allocation to detect unaligned reads.
141     pub align: u64,
142     /// Whether the allocation may be modified.
143     pub mutable: Mutability,
144     /// Use the `mark_static_initalized` method of `Memory` to ensure that an error occurs, if the memory of this
145     /// allocation is modified or deallocated in the future.
146     /// Helps guarantee that stack allocations aren't deallocated via `rust_deallocate`
147     pub kind: Kind,
148     /// Memory regions that are locked by some function
149     locks: BTreeMap<MemoryRange, Vec<LockInfo>>,
150 }
151
152 impl Allocation {
153     fn iter_locks<'a>(&'a self, offset: u64, len: u64) -> impl Iterator<Item=&'a LockInfo> + 'a {
154         self.locks.range(MemoryRange::range(offset, len))
155             .filter(move |&(range, _)| range.overlaps(offset, len))
156             .flat_map(|(_, locks)| locks.iter())
157     }
158
159     fn iter_lock_vecs_mut<'a>(&'a mut self, offset: u64, len: u64) -> impl Iterator<Item=(&'a MemoryRange, &'a mut Vec<LockInfo>)> + 'a {
160         self.locks.range_mut(MemoryRange::range(offset, len))
161             .filter(move |&(range, _)| range.overlaps(offset, len))
162     }
163
164     fn check_locks<'tcx>(&self, frame: usize, offset: u64, len: u64, access: AccessKind) -> Result<(), LockInfo> {
165         if len == 0 {
166             return Ok(())
167         }
168         for lock in self.iter_locks(offset, len) {
169             // Check if the lock is active, and is in conflict with the access.
170             if lock.status == LockStatus::Held && !lock.access_permitted(frame, access) {
171                 return Err(*lock);
172             }
173         }
174         Ok(())
175     }
176 }
177
178 #[derive(Debug, PartialEq, Copy, Clone)]
179 pub enum Kind {
180     /// Error if deallocated any other way than `rust_deallocate`
181     Rust,
182     /// Error if deallocated any other way than `free`
183     C,
184     /// Error if deallocated except during a stack pop
185     Stack,
186     /// Static in the process of being initialized.
187     /// The difference is important: An immutable static referring to a
188     /// mutable initialized static will freeze immutably and would not
189     /// be able to distinguish already initialized statics from uninitialized ones
190     UninitializedStatic,
191     /// May never be deallocated
192     Static,
193     /// Part of env var emulation
194     Env,
195 }
196
197 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
198 pub struct MemoryPointer {
199     pub alloc_id: AllocId,
200     pub offset: u64,
201 }
202
203 impl<'tcx> MemoryPointer {
204     pub fn new(alloc_id: AllocId, offset: u64) -> Self {
205         MemoryPointer { alloc_id, offset }
206     }
207
208     pub(crate) fn wrapping_signed_offset<C: HasDataLayout>(self, i: i64, cx: C) -> Self {
209         MemoryPointer::new(self.alloc_id, cx.data_layout().wrapping_signed_offset(self.offset, i))
210     }
211
212     pub(crate) fn overflowing_signed_offset<C: HasDataLayout>(self, i: i128, cx: C) -> (Self, bool) {
213         let (res, over) = cx.data_layout().overflowing_signed_offset(self.offset, i);
214         (MemoryPointer::new(self.alloc_id, res), over)
215     }
216
217     pub(crate) fn signed_offset<C: HasDataLayout>(self, i: i64, cx: C) -> EvalResult<'tcx, Self> {
218         Ok(MemoryPointer::new(self.alloc_id, cx.data_layout().signed_offset(self.offset, i)?))
219     }
220
221     pub(crate) fn overflowing_offset<C: HasDataLayout>(self, i: u64, cx: C) -> (Self, bool) {
222         let (res, over) = cx.data_layout().overflowing_offset(self.offset, i);
223         (MemoryPointer::new(self.alloc_id, res), over)
224     }
225
226     pub(crate) fn offset<C: HasDataLayout>(self, i: u64, cx: C) -> EvalResult<'tcx, Self> {
227         Ok(MemoryPointer::new(self.alloc_id, cx.data_layout().offset(self.offset, i)?))
228     }
229 }
230
231 ////////////////////////////////////////////////////////////////////////////////
232 // Top-level interpreter memory
233 ////////////////////////////////////////////////////////////////////////////////
234
235 pub type TlsKey = usize;
236
237 #[derive(Copy, Clone, Debug)]
238 pub struct TlsEntry<'tcx> {
239     data: Pointer, // Will eventually become a map from thread IDs to `Pointer`s, if we ever support more than one thread.
240     dtor: Option<ty::Instance<'tcx>>,
241 }
242
243 pub struct Memory<'a, 'tcx> {
244     /// Actual memory allocations (arbitrary bytes, may contain pointers into other allocations).
245     alloc_map: HashMap<AllocId, Allocation>,
246
247     /// The AllocId to assign to the next new allocation. Always incremented, never gets smaller.
248     next_id: AllocId,
249
250     /// Set of statics, constants, promoteds, vtables, ... to prevent `mark_static_initalized` from
251     /// stepping out of its own allocations. This set only contains statics backed by an
252     /// allocation. If they are ByVal or ByValPair they are not here, but will be inserted once
253     /// they become ByRef.
254     static_alloc: HashSet<AllocId>,
255
256     /// Number of virtual bytes allocated.
257     memory_usage: u64,
258
259     /// Maximum number of virtual bytes that may be allocated.
260     memory_size: u64,
261
262     /// Function "allocations". They exist solely so pointers have something to point to, and
263     /// we can figure out what they point to.
264     functions: HashMap<AllocId, ty::Instance<'tcx>>,
265
266     /// Inverse map of `functions` so we don't allocate a new pointer every time we need one
267     function_alloc_cache: HashMap<ty::Instance<'tcx>, AllocId>,
268
269     /// Target machine data layout to emulate.
270     pub layout: &'a TargetDataLayout,
271
272     /// A cache for basic byte allocations keyed by their contents. This is used to deduplicate
273     /// allocations for string and bytestring literals.
274     literal_alloc_cache: HashMap<Vec<u8>, AllocId>,
275
276     /// pthreads-style thread-local storage.
277     thread_local: BTreeMap<TlsKey, TlsEntry<'tcx>>,
278
279     /// The Key to use for the next thread-local allocation.
280     next_thread_local: TlsKey,
281
282     /// To avoid having to pass flags to every single memory access, we have some global state saying whether
283     /// alignment checking is currently enforced for read and/or write accesses.
284     reads_are_aligned: bool,
285     writes_are_aligned: bool,
286
287     /// The current stack frame.  Used to check accesses against locks.
288     cur_frame: usize,
289 }
290
291 impl<'a, 'tcx> Memory<'a, 'tcx> {
292     pub fn new(layout: &'a TargetDataLayout, max_memory: u64) -> Self {
293         Memory {
294             alloc_map: HashMap::new(),
295             functions: HashMap::new(),
296             function_alloc_cache: HashMap::new(),
297             next_id: AllocId(0),
298             layout,
299             memory_size: max_memory,
300             memory_usage: 0,
301             static_alloc: HashSet::new(),
302             literal_alloc_cache: HashMap::new(),
303             thread_local: BTreeMap::new(),
304             next_thread_local: 0,
305             reads_are_aligned: true,
306             writes_are_aligned: true,
307             cur_frame: usize::max_value(),
308         }
309     }
310
311     pub fn allocations(&self) -> ::std::collections::hash_map::Iter<AllocId, Allocation> {
312         self.alloc_map.iter()
313     }
314
315     pub fn create_fn_alloc(&mut self, instance: ty::Instance<'tcx>) -> MemoryPointer {
316         if let Some(&alloc_id) = self.function_alloc_cache.get(&instance) {
317             return MemoryPointer::new(alloc_id, 0);
318         }
319         let id = self.next_id;
320         debug!("creating fn ptr: {}", id);
321         self.next_id.0 += 1;
322         self.functions.insert(id, instance);
323         self.function_alloc_cache.insert(instance, id);
324         MemoryPointer::new(id, 0)
325     }
326
327     pub fn allocate_cached(&mut self, bytes: &[u8]) -> EvalResult<'tcx, MemoryPointer> {
328         if let Some(&alloc_id) = self.literal_alloc_cache.get(bytes) {
329             return Ok(MemoryPointer::new(alloc_id, 0));
330         }
331
332         let ptr = self.allocate(bytes.len() as u64, 1, Kind::UninitializedStatic)?;
333         self.write_bytes(ptr.into(), bytes)?;
334         self.mark_static_initalized(ptr.alloc_id, Mutability::Immutable)?;
335         self.literal_alloc_cache.insert(bytes.to_vec(), ptr.alloc_id);
336         Ok(ptr)
337     }
338
339     pub fn allocate(&mut self, size: u64, align: u64, kind: Kind) -> EvalResult<'tcx, MemoryPointer> {
340         assert_ne!(align, 0);
341         assert!(align.is_power_of_two());
342
343         if self.memory_size - self.memory_usage < size {
344             return Err(EvalError::OutOfMemory {
345                 allocation_size: size,
346                 memory_size: self.memory_size,
347                 memory_usage: self.memory_usage,
348             });
349         }
350         self.memory_usage += size;
351         assert_eq!(size as usize as u64, size);
352         let alloc = Allocation {
353             bytes: vec![0; size as usize],
354             relocations: BTreeMap::new(),
355             undef_mask: UndefMask::new(size),
356             align,
357             kind,
358             mutable: Mutability::Mutable,
359             locks: BTreeMap::new(),
360         };
361         let id = self.next_id;
362         self.next_id.0 += 1;
363         self.alloc_map.insert(id, alloc);
364         Ok(MemoryPointer::new(id, 0))
365     }
366
367     pub fn reallocate(&mut self, ptr: MemoryPointer, old_size: u64, old_align: u64, new_size: u64, new_align: u64, kind: Kind) -> EvalResult<'tcx, MemoryPointer> {
368         use std::cmp::min;
369
370         if ptr.offset != 0 {
371             return Err(EvalError::ReallocateNonBasePtr);
372         }
373         if let Ok(alloc) = self.get(ptr.alloc_id) {
374             if alloc.kind != kind {
375                 return Err(EvalError::ReallocatedWrongMemoryKind(alloc.kind, kind));
376             }
377         }
378
379         // For simplicities' sake, we implement reallocate as "alloc, copy, dealloc"
380         let new_ptr = self.allocate(new_size, new_align, kind)?;
381         self.copy(ptr.into(), new_ptr.into(), min(old_size, new_size), min(old_align, new_align), /*nonoverlapping*/true)?;
382         self.deallocate(ptr, Some((old_size, old_align)), kind)?;
383
384         Ok(new_ptr)
385     }
386
387     pub fn deallocate(&mut self, ptr: MemoryPointer, size_and_align: Option<(u64, u64)>, kind: Kind) -> EvalResult<'tcx> {
388         if ptr.offset != 0 {
389             return Err(EvalError::DeallocateNonBasePtr);
390         }
391
392         let alloc = match self.alloc_map.remove(&ptr.alloc_id) {
393             Some(alloc) => alloc,
394             None => return Err(EvalError::DoubleFree),
395         };
396
397         // It is okay for us to still holds locks on deallocation -- for example, we could store data we own
398         // in a local, and the local could be deallocated (from StorageDead) before the function returns.
399         // However, we should check *something*.  For now, we make sure that there is no conflicting write
400         // lock by another frame.  We *have* to permit deallocation if we hold a read lock.
401         // TODO: Figure out the exact rules here.
402         alloc.check_locks(self.cur_frame, 0, alloc.bytes.len() as u64, AccessKind::Read)
403             .map_err(|lock| EvalError::DeallocatedLockedMemory { ptr, lock })?;
404
405         if alloc.kind != kind {
406             return Err(EvalError::DeallocatedWrongMemoryKind(alloc.kind, kind));
407         }
408         if let Some((size, align)) = size_and_align {
409             if size != alloc.bytes.len() as u64 || align != alloc.align {
410                 return Err(EvalError::IncorrectAllocationInformation);
411             }
412         }
413
414         self.memory_usage -= alloc.bytes.len() as u64;
415         debug!("deallocated : {}", ptr.alloc_id);
416
417         Ok(())
418     }
419
420     pub fn pointer_size(&self) -> u64 {
421         self.layout.pointer_size.bytes()
422     }
423
424     pub fn endianess(&self) -> layout::Endian {
425         self.layout.endian
426     }
427
428     /// Check that the pointer is aligned AND non-NULL.
429     pub fn check_align(&self, ptr: Pointer, align: u64) -> EvalResult<'tcx> {
430         let offset = match ptr.into_inner_primval() {
431             PrimVal::Ptr(ptr) => {
432                 let alloc = self.get(ptr.alloc_id)?;
433                 if alloc.align < align {
434                     return Err(EvalError::AlignmentCheckFailed {
435                         has: alloc.align,
436                         required: align,
437                     });
438                 }
439                 ptr.offset
440             },
441             PrimVal::Bytes(bytes) => {
442                 let v = ((bytes as u128) % (1 << self.pointer_size())) as u64;
443                 if v == 0 {
444                     return Err(EvalError::InvalidNullPointerUsage);
445                 }
446                 v
447             },
448             PrimVal::Undef => return Err(EvalError::ReadUndefBytes),
449         };
450         if offset % align == 0 {
451             Ok(())
452         } else {
453             Err(EvalError::AlignmentCheckFailed {
454                 has: offset % align,
455                 required: align,
456             })
457         }
458     }
459
460     pub(crate) fn check_bounds(&self, ptr: MemoryPointer, access: bool) -> EvalResult<'tcx> {
461         let alloc = self.get(ptr.alloc_id)?;
462         let allocation_size = alloc.bytes.len() as u64;
463         if ptr.offset > allocation_size {
464             return Err(EvalError::PointerOutOfBounds { ptr, access, allocation_size });
465         }
466         Ok(())
467     }
468
469     pub(crate) fn set_cur_frame(&mut self, cur_frame: usize) {
470         self.cur_frame = cur_frame;
471     }
472
473     pub(crate) fn create_tls_key(&mut self, dtor: Option<ty::Instance<'tcx>>) -> TlsKey {
474         let new_key = self.next_thread_local;
475         self.next_thread_local += 1;
476         self.thread_local.insert(new_key, TlsEntry { data: Pointer::null(), dtor });
477         trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor);
478         return new_key;
479     }
480
481     pub(crate) fn delete_tls_key(&mut self, key: TlsKey) -> EvalResult<'tcx> {
482         return match self.thread_local.remove(&key) {
483             Some(_) => {
484                 trace!("TLS key {} removed", key);
485                 Ok(())
486             },
487             None => Err(EvalError::TlsOutOfBounds)
488         }
489     }
490
491     pub(crate) fn load_tls(&mut self, key: TlsKey) -> EvalResult<'tcx, Pointer> {
492         return match self.thread_local.get(&key) {
493             Some(&TlsEntry { data, .. }) => {
494                 trace!("TLS key {} loaded: {:?}", key, data);
495                 Ok(data)
496             },
497             None => Err(EvalError::TlsOutOfBounds)
498         }
499     }
500
501     pub(crate) fn store_tls(&mut self, key: TlsKey, new_data: Pointer) -> EvalResult<'tcx> {
502         return match self.thread_local.get_mut(&key) {
503             Some(&mut TlsEntry { ref mut data, .. }) => {
504                 trace!("TLS key {} stored: {:?}", key, new_data);
505                 *data = new_data;
506                 Ok(())
507             },
508             None => Err(EvalError::TlsOutOfBounds)
509         }
510     }
511     
512     /// Returns a dtor, its argument and its index, if one is supposed to run
513     ///
514     /// An optional destructor function may be associated with each key value.
515     /// At thread exit, if a key value has a non-NULL destructor pointer,
516     /// and the thread has a non-NULL value associated with that key,
517     /// the value of the key is set to NULL, and then the function pointed
518     /// to is called with the previously associated value as its sole argument.
519     /// The order of destructor calls is unspecified if more than one destructor
520     /// exists for a thread when it exits.
521     ///
522     /// If, after all the destructors have been called for all non-NULL values
523     /// with associated destructors, there are still some non-NULL values with
524     /// associated destructors, then the process is repeated.
525     /// If, after at least {PTHREAD_DESTRUCTOR_ITERATIONS} iterations of destructor
526     /// calls for outstanding non-NULL values, there are still some non-NULL values
527     /// with associated destructors, implementations may stop calling destructors,
528     /// or they may continue calling destructors until no non-NULL values with
529     /// associated destructors exist, even though this might result in an infinite loop.
530     pub(crate) fn fetch_tls_dtor(&mut self, key: Option<TlsKey>) -> EvalResult<'tcx, Option<(ty::Instance<'tcx>, Pointer, TlsKey)>> {
531         use std::collections::Bound::*;
532         let start = match key {
533             Some(key) => Excluded(key),
534             None => Unbounded,
535         };
536         for (&key, &mut TlsEntry { ref mut data, dtor }) in self.thread_local.range_mut((start, Unbounded)) {
537             if !data.is_null()? {
538                 if let Some(dtor) = dtor {
539                     let ret = Some((dtor, *data, key));
540                     *data = Pointer::null();
541                     return Ok(ret);
542                 }
543             }
544         }
545         return Ok(None);
546     }
547 }
548
549 /// Locking
550 impl<'a, 'tcx> Memory<'a, 'tcx> {
551     pub(crate) fn check_locks(&self, ptr: MemoryPointer, len: u64, access: AccessKind) -> EvalResult<'tcx> {
552         if len == 0 {
553             return Ok(())
554         }
555         let alloc = self.get(ptr.alloc_id)?;
556         alloc.check_locks(self.cur_frame, ptr.offset, len, access)
557             .map_err(|lock| EvalError::MemoryLockViolation { ptr, len, access, lock })
558     }
559
560     /// Acquire the lock for the given lifetime
561     pub(crate) fn acquire_lock(&mut self, ptr: MemoryPointer, len: u64, region: Option<CodeExtent>, kind: AccessKind) -> EvalResult<'tcx> {
562         assert!(len > 0);
563         trace!("Acquiring {:?} lock at {:?}, size {} for region {:?}", kind, ptr, len, region);
564         self.check_bounds(ptr.offset(len, self.layout)?, true)?; // if ptr.offset is in bounds, then so is ptr (because offset checks for overflow)
565         self.check_locks(ptr, len, kind)?; // make sure we have the access we are acquiring
566         let lifetime = DynamicLifetime { frame: self.cur_frame, region };
567         let alloc = self.get_mut_unchecked(ptr.alloc_id)?;
568         alloc.locks.entry(MemoryRange::new(ptr.offset, len)).or_insert_with(|| Vec::new()).push(LockInfo { lifetime, kind, status: LockStatus::Held });
569         Ok(())
570     }
571
572     /// Release a write lock prematurely. If there's just read locks, do nothing.
573     pub(crate) fn release_write_lock_until(&mut self, ptr: MemoryPointer, len: u64, release_until: Option<CodeExtent>) -> EvalResult<'tcx> {
574         assert!(len > 0);
575         let cur_frame = self.cur_frame;
576         let alloc = self.get_mut_unchecked(ptr.alloc_id)?;
577
578         for (range, locks) in alloc.iter_lock_vecs_mut(ptr.offset, len) {
579             if !range.contains(ptr.offset, len) {
580                 return Err(EvalError::Unimplemented(format!("miri does not support release part of a write-locked region")));
581             }
582
583             // Check all locks in this region; make sure there are no conflicting write locks of other frames.
584             // Also, if we will recover later, perform our release by changing the lock status.
585             for lock in locks.iter_mut() {
586                 if lock.kind == AccessKind::Read || lock.status != LockStatus::Held { continue; }
587                 if lock.lifetime.frame != cur_frame {
588                     return Err(EvalError::InvalidMemoryLockRelease { ptr, len });
589                 }
590                 let ptr = MemoryPointer { alloc_id : ptr.alloc_id, offset: range.offset() };
591                 trace!("Releasing write lock at {:?}, size {} until {:?}", ptr, range.len(), release_until);
592                 if let Some(region) = release_until {
593                     lock.status = LockStatus::RecoverAfter(region);
594                 }
595             }
596
597             // If we will not recove, we did not do anything above except for some checks. Now, erase the locks from the list.
598             if let None = release_until {
599                 // Delete everything that's a held write lock.  We already checked above that these are ours.
600                 // Unfortunately, this duplicates the condition from above.  Is there anything we can do about this?
601                 locks.retain(|lock| lock.kind == AccessKind::Read || lock.status != LockStatus::Held);
602             }
603         }
604
605         Ok(())
606     }
607
608     pub(crate) fn locks_lifetime_ended(&mut self, ending_region: Option<CodeExtent>) {
609         trace!("Releasing locks that expire at {:?}", ending_region);
610         let cur_frame = self.cur_frame;
611         let has_ended =  |lock: &LockInfo| -> bool {
612             if lock.lifetime.frame != cur_frame {
613                 return false;
614             }
615             match ending_region {
616                 None => true, // When a function ends, we end *all* its locks. It's okay for a function to still have lifetime-related locks
617                               // when it returns, that can happen e.g. with NLL when a lifetime can, but does not have to, extend beyond the
618                               // end of a function.
619                 Some(ending_region) => lock.lifetime.region == Some(ending_region),
620             }
621         };
622
623         for alloc in self.alloc_map.values_mut() {
624             for (_range, locks) in alloc.locks.iter_mut() {
625                 // Delete everything that ends now -- i.e., keep only all the other lifetimes.
626                 locks.retain(|lock| !has_ended(lock));
627                 // Activate locks that get recovered now
628                 if let Some(ending_region) = ending_region {
629                     for lock in locks.iter_mut() {
630                         if lock.lifetime.frame == cur_frame && lock.status == LockStatus::RecoverAfter(ending_region) {
631                             // FIXME: Check if this triggers a conflict between active locks
632                             lock.status = LockStatus::Held;
633                         }
634                     }
635                 }
636             }
637         }
638         // TODO: It may happen now that we leave empty vectors in the map.  Is it worth getting rid of them?
639     }
640 }
641
642 /// Allocation accessors
643 impl<'a, 'tcx> Memory<'a, 'tcx> {
644     pub fn get(&self, id: AllocId) -> EvalResult<'tcx, &Allocation> {
645         match self.alloc_map.get(&id) {
646             Some(alloc) => Ok(alloc),
647             None => match self.functions.get(&id) {
648                 Some(_) => Err(EvalError::DerefFunctionPointer),
649                 None => Err(EvalError::DanglingPointerDeref),
650             }
651         }
652     }
653     
654     fn get_mut_unchecked(&mut self, id: AllocId) -> EvalResult<'tcx, &mut Allocation> {
655         match self.alloc_map.get_mut(&id) {
656             Some(alloc) => Ok(alloc),
657             None => match self.functions.get(&id) {
658                 Some(_) => Err(EvalError::DerefFunctionPointer),
659                 None => Err(EvalError::DanglingPointerDeref),
660             }
661         }
662     }
663
664     pub fn get_mut(&mut self, id: AllocId) -> EvalResult<'tcx, &mut Allocation> {
665         let alloc = self.get_mut_unchecked(id)?;
666         if alloc.mutable == Mutability::Mutable {
667             Ok(alloc)
668         } else {
669             Err(EvalError::ModifiedConstantMemory)
670         }
671     }
672
673     pub fn get_fn(&self, ptr: MemoryPointer) -> EvalResult<'tcx, ty::Instance<'tcx>> {
674         if ptr.offset != 0 {
675             return Err(EvalError::InvalidFunctionPointer);
676         }
677         debug!("reading fn ptr: {}", ptr.alloc_id);
678         match self.functions.get(&ptr.alloc_id) {
679             Some(&fndef) => Ok(fndef),
680             None => match self.alloc_map.get(&ptr.alloc_id) {
681                 Some(_) => Err(EvalError::ExecuteMemory),
682                 None => Err(EvalError::InvalidFunctionPointer),
683             }
684         }
685     }
686
687     /// For debugging, print an allocation and all allocations it points to, recursively.
688     pub fn dump_alloc(&self, id: AllocId) {
689         self.dump_allocs(vec![id]);
690     }
691
692     /// For debugging, print a list of allocations and all allocations they point to, recursively.
693     pub fn dump_allocs(&self, mut allocs: Vec<AllocId>) {
694         use std::fmt::Write;
695         allocs.sort();
696         allocs.dedup();
697         let mut allocs_to_print = VecDeque::from(allocs);
698         let mut allocs_seen = HashSet::new();
699
700         while let Some(id) = allocs_to_print.pop_front() {
701             let mut msg = format!("Alloc {:<5} ", format!("{}:", id));
702             let prefix_len = msg.len();
703             let mut relocations = vec![];
704
705             let alloc = match (self.alloc_map.get(&id), self.functions.get(&id)) {
706                 (Some(a), None) => a,
707                 (None, Some(instance)) => {
708                     trace!("{} {}", msg, instance);
709                     continue;
710                 },
711                 (None, None) => {
712                     trace!("{} (deallocated)", msg);
713                     continue;
714                 },
715                 (Some(_), Some(_)) => bug!("miri invariant broken: an allocation id exists that points to both a function and a memory location"),
716             };
717
718             for i in 0..(alloc.bytes.len() as u64) {
719                 if let Some(&target_id) = alloc.relocations.get(&i) {
720                     if allocs_seen.insert(target_id) {
721                         allocs_to_print.push_back(target_id);
722                     }
723                     relocations.push((i, target_id));
724                 }
725                 if alloc.undef_mask.is_range_defined(i, i + 1) {
726                     // this `as usize` is fine, since `i` came from a `usize`
727                     write!(msg, "{:02x} ", alloc.bytes[i as usize]).unwrap();
728                 } else {
729                     msg.push_str("__ ");
730                 }
731             }
732
733             let immutable = match (alloc.kind, alloc.mutable) {
734                 (Kind::UninitializedStatic, _) => " (static in the process of initialization)",
735                 (Kind::Static, Mutability::Mutable) => " (static mut)",
736                 (Kind::Static, Mutability::Immutable) => " (immutable)",
737                 (Kind::Env, _) => " (env var)",
738                 (Kind::C, _) => " (malloc)",
739                 (Kind::Rust, _) => " (heap)",
740                 (Kind::Stack, _) => " (stack)",
741             };
742             trace!("{}({} bytes, alignment {}){}", msg, alloc.bytes.len(), alloc.align, immutable);
743
744             if !relocations.is_empty() {
745                 msg.clear();
746                 write!(msg, "{:1$}", "", prefix_len).unwrap(); // Print spaces.
747                 let mut pos = 0;
748                 let relocation_width = (self.pointer_size() - 1) * 3;
749                 for (i, target_id) in relocations {
750                     // this `as usize` is fine, since we can't print more chars than `usize::MAX`
751                     write!(msg, "{:1$}", "", ((i - pos) * 3) as usize).unwrap();
752                     let target = format!("({})", target_id);
753                     // this `as usize` is fine, since we can't print more chars than `usize::MAX`
754                     write!(msg, "â””{0:─^1$}┘ ", target, relocation_width as usize).unwrap();
755                     pos = i + self.pointer_size();
756                 }
757                 trace!("{}", msg);
758             }
759         }
760     }
761
762     pub fn leak_report(&self) -> usize {
763         trace!("### LEAK REPORT ###");
764         let leaks: Vec<_> = self.alloc_map
765             .iter()
766             .filter_map(|(&key, val)| {
767                 if val.kind != Kind::Static {
768                     Some(key)
769                 } else {
770                     None
771                 }
772             })
773             .collect();
774         let n = leaks.len();
775         self.dump_allocs(leaks);
776         n
777     }
778 }
779
780 /// Byte accessors
781 impl<'a, 'tcx> Memory<'a, 'tcx> {
782     fn get_bytes_unchecked(&self, ptr: MemoryPointer, size: u64, align: u64) -> EvalResult<'tcx, &[u8]> {
783         // Zero-sized accesses can use dangling pointers, but they still have to be aligned and non-NULL
784         if self.reads_are_aligned {
785             self.check_align(ptr.into(), align)?;
786         }
787         if size == 0 {
788             return Ok(&[]);
789         }
790         self.check_locks(ptr, size, AccessKind::Read)?;
791         self.check_bounds(ptr.offset(size, self)?, true)?; // if ptr.offset is in bounds, then so is ptr (because offset checks for overflow)
792         let alloc = self.get(ptr.alloc_id)?;
793         assert_eq!(ptr.offset as usize as u64, ptr.offset);
794         assert_eq!(size as usize as u64, size);
795         let offset = ptr.offset as usize;
796         Ok(&alloc.bytes[offset..offset + size as usize])
797     }
798
799     fn get_bytes_unchecked_mut(&mut self, ptr: MemoryPointer, size: u64, align: u64) -> EvalResult<'tcx, &mut [u8]> {
800         // Zero-sized accesses can use dangling pointers, but they still have to be aligned and non-NULL
801         if self.writes_are_aligned {
802             self.check_align(ptr.into(), align)?;
803         }
804         if size == 0 {
805             return Ok(&mut []);
806         }
807         self.check_locks(ptr, size, AccessKind::Write)?;
808         self.check_bounds(ptr.offset(size, self.layout)?, true)?; // if ptr.offset is in bounds, then so is ptr (because offset checks for overflow)
809         let alloc = self.get_mut(ptr.alloc_id)?;
810         assert_eq!(ptr.offset as usize as u64, ptr.offset);
811         assert_eq!(size as usize as u64, size);
812         let offset = ptr.offset as usize;
813         Ok(&mut alloc.bytes[offset..offset + size as usize])
814     }
815
816     fn get_bytes(&self, ptr: MemoryPointer, size: u64, align: u64) -> EvalResult<'tcx, &[u8]> {
817         assert_ne!(size, 0);
818         if self.relocations(ptr, size)?.count() != 0 {
819             return Err(EvalError::ReadPointerAsBytes);
820         }
821         self.check_defined(ptr, size)?;
822         self.get_bytes_unchecked(ptr, size, align)
823     }
824
825     fn get_bytes_mut(&mut self, ptr: MemoryPointer, size: u64, align: u64) -> EvalResult<'tcx, &mut [u8]> {
826         assert_ne!(size, 0);
827         self.clear_relocations(ptr, size)?;
828         self.mark_definedness(ptr.into(), size, true)?;
829         self.get_bytes_unchecked_mut(ptr, size, align)
830     }
831 }
832
833 /// Reading and writing
834 impl<'a, 'tcx> Memory<'a, 'tcx> {
835     /// mark an allocation as being the entry point to a static (see `static_alloc` field)
836     pub fn mark_static(&mut self, alloc_id: AllocId) {
837         trace!("mark_static: {:?}", alloc_id);
838         if !self.static_alloc.insert(alloc_id) {
839             bug!("tried to mark an allocation ({:?}) as static twice", alloc_id);
840         }
841     }
842
843     /// mark an allocation pointed to by a static as static and initialized
844     pub fn mark_inner_allocation(&mut self, alloc: AllocId, mutability: Mutability) -> EvalResult<'tcx> {
845         // relocations into other statics are not "inner allocations"
846         if !self.static_alloc.contains(&alloc) {
847             self.mark_static_initalized(alloc, mutability)?;
848         }
849         Ok(())
850     }
851
852     /// mark an allocation as static and initialized, either mutable or not
853     pub fn mark_static_initalized(&mut self, alloc_id: AllocId, mutability: Mutability) -> EvalResult<'tcx> {
854         trace!("mark_static_initalized {:?}, mutability: {:?}", alloc_id, mutability);
855         // do not use `self.get_mut(alloc_id)` here, because we might have already marked a
856         // sub-element or have circular pointers (e.g. `Rc`-cycles)
857         let relocations = match self.alloc_map.get_mut(&alloc_id) {
858             Some(&mut Allocation { ref mut relocations, ref mut kind, ref mut mutable, .. }) => {
859                 match *kind {
860                     // const eval results can refer to "locals".
861                     // E.g. `const Foo: &u32 = &1;` refers to the temp local that stores the `1`
862                     Kind::Stack |
863                     // The entire point of this function
864                     Kind::UninitializedStatic |
865                     // In the future const eval will allow heap allocations so we'll need to protect them
866                     // from deallocation, too
867                     Kind::Rust |
868                     Kind::C => {},
869                     Kind::Static => {
870                         trace!("mark_static_initalized: skipping already initialized static referred to by static currently being initialized");
871                         return Ok(());
872                     },
873                     // FIXME: This could be allowed, but not for env vars set during miri execution
874                     Kind::Env => return Err(EvalError::Unimplemented("statics can't refer to env vars".to_owned())),
875                 }
876                 *kind = Kind::Static;
877                 *mutable = mutability;
878                 // take out the relocations vector to free the borrow on self, so we can call
879                 // mark recursively
880                 mem::replace(relocations, Default::default())
881             },
882             None if !self.functions.contains_key(&alloc_id) => return Err(EvalError::DanglingPointerDeref),
883             _ => return Ok(()),
884         };
885         // recurse into inner allocations
886         for &alloc in relocations.values() {
887             self.mark_inner_allocation(alloc, mutability)?;
888         }
889         // put back the relocations
890         self.alloc_map.get_mut(&alloc_id).expect("checked above").relocations = relocations;
891         Ok(())
892     }
893
894     pub fn copy(&mut self, src: Pointer, dest: Pointer, size: u64, align: u64, nonoverlapping: bool) -> EvalResult<'tcx> {
895         if size == 0 {
896             // Empty accesses don't need to be valid pointers, but they should still be aligned
897             if self.reads_are_aligned {
898                 self.check_align(src, align)?;
899             }
900             if self.writes_are_aligned {
901                 self.check_align(dest, align)?;
902             }
903             return Ok(());
904         }
905         let src = src.to_ptr()?;
906         let dest = dest.to_ptr()?;
907         self.check_relocation_edges(src, size)?;
908
909         let src_bytes = self.get_bytes_unchecked(src, size, align)?.as_ptr();
910         let dest_bytes = self.get_bytes_mut(dest, size, align)?.as_mut_ptr();
911
912         // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
913         // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
914         // `dest` could possibly overlap.
915         unsafe {
916             assert_eq!(size as usize as u64, size);
917             if src.alloc_id == dest.alloc_id {
918                 if nonoverlapping {
919                     if (src.offset <= dest.offset && src.offset + size > dest.offset) ||
920                        (dest.offset <= src.offset && dest.offset + size > src.offset) {
921                         return Err(EvalError::Intrinsic(format!("copy_nonoverlapping called on overlapping ranges")));
922                     }
923                 }
924                 ptr::copy(src_bytes, dest_bytes, size as usize);
925             } else {
926                 ptr::copy_nonoverlapping(src_bytes, dest_bytes, size as usize);
927             }
928         }
929
930         self.copy_undef_mask(src, dest, size)?;
931         self.copy_relocations(src, dest, size)?;
932
933         Ok(())
934     }
935
936     pub fn read_c_str(&self, ptr: MemoryPointer) -> EvalResult<'tcx, &[u8]> {
937         let alloc = self.get(ptr.alloc_id)?;
938         assert_eq!(ptr.offset as usize as u64, ptr.offset);
939         let offset = ptr.offset as usize;
940         match alloc.bytes[offset..].iter().position(|&c| c == 0) {
941             Some(size) => {
942                 if self.relocations(ptr, (size + 1) as u64)?.count() != 0 {
943                     return Err(EvalError::ReadPointerAsBytes);
944                 }
945                 self.check_defined(ptr, (size + 1) as u64)?;
946                 self.check_locks(ptr, (size + 1) as u64, AccessKind::Read)?;
947                 Ok(&alloc.bytes[offset..offset + size])
948             },
949             None => Err(EvalError::UnterminatedCString(ptr)),
950         }
951     }
952
953     pub fn read_bytes(&self, ptr: Pointer, size: u64) -> EvalResult<'tcx, &[u8]> {
954         if size == 0 {
955             // Empty accesses don't need to be valid pointers, but they should still be non-NULL
956             if self.reads_are_aligned {
957                 self.check_align(ptr, 1)?;
958             }
959             return Ok(&[]);
960         }
961         self.get_bytes(ptr.to_ptr()?, size, 1)
962     }
963
964     pub fn write_bytes(&mut self, ptr: Pointer, src: &[u8]) -> EvalResult<'tcx> {
965         if src.is_empty() {
966             // Empty accesses don't need to be valid pointers, but they should still be non-NULL
967             if self.writes_are_aligned {
968                 self.check_align(ptr, 1)?;
969             }
970             return Ok(());
971         }
972         let bytes = self.get_bytes_mut(ptr.to_ptr()?, src.len() as u64, 1)?;
973         bytes.clone_from_slice(src);
974         Ok(())
975     }
976
977     pub fn write_repeat(&mut self, ptr: Pointer, val: u8, count: u64) -> EvalResult<'tcx> {
978         if count == 0 {
979             // Empty accesses don't need to be valid pointers, but they should still be non-NULL
980             if self.writes_are_aligned {
981                 self.check_align(ptr, 1)?;
982             }
983             return Ok(());
984         }
985         let bytes = self.get_bytes_mut(ptr.to_ptr()?, count, 1)?;
986         for b in bytes { *b = val; }
987         Ok(())
988     }
989
990     pub fn read_ptr(&self, ptr: MemoryPointer) -> EvalResult<'tcx, Pointer> {
991         let size = self.pointer_size();
992         self.check_relocation_edges(ptr, size)?; // Make sure we don't read part of a pointer as a pointer
993         let endianess = self.endianess();
994         let bytes = self.get_bytes_unchecked(ptr, size, size)?;
995         // Undef check happens *after* we established that the alignment is correct.
996         // We must not return Ok() for unaligned pointers!
997         if self.check_defined(ptr, size).is_err() {
998             return Ok(PrimVal::Undef.into());
999         }
1000         let offset = read_target_uint(endianess, bytes).unwrap();
1001         assert_eq!(offset as u64 as u128, offset);
1002         let offset = offset as u64;
1003         let alloc = self.get(ptr.alloc_id)?;
1004         match alloc.relocations.get(&ptr.offset) {
1005             Some(&alloc_id) => Ok(PrimVal::Ptr(MemoryPointer::new(alloc_id, offset)).into()),
1006             None => Ok(PrimVal::Bytes(offset as u128).into()),
1007         }
1008     }
1009
1010     pub fn write_ptr(&mut self, dest: MemoryPointer, ptr: MemoryPointer) -> EvalResult<'tcx> {
1011         self.write_usize(dest, ptr.offset as u64)?;
1012         self.get_mut(dest.alloc_id)?.relocations.insert(dest.offset, ptr.alloc_id);
1013         Ok(())
1014     }
1015
1016     pub fn write_primval(
1017         &mut self,
1018         dest: Pointer,
1019         val: PrimVal,
1020         size: u64,
1021     ) -> EvalResult<'tcx> {
1022         match val {
1023             PrimVal::Ptr(ptr) => {
1024                 assert_eq!(size, self.pointer_size());
1025                 self.write_ptr(dest.to_ptr()?, ptr)
1026             }
1027
1028             PrimVal::Bytes(bytes) => {
1029                 // We need to mask here, or the byteorder crate can die when given a u64 larger
1030                 // than fits in an integer of the requested size.
1031                 let mask = match size {
1032                     1 => !0u8 as u128,
1033                     2 => !0u16 as u128,
1034                     4 => !0u32 as u128,
1035                     8 => !0u64 as u128,
1036                     16 => !0,
1037                     n => bug!("unexpected PrimVal::Bytes size: {}", n),
1038                 };
1039                 self.write_uint(dest.to_ptr()?, bytes & mask, size)
1040             }
1041
1042             PrimVal::Undef => self.mark_definedness(dest, size, false),
1043         }
1044     }
1045
1046     pub fn read_bool(&self, ptr: MemoryPointer) -> EvalResult<'tcx, bool> {
1047         let bytes = self.get_bytes(ptr, 1, self.layout.i1_align.abi())?;
1048         match bytes[0] {
1049             0 => Ok(false),
1050             1 => Ok(true),
1051             _ => Err(EvalError::InvalidBool),
1052         }
1053     }
1054
1055     pub fn write_bool(&mut self, ptr: MemoryPointer, b: bool) -> EvalResult<'tcx> {
1056         let align = self.layout.i1_align.abi();
1057         self.get_bytes_mut(ptr, 1, align)
1058             .map(|bytes| bytes[0] = b as u8)
1059     }
1060
1061     fn int_align(&self, size: u64) -> EvalResult<'tcx, u64> {
1062         match size {
1063             1 => Ok(self.layout.i8_align.abi()),
1064             2 => Ok(self.layout.i16_align.abi()),
1065             4 => Ok(self.layout.i32_align.abi()),
1066             8 => Ok(self.layout.i64_align.abi()),
1067             16 => Ok(self.layout.i128_align.abi()),
1068             _ => bug!("bad integer size: {}", size),
1069         }
1070     }
1071
1072     pub fn read_int(&self, ptr: MemoryPointer, size: u64) -> EvalResult<'tcx, i128> {
1073         let align = self.int_align(size)?;
1074         self.get_bytes(ptr, size, align).map(|b| read_target_int(self.endianess(), b).unwrap())
1075     }
1076
1077     pub fn write_int(&mut self, ptr: MemoryPointer, n: i128, size: u64) -> EvalResult<'tcx> {
1078         let align = self.int_align(size)?;
1079         let endianess = self.endianess();
1080         let b = self.get_bytes_mut(ptr, size, align)?;
1081         write_target_int(endianess, b, n).unwrap();
1082         Ok(())
1083     }
1084
1085     pub fn read_uint(&self, ptr: MemoryPointer, size: u64) -> EvalResult<'tcx, u128> {
1086         let align = self.int_align(size)?;
1087         self.get_bytes(ptr, size, align).map(|b| read_target_uint(self.endianess(), b).unwrap())
1088     }
1089
1090     pub fn write_uint(&mut self, ptr: MemoryPointer, n: u128, size: u64) -> EvalResult<'tcx> {
1091         let align = self.int_align(size)?;
1092         let endianess = self.endianess();
1093         let b = self.get_bytes_mut(ptr, size, align)?;
1094         write_target_uint(endianess, b, n).unwrap();
1095         Ok(())
1096     }
1097
1098     pub fn read_isize(&self, ptr: MemoryPointer) -> EvalResult<'tcx, i64> {
1099         self.read_int(ptr, self.pointer_size()).map(|i| i as i64)
1100     }
1101
1102     pub fn write_isize(&mut self, ptr: MemoryPointer, n: i64) -> EvalResult<'tcx> {
1103         let size = self.pointer_size();
1104         self.write_int(ptr, n as i128, size)
1105     }
1106
1107     pub fn read_usize(&self, ptr: MemoryPointer) -> EvalResult<'tcx, u64> {
1108         self.read_uint(ptr, self.pointer_size()).map(|i| i as u64)
1109     }
1110
1111     pub fn write_usize(&mut self, ptr: MemoryPointer, n: u64) -> EvalResult<'tcx> {
1112         let size = self.pointer_size();
1113         self.write_uint(ptr, n as u128, size)
1114     }
1115
1116     pub fn write_f32(&mut self, ptr: MemoryPointer, f: f32) -> EvalResult<'tcx> {
1117         let endianess = self.endianess();
1118         let align = self.layout.f32_align.abi();
1119         let b = self.get_bytes_mut(ptr, 4, align)?;
1120         write_target_f32(endianess, b, f).unwrap();
1121         Ok(())
1122     }
1123
1124     pub fn write_f64(&mut self, ptr: MemoryPointer, f: f64) -> EvalResult<'tcx> {
1125         let endianess = self.endianess();
1126         let align = self.layout.f64_align.abi();
1127         let b = self.get_bytes_mut(ptr, 8, align)?;
1128         write_target_f64(endianess, b, f).unwrap();
1129         Ok(())
1130     }
1131
1132     pub fn read_f32(&self, ptr: MemoryPointer) -> EvalResult<'tcx, f32> {
1133         self.get_bytes(ptr, 4, self.layout.f32_align.abi())
1134             .map(|b| read_target_f32(self.endianess(), b).unwrap())
1135     }
1136
1137     pub fn read_f64(&self, ptr: MemoryPointer) -> EvalResult<'tcx, f64> {
1138         self.get_bytes(ptr, 8, self.layout.f64_align.abi())
1139             .map(|b| read_target_f64(self.endianess(), b).unwrap())
1140     }
1141 }
1142
1143 /// Relocations
1144 impl<'a, 'tcx> Memory<'a, 'tcx> {
1145     fn relocations(&self, ptr: MemoryPointer, size: u64)
1146         -> EvalResult<'tcx, btree_map::Range<u64, AllocId>>
1147     {
1148         let start = ptr.offset.saturating_sub(self.pointer_size() - 1);
1149         let end = ptr.offset + size;
1150         Ok(self.get(ptr.alloc_id)?.relocations.range(start..end))
1151     }
1152
1153     fn clear_relocations(&mut self, ptr: MemoryPointer, size: u64) -> EvalResult<'tcx> {
1154         // Find all relocations overlapping the given range.
1155         let keys: Vec<_> = self.relocations(ptr, size)?.map(|(&k, _)| k).collect();
1156         if keys.is_empty() { return Ok(()); }
1157
1158         // Find the start and end of the given range and its outermost relocations.
1159         let start = ptr.offset;
1160         let end = start + size;
1161         let first = *keys.first().unwrap();
1162         let last = *keys.last().unwrap() + self.pointer_size();
1163
1164         let alloc = self.get_mut(ptr.alloc_id)?;
1165
1166         // Mark parts of the outermost relocations as undefined if they partially fall outside the
1167         // given range.
1168         if first < start { alloc.undef_mask.set_range(first, start, false); }
1169         if last > end { alloc.undef_mask.set_range(end, last, false); }
1170
1171         // Forget all the relocations.
1172         for k in keys { alloc.relocations.remove(&k); }
1173
1174         Ok(())
1175     }
1176
1177     fn check_relocation_edges(&self, ptr: MemoryPointer, size: u64) -> EvalResult<'tcx> {
1178         let overlapping_start = self.relocations(ptr, 0)?.count();
1179         let overlapping_end = self.relocations(ptr.offset(size, self.layout)?, 0)?.count();
1180         if overlapping_start + overlapping_end != 0 {
1181             return Err(EvalError::ReadPointerAsBytes);
1182         }
1183         Ok(())
1184     }
1185
1186     fn copy_relocations(&mut self, src: MemoryPointer, dest: MemoryPointer, size: u64) -> EvalResult<'tcx> {
1187         let relocations: Vec<_> = self.relocations(src, size)?
1188             .map(|(&offset, &alloc_id)| {
1189                 // Update relocation offsets for the new positions in the destination allocation.
1190                 (offset + dest.offset - src.offset, alloc_id)
1191             })
1192             .collect();
1193         self.get_mut(dest.alloc_id)?.relocations.extend(relocations);
1194         Ok(())
1195     }
1196 }
1197
1198 /// Undefined bytes
1199 impl<'a, 'tcx> Memory<'a, 'tcx> {
1200     // FIXME(solson): This is a very naive, slow version.
1201     fn copy_undef_mask(&mut self, src: MemoryPointer, dest: MemoryPointer, size: u64) -> EvalResult<'tcx> {
1202         // The bits have to be saved locally before writing to dest in case src and dest overlap.
1203         assert_eq!(size as usize as u64, size);
1204         let mut v = Vec::with_capacity(size as usize);
1205         for i in 0..size {
1206             let defined = self.get(src.alloc_id)?.undef_mask.get(src.offset + i);
1207             v.push(defined);
1208         }
1209         for (i, defined) in v.into_iter().enumerate() {
1210             self.get_mut(dest.alloc_id)?.undef_mask.set(dest.offset + i as u64, defined);
1211         }
1212         Ok(())
1213     }
1214
1215     fn check_defined(&self, ptr: MemoryPointer, size: u64) -> EvalResult<'tcx> {
1216         let alloc = self.get(ptr.alloc_id)?;
1217         if !alloc.undef_mask.is_range_defined(ptr.offset, ptr.offset + size) {
1218             return Err(EvalError::ReadUndefBytes);
1219         }
1220         Ok(())
1221     }
1222
1223     pub fn mark_definedness(
1224         &mut self,
1225         ptr: Pointer,
1226         size: u64,
1227         new_state: bool
1228     ) -> EvalResult<'tcx> {
1229         if size == 0 {
1230             return Ok(())
1231         }
1232         let ptr = ptr.to_ptr()?;
1233         let mut alloc = self.get_mut(ptr.alloc_id)?;
1234         alloc.undef_mask.set_range(ptr.offset, ptr.offset + size, new_state);
1235         Ok(())
1236     }
1237 }
1238
1239 ////////////////////////////////////////////////////////////////////////////////
1240 // Methods to access integers in the target endianess
1241 ////////////////////////////////////////////////////////////////////////////////
1242
1243 fn write_target_uint(endianess: layout::Endian, mut target: &mut [u8], data: u128) -> Result<(), io::Error> {
1244     let len = target.len();
1245     match endianess {
1246         layout::Endian::Little => target.write_uint128::<LittleEndian>(data, len),
1247         layout::Endian::Big => target.write_uint128::<BigEndian>(data, len),
1248     }
1249 }
1250 fn write_target_int(endianess: layout::Endian, mut target: &mut [u8], data: i128) -> Result<(), io::Error> {
1251     let len = target.len();
1252     match endianess {
1253         layout::Endian::Little => target.write_int128::<LittleEndian>(data, len),
1254         layout::Endian::Big => target.write_int128::<BigEndian>(data, len),
1255     }
1256 }
1257
1258 fn read_target_uint(endianess: layout::Endian, mut source: &[u8]) -> Result<u128, io::Error> {
1259     match endianess {
1260         layout::Endian::Little => source.read_uint128::<LittleEndian>(source.len()),
1261         layout::Endian::Big => source.read_uint128::<BigEndian>(source.len()),
1262     }
1263 }
1264 fn read_target_int(endianess: layout::Endian, mut source: &[u8]) -> Result<i128, io::Error> {
1265     match endianess {
1266         layout::Endian::Little => source.read_int128::<LittleEndian>(source.len()),
1267         layout::Endian::Big => source.read_int128::<BigEndian>(source.len()),
1268     }
1269 }
1270
1271 ////////////////////////////////////////////////////////////////////////////////
1272 // Methods to access floats in the target endianess
1273 ////////////////////////////////////////////////////////////////////////////////
1274
1275 fn write_target_f32(endianess: layout::Endian, mut target: &mut [u8], data: f32) -> Result<(), io::Error> {
1276     match endianess {
1277         layout::Endian::Little => target.write_f32::<LittleEndian>(data),
1278         layout::Endian::Big => target.write_f32::<BigEndian>(data),
1279     }
1280 }
1281 fn write_target_f64(endianess: layout::Endian, mut target: &mut [u8], data: f64) -> Result<(), io::Error> {
1282     match endianess {
1283         layout::Endian::Little => target.write_f64::<LittleEndian>(data),
1284         layout::Endian::Big => target.write_f64::<BigEndian>(data),
1285     }
1286 }
1287
1288 fn read_target_f32(endianess: layout::Endian, mut source: &[u8]) -> Result<f32, io::Error> {
1289     match endianess {
1290         layout::Endian::Little => source.read_f32::<LittleEndian>(),
1291         layout::Endian::Big => source.read_f32::<BigEndian>(),
1292     }
1293 }
1294 fn read_target_f64(endianess: layout::Endian, mut source: &[u8]) -> Result<f64, io::Error> {
1295     match endianess {
1296         layout::Endian::Little => source.read_f64::<LittleEndian>(),
1297         layout::Endian::Big => source.read_f64::<BigEndian>(),
1298     }
1299 }
1300
1301 ////////////////////////////////////////////////////////////////////////////////
1302 // Undefined byte tracking
1303 ////////////////////////////////////////////////////////////////////////////////
1304
1305 type Block = u64;
1306 const BLOCK_SIZE: u64 = 64;
1307
1308 #[derive(Clone, Debug)]
1309 pub struct UndefMask {
1310     blocks: Vec<Block>,
1311     len: u64,
1312 }
1313
1314 impl UndefMask {
1315     fn new(size: u64) -> Self {
1316         let mut m = UndefMask {
1317             blocks: vec![],
1318             len: 0,
1319         };
1320         m.grow(size, false);
1321         m
1322     }
1323
1324     /// Check whether the range `start..end` (end-exclusive) is entirely defined.
1325     pub fn is_range_defined(&self, start: u64, end: u64) -> bool {
1326         if end > self.len { return false; }
1327         for i in start..end {
1328             if !self.get(i) { return false; }
1329         }
1330         true
1331     }
1332
1333     fn set_range(&mut self, start: u64, end: u64, new_state: bool) {
1334         let len = self.len;
1335         if end > len { self.grow(end - len, new_state); }
1336         self.set_range_inbounds(start, end, new_state);
1337     }
1338
1339     fn set_range_inbounds(&mut self, start: u64, end: u64, new_state: bool) {
1340         for i in start..end { self.set(i, new_state); }
1341     }
1342
1343     fn get(&self, i: u64) -> bool {
1344         let (block, bit) = bit_index(i);
1345         (self.blocks[block] & 1 << bit) != 0
1346     }
1347
1348     fn set(&mut self, i: u64, new_state: bool) {
1349         let (block, bit) = bit_index(i);
1350         if new_state {
1351             self.blocks[block] |= 1 << bit;
1352         } else {
1353             self.blocks[block] &= !(1 << bit);
1354         }
1355     }
1356
1357     fn grow(&mut self, amount: u64, new_state: bool) {
1358         let unused_trailing_bits = self.blocks.len() as u64 * BLOCK_SIZE - self.len;
1359         if amount > unused_trailing_bits {
1360             let additional_blocks = amount / BLOCK_SIZE + 1;
1361             assert_eq!(additional_blocks as usize as u64, additional_blocks);
1362             self.blocks.extend(iter::repeat(0).take(additional_blocks as usize));
1363         }
1364         let start = self.len;
1365         self.len += amount;
1366         self.set_range_inbounds(start, start + amount, new_state);
1367     }
1368 }
1369
1370 fn bit_index(bits: u64) -> (usize, usize) {
1371     let a = bits / BLOCK_SIZE;
1372     let b = bits % BLOCK_SIZE;
1373     assert_eq!(a as usize as u64, a);
1374     assert_eq!(b as usize as u64, b);
1375     (a as usize, b as usize)
1376 }
1377
1378 ////////////////////////////////////////////////////////////////////////////////
1379 // Unaligned accesses
1380 ////////////////////////////////////////////////////////////////////////////////
1381
1382 pub(crate) trait HasMemory<'a, 'tcx> {
1383     fn memory_mut(&mut self) -> &mut Memory<'a, 'tcx>;
1384     fn memory(&self) -> &Memory<'a, 'tcx>;
1385
1386     // These are not supposed to be overriden.
1387     fn read_maybe_aligned<F, T>(&mut self, aligned: bool, f: F) -> EvalResult<'tcx, T>
1388         where F: FnOnce(&mut Self) -> EvalResult<'tcx, T>
1389     {
1390         assert!(self.memory_mut().reads_are_aligned, "Unaligned reads must not be nested");
1391         self.memory_mut().reads_are_aligned = aligned;
1392         let t = f(self);
1393         self.memory_mut().reads_are_aligned = true;
1394         t
1395     }
1396
1397     fn write_maybe_aligned<F, T>(&mut self, aligned: bool, f: F) -> EvalResult<'tcx, T>
1398         where F: FnOnce(&mut Self) -> EvalResult<'tcx, T>
1399     {
1400         assert!(self.memory_mut().writes_are_aligned, "Unaligned writes must not be nested");
1401         self.memory_mut().writes_are_aligned = aligned;
1402         let t = f(self);
1403         self.memory_mut().writes_are_aligned = true;
1404         t
1405     }
1406 }
1407
1408 impl<'a, 'tcx> HasMemory<'a, 'tcx> for Memory<'a, 'tcx> {
1409     #[inline]
1410     fn memory_mut(&mut self) -> &mut Memory<'a, 'tcx> {
1411         self
1412     }
1413
1414     #[inline]
1415     fn memory(&self) -> &Memory<'a, 'tcx> {
1416         self
1417     }
1418 }
1419
1420 impl<'a, 'tcx> HasMemory<'a, 'tcx> for EvalContext<'a, 'tcx> {
1421     #[inline]
1422     fn memory_mut(&mut self) -> &mut Memory<'a, 'tcx> {
1423         &mut self.memory
1424     }
1425
1426     #[inline]
1427     fn memory(&self) -> &Memory<'a, 'tcx> {
1428         &self.memory
1429     }
1430 }
1431
1432 ////////////////////////////////////////////////////////////////////////////////
1433 // Pointer arithmetic
1434 ////////////////////////////////////////////////////////////////////////////////
1435
1436 pub trait PointerArithmetic : layout::HasDataLayout {
1437     // These are not supposed to be overriden.
1438
1439     //// Trunace the given value to the pointer size; also return whether there was an overflow
1440     fn truncate_to_ptr(self, val: u128) -> (u64, bool) {
1441         let max_ptr_plus_1 = 1u128 << self.data_layout().pointer_size.bits();
1442         ((val % max_ptr_plus_1) as u64, val >= max_ptr_plus_1)
1443     }
1444
1445     // Overflow checking only works properly on the range from -u64 to +u64.
1446     fn overflowing_signed_offset(self, val: u64, i: i128) -> (u64, bool) {
1447         // FIXME: is it possible to over/underflow here?
1448         if i < 0 {
1449             // trickery to ensure that i64::min_value() works fine
1450             // this formula only works for true negative values, it panics for zero!
1451             let n = u64::max_value() - (i as u64) + 1;
1452             val.overflowing_sub(n)
1453         } else {
1454             self.overflowing_offset(val, i as u64)
1455         }
1456     }
1457
1458     fn overflowing_offset(self, val: u64, i: u64) -> (u64, bool) {
1459         let (res, over1) = val.overflowing_add(i);
1460         let (res, over2) = self.truncate_to_ptr(res as u128);
1461         (res, over1 || over2)
1462     }
1463
1464     fn signed_offset<'tcx>(self, val: u64, i: i64) -> EvalResult<'tcx, u64> {
1465         let (res, over) = self.overflowing_signed_offset(val, i as i128);
1466         if over {
1467             Err(EvalError::OverflowingMath)
1468         } else {
1469             Ok(res)
1470         }
1471     }
1472
1473     fn offset<'tcx>(self, val: u64, i: u64) -> EvalResult<'tcx, u64> {
1474         let (res, over) = self.overflowing_offset(val, i);
1475         if over {
1476             Err(EvalError::OverflowingMath)
1477         } else {
1478             Ok(res)
1479         }
1480     }
1481
1482     fn wrapping_signed_offset(self, val: u64, i: i64) -> u64 {
1483         self.overflowing_signed_offset(val, i as i128).0
1484     }
1485 }
1486
1487 impl<T: layout::HasDataLayout> PointerArithmetic for T {}
1488
1489 impl<'a, 'tcx> layout::HasDataLayout for &'a Memory<'a, 'tcx> {
1490     #[inline]
1491     fn data_layout(&self) -> &TargetDataLayout {
1492         self.layout
1493     }
1494 }
1495 impl<'a, 'tcx> layout::HasDataLayout for &'a EvalContext<'a, 'tcx> {
1496     #[inline]
1497     fn data_layout(&self) -> &TargetDataLayout {
1498         self.memory().layout
1499     }
1500 }
1501
1502 impl<'c, 'b, 'a, 'tcx> layout::HasDataLayout for &'c &'b mut EvalContext<'a, 'tcx> {
1503     #[inline]
1504     fn data_layout(&self) -> &TargetDataLayout {
1505         self.memory().layout
1506     }
1507 }