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