memory.rs 36.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11 12 13 14 15 16 17 18
//! The memory subsystem.
//!
//! Generally, we use `Pointer` to denote memory addresses. However, some operations
//! have a "size"-like parameter, and they take `Scalar` for the address because
//! if the size is 0, then the pointer can also be a (properly aligned, non-NULL)
//! integer.  It is crucial that these operations call `check_align` *before*
//! short-circuiting the empty case!

19
use std::collections::VecDeque;
20
use std::hash::{Hash, Hasher};
21
use std::ptr;
22

23
use rustc::hir::def_id::DefId;
24
use rustc::ty::Instance;
25
use rustc::ty::ParamEnv;
26
use rustc::ty::query::TyCtxtAt;
27
use rustc::ty::layout::{self, Align, TargetDataLayout, Size};
R
Ralf Jung 已提交
28
use rustc::mir::interpret::{Pointer, AllocId, Allocation, AccessKind, ScalarMaybeUndef,
29 30
                            EvalResult, Scalar, EvalErrorKind, GlobalId, AllocType, truncate};
pub use rustc::mir::interpret::{write_target_uint, read_target_uint};
31
use rustc_data_structures::fx::{FxHashSet, FxHashMap, FxHasher};
32 33

use syntax::ast::Mutability;
34

O
Oliver Schneider 已提交
35
use super::{EvalContext, Machine};
36

37

S
Scott Olson 已提交
38 39 40 41
////////////////////////////////////////////////////////////////////////////////
// Allocations and pointers
////////////////////////////////////////////////////////////////////////////////

42
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
43
pub enum MemoryKind<T> {
O
Oliver Schneider 已提交
44
    /// Error if deallocated except during a stack pop
45
    Stack,
46 47
    /// Additional memory kinds a machine wishes to distinguish from the builtin ones
    Machine(T),
S
Scott Olson 已提交
48 49
}

50 51 52 53
////////////////////////////////////////////////////////////////////////////////
// Top-level interpreter memory
////////////////////////////////////////////////////////////////////////////////

54
#[derive(Clone)]
O
Oliver Schneider 已提交
55
pub struct Memory<'a, 'mir, 'tcx: 'a + 'mir, M: Machine<'mir, 'tcx>> {
56 57
    /// Additional data required by the Machine
    pub data: M::MemoryData,
R
Ralf Jung 已提交
58

O
Oliver Schneider 已提交
59
    /// Helps guarantee that stack allocations aren't deallocated via `rust_deallocate`
60
    alloc_kind: FxHashMap<AllocId, MemoryKind<M::MemoryKinds>>,
O
Oliver Schneider 已提交
61

S
Scott Olson 已提交
62
    /// Actual memory allocations (arbitrary bytes, may contain pointers into other allocations).
63
    alloc_map: FxHashMap<AllocId, Allocation>,
S
Scott Olson 已提交
64

65
    pub tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
S
Scott Olson 已提交
66 67
}

68 69 70 71 72 73 74 75 76 77 78 79 80 81
impl<'a, 'mir, 'tcx, M> Eq for Memory<'a, 'mir, 'tcx, M>
    where M: Machine<'mir, 'tcx>,
          'tcx: 'a + 'mir,
{}

impl<'a, 'mir, 'tcx, M> PartialEq for Memory<'a, 'mir, 'tcx, M>
    where M: Machine<'mir, 'tcx>,
          'tcx: 'a + 'mir,
{
    fn eq(&self, other: &Self) -> bool {
        let Memory {
            data,
            alloc_kind,
            alloc_map,
82
            tcx: _,
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
        } = self;

        *data == other.data
            && *alloc_kind == other.alloc_kind
            && *alloc_map == other.alloc_map
    }
}

impl<'a, 'mir, 'tcx, M> Hash for Memory<'a, 'mir, 'tcx, M>
    where M: Machine<'mir, 'tcx>,
          'tcx: 'a + 'mir,
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        let Memory {
            data,
            alloc_kind: _,
            alloc_map: _,
100
            tcx: _,
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
        } = self;

        data.hash(state);

        // We ignore some fields which don't change between evaluation steps.

        // Since HashMaps which contain the same items may have different
        // iteration orders, we use a commutative operation (in this case
        // addition, but XOR would also work), to combine the hash of each
        // `Allocation`.
        self.allocations()
            .map(|allocs| {
                let mut h = FxHasher::default();
                allocs.hash(&mut h);
                h.finish()
            })
            .fold(0u64, |hash, x| hash.wrapping_add(x))
            .hash(state);
    }
}

O
Oliver Schneider 已提交
122
impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
123
    pub fn new(tcx: TyCtxtAt<'a, 'tcx, 'tcx>, data: M::MemoryData) -> Self {
124
        Memory {
125
            data,
126 127
            alloc_kind: FxHashMap::default(),
            alloc_map: FxHashMap::default(),
O
Oliver Schneider 已提交
128
            tcx,
129
        }
130 131
    }

R
rustfmt  
Ralf Jung 已提交
132 133
    pub fn allocations<'x>(
        &'x self,
O
Oliver Schneider 已提交
134
    ) -> impl Iterator<Item = (AllocId, &'x Allocation)> {
135
        self.alloc_map.iter().map(|(&id, alloc)| (id, alloc))
136 137
    }

138
    pub fn create_fn_alloc(&mut self, instance: Instance<'tcx>) -> Pointer {
139
        self.tcx.alloc_map.lock().create_fn_alloc(instance).into()
O
Oliver Schneider 已提交
140 141
    }

142
    pub fn allocate_bytes(&mut self, bytes: &[u8]) -> Pointer {
143
        self.tcx.allocate_bytes(bytes).into()
144 145
    }

O
Oliver Schneider 已提交
146
    /// kind is `None` for statics
147
    pub fn allocate_value(
148
        &mut self,
149
        alloc: Allocation,
150
        kind: MemoryKind<M::MemoryKinds>,
151
    ) -> EvalResult<'tcx, AllocId> {
152
        let id = self.tcx.alloc_map.lock().reserve();
O
Oliver Schneider 已提交
153
        M::add_lock(self, id);
154 155
        self.alloc_map.insert(id, alloc);
        self.alloc_kind.insert(id, kind);
156 157 158 159 160 161
        Ok(id)
    }

    /// kind is `None` for statics
    pub fn allocate(
        &mut self,
162
        size: Size,
163
        align: Align,
164
        kind: MemoryKind<M::MemoryKinds>,
165
    ) -> EvalResult<'tcx, Pointer> {
166
        self.allocate_value(Allocation::undef(size, align), kind).map(Pointer::from)
167 168
    }

169 170
    pub fn reallocate(
        &mut self,
171
        ptr: Pointer,
172
        old_size: Size,
173
        old_align: Align,
174
        new_size: Size,
175
        new_align: Align,
176
        kind: MemoryKind<M::MemoryKinds>,
177
    ) -> EvalResult<'tcx, Pointer> {
178
        if ptr.offset.bytes() != 0 {
179
            return err!(ReallocateNonBasePtr);
180
        }
181 182
        if self.alloc_map.contains_key(&ptr.alloc_id) {
            let alloc_kind = self.alloc_kind[&ptr.alloc_id];
O
Oliver Schneider 已提交
183
            if alloc_kind != kind {
R
rustfmt  
Ralf Jung 已提交
184
                return err!(ReallocatedWrongMemoryKind(
O
Oliver Schneider 已提交
185
                    format!("{:?}", alloc_kind),
R
rustfmt  
Ralf Jung 已提交
186 187
                    format!("{:?}", kind),
                ));
188
            }
189
        }
190

R
Ralf Jung 已提交
191
        // For simplicities' sake, we implement reallocate as "alloc, copy, dealloc"
192
        let new_ptr = self.allocate(new_size, new_align, kind)?;
R
rustfmt  
Ralf Jung 已提交
193 194
        self.copy(
            ptr.into(),
195
            old_align,
R
rustfmt  
Ralf Jung 已提交
196
            new_ptr.into(),
197 198
            new_align,
            old_size.min(new_size),
R
rustfmt  
Ralf Jung 已提交
199 200 201
            /*nonoverlapping*/
            true,
        )?;
202
        self.deallocate(ptr, Some((old_size, old_align)), kind)?;
203

R
Ralf Jung 已提交
204
        Ok(new_ptr)
205 206
    }

207
    pub fn deallocate_local(&mut self, ptr: Pointer) -> EvalResult<'tcx> {
208
        match self.alloc_kind.get(&ptr.alloc_id).cloned() {
O
Oliver Schneider 已提交
209 210 211 212 213 214 215
            Some(MemoryKind::Stack) => self.deallocate(ptr, None, MemoryKind::Stack),
            // Happens if the memory was interned into immutable memory
            None => Ok(()),
            other => bug!("local contained non-stack memory: {:?}", other),
        }
    }

216 217
    pub fn deallocate(
        &mut self,
218
        ptr: Pointer,
219
        size_and_align: Option<(Size, Align)>,
220
        kind: MemoryKind<M::MemoryKinds>,
221
    ) -> EvalResult<'tcx> {
222
        if ptr.offset.bytes() != 0 {
223
            return err!(DeallocateNonBasePtr);
224
        }
225

226
        let alloc = match self.alloc_map.remove(&ptr.alloc_id) {
O
Oliver Schneider 已提交
227
            Some(alloc) => alloc,
228
            None => {
229 230 231 232 233 234 235 236 237 238 239 240 241
                return match self.tcx.alloc_map.lock().get(ptr.alloc_id) {
                    Some(AllocType::Function(..)) => err!(DeallocatedWrongMemoryKind(
                        "function".to_string(),
                        format!("{:?}", kind),
                    )),
                    Some(AllocType::Static(..)) |
                    Some(AllocType::Memory(..)) => err!(DeallocatedWrongMemoryKind(
                        "static".to_string(),
                        format!("{:?}", kind),
                    )),
                    None => err!(DoubleFree)
                }
            }
242 243
        };

244
        let alloc_kind = self.alloc_kind.remove(&ptr.alloc_id).expect("alloc_map out of sync with alloc_kind");
245

B
Bernardo Meurer 已提交
246 247 248 249 250 251
        // It is okay for us to still holds locks on deallocation -- for example, we could store
        // data we own in a local, and the local could be deallocated (from StorageDead) before the
        // function returns. However, we should check *something*.  For now, we make sure that there
        // is no conflicting write lock by another frame.  We *have* to permit deallocation if we
        // hold a read lock.
        // FIXME: Figure out the exact rules here.
252
        M::free_lock(self, ptr.alloc_id, alloc.bytes.len() as u64)?;
253

O
Oliver Schneider 已提交
254
        if alloc_kind != kind {
R
rustfmt  
Ralf Jung 已提交
255
            return err!(DeallocatedWrongMemoryKind(
O
Oliver Schneider 已提交
256
                format!("{:?}", alloc_kind),
R
rustfmt  
Ralf Jung 已提交
257 258
                format!("{:?}", kind),
            ));
259 260
        }
        if let Some((size, align)) = size_and_align {
261 262
            if size.bytes() != alloc.bytes.len() as u64 || align != alloc.align {
                return err!(IncorrectAllocationInformation(size, Size::from_bytes(alloc.bytes.len() as u64), align, alloc.align));
263
            }
264
        }
265

O
Oliver Schneider 已提交
266
        debug!("deallocated : {}", ptr.alloc_id);
267 268 269

        Ok(())
    }
270

271 272
    pub fn pointer_size(&self) -> Size {
        self.tcx.data_layout.pointer_size
273
    }
O
Oliver Schneider 已提交
274

275
    pub fn endianness(&self) -> layout::Endian {
O
Oliver Schneider 已提交
276
        self.tcx.data_layout.endian
O
Oliver Schneider 已提交
277
    }
278

279 280
    /// Check that the pointer is aligned AND non-NULL. This supports scalars
    /// for the benefit of other parts of miri that need to check alignment even for ZST.
281
    pub fn check_align(&self, ptr: Scalar, required_align: Align) -> EvalResult<'tcx> {
282
        // Check non-NULL/Undef, extract offset
283
        let (offset, alloc_align) = match ptr {
O
Oliver Schneider 已提交
284
            Scalar::Ptr(ptr) => {
285
                let alloc = self.get(ptr.alloc_id)?;
286
                (ptr.offset.bytes(), alloc.align)
R
rustfmt  
Ralf Jung 已提交
287
            }
288 289
            Scalar::Bits { bits, size } => {
                assert_eq!(size as u64, self.pointer_size().bytes());
290 291
                // FIXME: what on earth does this line do? docs or fix needed!
                let v = ((bits as u128) % (1 << self.pointer_size().bytes())) as u64;
292
                if v == 0 {
293
                    return err!(InvalidNullPointerUsage);
294
                }
295 296
                // the base address if the "integer allocation" is 0 and hence always aligned
                (v, required_align)
R
rustfmt  
Ralf Jung 已提交
297
            }
298
        };
299
        // Check alignment
300
        if alloc_align.abi() < required_align.abi() {
301
            return err!(AlignmentCheckFailed {
302 303
                has: alloc_align,
                required: required_align,
304 305
            });
        }
306
        if offset % required_align.abi() == 0 {
307 308
            Ok(())
        } else {
309
            let has = offset % required_align.abi();
310
            err!(AlignmentCheckFailed {
311 312
                has: Align::from_bytes(has, has).unwrap(),
                required: required_align,
313 314 315
            })
        }
    }
316

R
Ralf Jung 已提交
317 318 319
    /// Check if the pointer is "in-bounds". Notice that a pointer pointing at the end
    /// of an allocation (i.e., at the first *inaccessible* location) *is* considered
    /// in-bounds!  This follows C's/LLVM's rules.
320
    pub fn check_bounds(&self, ptr: Pointer, access: bool) -> EvalResult<'tcx> {
321 322
        let alloc = self.get(ptr.alloc_id)?;
        let allocation_size = alloc.bytes.len() as u64;
323
        if ptr.offset.bytes() > allocation_size {
R
rustfmt  
Ralf Jung 已提交
324 325 326
            return err!(PointerOutOfBounds {
                ptr,
                access,
327
                allocation_size: Size::from_bytes(allocation_size),
R
rustfmt  
Ralf Jung 已提交
328
            });
329 330 331
        }
        Ok(())
    }
O
Oliver Schneider 已提交
332
}
333

O
Oliver Schneider 已提交
334
/// Allocation accessors
O
Oliver Schneider 已提交
335
impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
336
    fn const_eval_static(&self, def_id: DefId) -> EvalResult<'tcx, &'tcx Allocation> {
337 338 339
        if self.tcx.is_foreign_item(def_id) {
            return err!(ReadForeignStatic);
        }
340 341 342 343 344
        let instance = Instance::mono(self.tcx.tcx, def_id);
        let gid = GlobalId {
            instance,
            promoted: None,
        };
345
        self.tcx.const_eval(ParamEnv::reveal_all().and(gid)).map_err(|err| {
346 347
            // no need to report anything, the const_eval call takes care of that for statics
            assert!(self.tcx.is_static(def_id).is_some());
348
            EvalErrorKind::ReferencedConstant(err).into()
349
        }).map(|val| {
R
Ralf Jung 已提交
350
            self.tcx.const_to_allocation(val)
351 352 353
        })
    }

O
Oliver Schneider 已提交
354 355
    pub fn get(&self, id: AllocId) -> EvalResult<'tcx, &Allocation> {
        // normal alloc?
356
        match self.alloc_map.get(&id) {
357
            Some(alloc) => Ok(alloc),
O
Oliver Schneider 已提交
358
            // uninitialized static alloc?
359 360 361 362 363 364 365 366 367 368
            None => {
                // static alloc?
                let alloc = self.tcx.alloc_map.lock().get(id);
                match alloc {
                    Some(AllocType::Memory(mem)) => Ok(mem),
                    Some(AllocType::Function(..)) => {
                        Err(EvalErrorKind::DerefFunctionPointer.into())
                    }
                    Some(AllocType::Static(did)) => {
                        self.const_eval_static(did)
369
                    }
370 371
                    None => Err(EvalErrorKind::DanglingPointerDeref.into()),
                }
O
Oliver Schneider 已提交
372
            },
373
        }
374
    }
R
rustfmt  
Ralf Jung 已提交
375

O
Oliver Schneider 已提交
376
    fn get_mut(
R
rustfmt  
Ralf Jung 已提交
377 378
        &mut self,
        id: AllocId,
O
Oliver Schneider 已提交
379 380
    ) -> EvalResult<'tcx, &mut Allocation> {
        // normal alloc?
381
        match self.alloc_map.get_mut(&id) {
O
Oliver Schneider 已提交
382 383
            Some(alloc) => Ok(alloc),
            // uninitialized static alloc?
384 385 386 387 388 389 390 391
            None => {
                // no alloc or immutable alloc? produce an error
                match self.tcx.alloc_map.lock().get(id) {
                    Some(AllocType::Memory(..)) |
                    Some(AllocType::Static(..)) => err!(ModifiedConstantMemory),
                    Some(AllocType::Function(..)) => err!(DerefFunctionPointer),
                    None => err!(DanglingPointerDeref),
                }
O
Oliver Schneider 已提交
392
            },
R
Ralf Jung 已提交
393 394 395
        }
    }

396
    pub fn get_fn(&self, ptr: Pointer) -> EvalResult<'tcx, Instance<'tcx>> {
397
        if ptr.offset.bytes() != 0 {
398
            return err!(InvalidFunctionPointer);
399 400
        }
        debug!("reading fn ptr: {}", ptr.alloc_id);
401 402 403 404
        match self.tcx.alloc_map.lock().get(ptr.alloc_id) {
            Some(AllocType::Function(instance)) => Ok(instance),
            _ => Err(EvalErrorKind::ExecuteMemory.into()),
        }
O
Oliver Schneider 已提交
405 406
    }

B
bjorn3 已提交
407 408 409 410
    pub fn get_alloc_kind(&self, id: AllocId) -> Option<MemoryKind<M::MemoryKinds>> {
        self.alloc_kind.get(&id).cloned()
    }

411 412
    /// For debugging, print an allocation and all allocations it points to, recursively.
    pub fn dump_alloc(&self, id: AllocId) {
413 414 415
        if !log_enabled!(::log::Level::Trace) {
            return;
        }
416 417 418 419 420
        self.dump_allocs(vec![id]);
    }

    /// For debugging, print a list of allocations and all allocations they point to, recursively.
    pub fn dump_allocs(&self, mut allocs: Vec<AllocId>) {
421 422 423
        if !log_enabled!(::log::Level::Trace) {
            return;
        }
424
        use std::fmt::Write;
425 426 427
        allocs.sort();
        allocs.dedup();
        let mut allocs_to_print = VecDeque::from(allocs);
428
        let mut allocs_seen = FxHashSet::default();
429 430

        while let Some(id) = allocs_to_print.pop_front() {
431 432
            let mut msg = format!("Alloc {:<5} ", format!("{}:", id));
            let prefix_len = msg.len();
433 434
            let mut relocations = vec![];

O
Oliver Schneider 已提交
435 436
            let (alloc, immutable) =
                // normal alloc?
437 438
                match self.alloc_map.get(&id) {
                    Some(a) => (a, match self.alloc_kind[&id] {
O
Oliver Schneider 已提交
439 440 441
                        MemoryKind::Stack => " (stack)".to_owned(),
                        MemoryKind::Machine(m) => format!(" ({:?})", m),
                    }),
442 443 444 445 446 447 448
                    None => {
                        // static alloc?
                        match self.tcx.alloc_map.lock().get(id) {
                            Some(AllocType::Memory(a)) => (a, "(immutable)".to_owned()),
                            Some(AllocType::Function(func)) => {
                                trace!("{} {}", msg, func);
                                continue;
O
Oliver Schneider 已提交
449
                            }
450 451 452 453 454 455 456 457 458
                            Some(AllocType::Static(did)) => {
                                trace!("{} {:?}", msg, did);
                                continue;
                            }
                            None => {
                                trace!("{} (deallocated)", msg);
                                continue;
                            }
                        }
O
Oliver Schneider 已提交
459
                    },
O
Oliver Schneider 已提交
460
                };
461

462
            for i in 0..(alloc.bytes.len() as u64) {
463
                let i = Size::from_bytes(i);
464
                if let Some(&target_id) = alloc.relocations.get(&i) {
S
Scott Olson 已提交
465
                    if allocs_seen.insert(target_id) {
466 467
                        allocs_to_print.push_back(target_id);
                    }
468
                    relocations.push((i, target_id));
469
                }
470
                if alloc.undef_mask.is_range_defined(i, i + Size::from_bytes(1)) {
471
                    // this `as usize` is fine, since `i` came from a `usize`
472
                    write!(msg, "{:02x} ", alloc.bytes[i.bytes() as usize]).unwrap();
473
                } else {
474
                    msg.push_str("__ ");
475 476
                }
            }
477

R
rustfmt  
Ralf Jung 已提交
478 479 480 481
            trace!(
                "{}({} bytes, alignment {}){}",
                msg,
                alloc.bytes.len(),
482
                alloc.align.abi(),
R
rustfmt  
Ralf Jung 已提交
483 484
                immutable
            );
485 486

            if !relocations.is_empty() {
487 488
                msg.clear();
                write!(msg, "{:1$}", "", prefix_len).unwrap(); // Print spaces.
489
                let mut pos = Size::ZERO;
490
                let relocation_width = (self.pointer_size().bytes() - 1) * 3;
491
                for (i, target_id) in relocations {
492
                    // this `as usize` is fine, since we can't print more chars than `usize::MAX`
493
                    write!(msg, "{:1$}", "", ((i - pos) * 3).bytes() as usize).unwrap();
O
Oliver Schneider 已提交
494
                    let target = format!("({})", target_id);
495 496
                    // this `as usize` is fine, since we can't print more chars than `usize::MAX`
                    write!(msg, "└{0:─^1$}┘ ", target, relocation_width as usize).unwrap();
497
                    pos = i + self.pointer_size();
498
                }
499
                trace!("{}", msg);
500 501 502
            }
        }
    }
O
Oliver Schneider 已提交
503 504 505 506

    pub fn leak_report(&self) -> usize {
        trace!("### LEAK REPORT ###");
        let leaks: Vec<_> = self.alloc_map
O
Oliver Schneider 已提交
507
            .keys()
O
Oliver Schneider 已提交
508
            .cloned()
O
Oliver Schneider 已提交
509 510 511 512 513
            .collect();
        let n = leaks.len();
        self.dump_allocs(leaks);
        n
    }
O
Oliver Schneider 已提交
514
}
515

O
Oliver Schneider 已提交
516
/// Byte accessors
O
Oliver Schneider 已提交
517
impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
518
    /// This checks alignment!
R
rustfmt  
Ralf Jung 已提交
519 520
    fn get_bytes_unchecked(
        &self,
521
        ptr: Pointer,
522
        size: Size,
523
        align: Align,
R
rustfmt  
Ralf Jung 已提交
524
    ) -> EvalResult<'tcx, &[u8]> {
B
Bernardo Meurer 已提交
525 526
        // Zero-sized accesses can use dangling pointers,
        // but they still have to be aligned and non-NULL
527
        self.check_align(ptr.into(), align)?;
528
        if size.bytes() == 0 {
R
Ralf Jung 已提交
529 530
            return Ok(&[]);
        }
O
Oliver Schneider 已提交
531
        M::check_locks(self, ptr, size, AccessKind::Read)?;
B
Bernardo Meurer 已提交
532 533
        // if ptr.offset is in bounds, then so is ptr (because offset checks for overflow)
        self.check_bounds(ptr.offset(size, self)?, true)?;
S
Scott Olson 已提交
534
        let alloc = self.get(ptr.alloc_id)?;
535 536 537 538
        assert_eq!(ptr.offset.bytes() as usize as u64, ptr.offset.bytes());
        assert_eq!(size.bytes() as usize as u64, size.bytes());
        let offset = ptr.offset.bytes() as usize;
        Ok(&alloc.bytes[offset..offset + size.bytes() as usize])
539 540
    }

541
    /// This checks alignment!
R
rustfmt  
Ralf Jung 已提交
542 543
    fn get_bytes_unchecked_mut(
        &mut self,
544
        ptr: Pointer,
545
        size: Size,
546
        align: Align,
R
rustfmt  
Ralf Jung 已提交
547
    ) -> EvalResult<'tcx, &mut [u8]> {
B
Bernardo Meurer 已提交
548 549
        // Zero-sized accesses can use dangling pointers,
        // but they still have to be aligned and non-NULL
550
        self.check_align(ptr.into(), align)?;
551
        if size.bytes() == 0 {
R
Ralf Jung 已提交
552 553
            return Ok(&mut []);
        }
O
Oliver Schneider 已提交
554
        M::check_locks(self, ptr, size, AccessKind::Write)?;
B
Bernardo Meurer 已提交
555 556
        // if ptr.offset is in bounds, then so is ptr (because offset checks for overflow)
        self.check_bounds(ptr.offset(size, &*self)?, true)?;
S
Scott Olson 已提交
557
        let alloc = self.get_mut(ptr.alloc_id)?;
558 559 560 561
        assert_eq!(ptr.offset.bytes() as usize as u64, ptr.offset.bytes());
        assert_eq!(size.bytes() as usize as u64, size.bytes());
        let offset = ptr.offset.bytes() as usize;
        Ok(&mut alloc.bytes[offset..offset + size.bytes() as usize])
562 563
    }

564
    fn get_bytes(&self, ptr: Pointer, size: Size, align: Align) -> EvalResult<'tcx, &[u8]> {
565
        assert_ne!(size.bytes(), 0);
566
        if self.relocations(ptr, size)?.len() != 0 {
567
            return err!(ReadPointerAsBytes);
S
Scott Olson 已提交
568
        }
S
Scott Olson 已提交
569
        self.check_defined(ptr, size)?;
O
Oliver Schneider 已提交
570
        self.get_bytes_unchecked(ptr, size, align)
571 572
    }

R
rustfmt  
Ralf Jung 已提交
573 574
    fn get_bytes_mut(
        &mut self,
575
        ptr: Pointer,
576
        size: Size,
577
        align: Align,
R
rustfmt  
Ralf Jung 已提交
578
    ) -> EvalResult<'tcx, &mut [u8]> {
579
        assert_ne!(size.bytes(), 0);
S
Scott Olson 已提交
580
        self.clear_relocations(ptr, size)?;
581
        self.mark_definedness(ptr, size, true)?;
O
Oliver Schneider 已提交
582
        self.get_bytes_unchecked_mut(ptr, size, align)
S
Scott Olson 已提交
583
    }
O
Oliver Schneider 已提交
584
}
S
Scott Olson 已提交
585

O
Oliver Schneider 已提交
586
/// Reading and writing
O
Oliver Schneider 已提交
587
impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
588
    /// mark an allocation pointed to by a static as static and initialized
589
    fn mark_inner_allocation_initialized(
R
rustfmt  
Ralf Jung 已提交
590 591 592 593
        &mut self,
        alloc: AllocId,
        mutability: Mutability,
    ) -> EvalResult<'tcx> {
594
        match self.alloc_kind.get(&alloc) {
O
Oliver Schneider 已提交
595
            // do not go into statics
O
Oliver Schneider 已提交
596
            None => Ok(()),
O
Oliver Schneider 已提交
597
            // just locals and machine allocs
598
            Some(_) => self.mark_static_initialized(alloc, mutability),
599 600 601
        }
    }

602
    /// mark an allocation as static and initialized, either mutable or not
603
    pub fn mark_static_initialized(
R
rustfmt  
Ralf Jung 已提交
604 605 606 607 608
        &mut self,
        alloc_id: AllocId,
        mutability: Mutability,
    ) -> EvalResult<'tcx> {
        trace!(
609
            "mark_static_initialized {:?}, mutability: {:?}",
R
rustfmt  
Ralf Jung 已提交
610 611 612
            alloc_id,
            mutability
        );
O
Oliver Schneider 已提交
613 614 615
        // The machine handled it
        if M::mark_static_initialized(self, alloc_id, mutability)? {
            return Ok(())
O
Oliver Schneider 已提交
616
        }
O
Oliver Schneider 已提交
617 618 619 620 621
        let alloc = self.alloc_map.remove(&alloc_id);
        match self.alloc_kind.remove(&alloc_id) {
            None => {},
            Some(MemoryKind::Machine(_)) => bug!("machine didn't handle machine alloc"),
            Some(MemoryKind::Stack) => {},
O
Oliver Schneider 已提交
622
        }
623
        if let Some(mut alloc) = alloc {
M
Matthias Krüger 已提交
624
            // ensure llvm knows not to put this into immutable memory
625
            alloc.runtime_mutability = mutability;
O
Oliver Schneider 已提交
626
            let alloc = self.tcx.intern_const_alloc(alloc);
627
            self.tcx.alloc_map.lock().set_id_memory(alloc_id, alloc);
O
Oliver Schneider 已提交
628 629 630
            // recurse into inner allocations
            for &alloc in alloc.relocations.values() {
                self.mark_inner_allocation_initialized(alloc, mutability)?;
R
rustfmt  
Ralf Jung 已提交
631
            }
O
Oliver Schneider 已提交
632 633
        } else {
            bug!("no allocation found for {:?}", alloc_id);
634
        }
635 636 637
        Ok(())
    }

R
rustfmt  
Ralf Jung 已提交
638 639
    pub fn copy(
        &mut self,
640
        src: Scalar,
641
        src_align: Align,
642
        dest: Scalar,
643
        dest_align: Align,
644
        size: Size,
R
rustfmt  
Ralf Jung 已提交
645
        nonoverlapping: bool,
646 647 648 649 650 651 652 653 654 655 656 657 658
    ) -> EvalResult<'tcx> {
        self.copy_repeatedly(src, src_align, dest, dest_align, size, 1, nonoverlapping)
    }

    pub fn copy_repeatedly(
        &mut self,
        src: Scalar,
        src_align: Align,
        dest: Scalar,
        dest_align: Align,
        size: Size,
        length: u64,
        nonoverlapping: bool,
R
rustfmt  
Ralf Jung 已提交
659
    ) -> EvalResult<'tcx> {
660
        if size.bytes() == 0 {
661 662 663
            // Nothing to do for ZST, other than checking alignment and non-NULLness.
            self.check_align(src, src_align)?;
            self.check_align(dest, dest_align)?;
664 665
            return Ok(());
        }
666 667
        let src = src.to_ptr()?;
        let dest = dest.to_ptr()?;
S
Scott Olson 已提交
668
        self.check_relocation_edges(src, size)?;
S
Scott Olson 已提交
669

670 671 672
        // first copy the relocations to a temporary buffer, because
        // `get_bytes_mut` will clear the relocations, which is correct,
        // since we don't want to keep any relocations at the target.
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
        let relocations = {
            let relocations = self.relocations(src, size)?;
            let mut new_relocations = Vec::with_capacity(relocations.len() * (length as usize));
            for i in 0..length {
                new_relocations.extend(
                    relocations
                    .iter()
                    .map(|&(offset, alloc_id)| {
                    (offset + dest.offset - src.offset + (i * size * relocations.len() as u64), alloc_id)
                    })
                );
            }

            new_relocations
        };
688

689
        // This also checks alignment.
690
        let src_bytes = self.get_bytes_unchecked(src, size, src_align)?.as_ptr();
691
        let dest_bytes = self.get_bytes_mut(dest, size * length, dest_align)?.as_mut_ptr();
692 693 694 695 696

        // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
        // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
        // `dest` could possibly overlap.
        unsafe {
697
            assert_eq!(size.bytes() as usize as u64, size.bytes());
698
            if src.alloc_id == dest.alloc_id {
699 700
                if nonoverlapping {
                    if (src.offset <= dest.offset && src.offset + size > dest.offset) ||
R
rustfmt  
Ralf Jung 已提交
701 702 703
                        (dest.offset <= src.offset && dest.offset + size > src.offset)
                    {
                        return err!(Intrinsic(
L
ljedrz 已提交
704
                            "copy_nonoverlapping called on overlapping ranges".to_string(),
R
rustfmt  
Ralf Jung 已提交
705
                        ));
706 707
                    }
                }
708 709 710 711

                for i in 0..length {
                    ptr::copy(src_bytes, dest_bytes.offset((size.bytes() * i) as isize), size.bytes() as usize);
                }
712
            } else {
713 714 715
                for i in 0..length {
                    ptr::copy_nonoverlapping(src_bytes, dest_bytes.offset((size.bytes() * i) as isize), size.bytes() as usize);
                }
716 717 718
            }
        }

719
        self.copy_undef_mask(src, dest, size, length)?;
720
        // copy back the relocations
721
        self.get_mut(dest.alloc_id)?.relocations.insert_presorted(relocations);
722 723

        Ok(())
724 725
    }

726
    pub fn read_c_str(&self, ptr: Pointer) -> EvalResult<'tcx, &[u8]> {
727
        let alloc = self.get(ptr.alloc_id)?;
728 729
        assert_eq!(ptr.offset.bytes() as usize as u64, ptr.offset.bytes());
        let offset = ptr.offset.bytes() as usize;
730 731
        match alloc.bytes[offset..].iter().position(|&c| c == 0) {
            Some(size) => {
732
                let p1 = Size::from_bytes((size + 1) as u64);
733
                if self.relocations(ptr, p1)?.len() != 0 {
734
                    return err!(ReadPointerAsBytes);
735
                }
736 737
                self.check_defined(ptr, p1)?;
                M::check_locks(self, ptr, p1, AccessKind::Read)?;
738
                Ok(&alloc.bytes[offset..offset + size])
R
rustfmt  
Ralf Jung 已提交
739
            }
740
            None => err!(UnterminatedCString(ptr)),
741 742 743
        }
    }

744
    pub fn read_bytes(&self, ptr: Scalar, size: Size) -> EvalResult<'tcx, &[u8]> {
745
        // Empty accesses don't need to be valid pointers, but they should still be non-NULL
746
        let align = Align::from_bytes(1, 1).unwrap();
747
        if size.bytes() == 0 {
748
            self.check_align(ptr, align)?;
749 750
            return Ok(&[]);
        }
751
        self.get_bytes(ptr.to_ptr()?, size, align)
752 753
    }

754
    pub fn write_bytes(&mut self, ptr: Scalar, src: &[u8]) -> EvalResult<'tcx> {
755
        // Empty accesses don't need to be valid pointers, but they should still be non-NULL
756
        let align = Align::from_bytes(1, 1).unwrap();
757
        if src.is_empty() {
758
            self.check_align(ptr, align)?;
759 760
            return Ok(());
        }
761
        let bytes = self.get_bytes_mut(ptr.to_ptr()?, Size::from_bytes(src.len() as u64), align)?;
S
Scott Olson 已提交
762 763 764 765
        bytes.clone_from_slice(src);
        Ok(())
    }

766
    pub fn write_repeat(&mut self, ptr: Scalar, val: u8, count: Size) -> EvalResult<'tcx> {
767
        // Empty accesses don't need to be valid pointers, but they should still be non-NULL
768
        let align = Align::from_bytes(1, 1).unwrap();
769
        if count.bytes() == 0 {
770
            self.check_align(ptr, align)?;
771 772
            return Ok(());
        }
773
        let bytes = self.get_bytes_mut(ptr.to_ptr()?, count, align)?;
R
rustfmt  
Ralf Jung 已提交
774 775 776
        for b in bytes {
            *b = val;
        }
S
Scott Olson 已提交
777 778 779
        Ok(())
    }

780
    /// Read a *non-ZST* scalar
781
    pub fn read_scalar(&self, ptr: Pointer, ptr_align: Align, size: Size) -> EvalResult<'tcx, ScalarMaybeUndef> {
B
Bernardo Meurer 已提交
782 783
        // Make sure we don't read part of a pointer as a pointer
        self.check_relocation_edges(ptr, size)?;
784
        let endianness = self.endianness();
785
        // get_bytes_unchecked tests alignment
786
        let bytes = self.get_bytes_unchecked(ptr, size, ptr_align.min(self.int_align(size)))?;
787 788 789
        // Undef check happens *after* we established that the alignment is correct.
        // We must not return Ok() for unaligned pointers!
        if self.check_defined(ptr, size).is_err() {
B
Bernardo Meurer 已提交
790 791
            // this inflates undefined bytes to the entire scalar,
            // even if only a few bytes are undefined
792
            return Ok(ScalarMaybeUndef::Undef);
793
        }
794
        // Now we do the actual reading
795
        let bits = read_target_uint(endianness, bytes).unwrap();
796 797
        // See if we got a pointer
        if size != self.pointer_size() {
798
            if self.relocations(ptr, size)?.len() != 0 {
799 800 801 802 803
                return err!(ReadPointerAsBytes);
            }
        } else {
            let alloc = self.get(ptr.alloc_id)?;
            match alloc.relocations.get(&ptr.offset) {
804
                Some(&alloc_id) => return Ok(ScalarMaybeUndef::Scalar(Pointer::new(alloc_id, Size::from_bytes(bits as u64)).into())),
805 806
                None => {},
            }
807
        }
808
        // We don't. Just return the bits.
809
        Ok(ScalarMaybeUndef::Scalar(Scalar::Bits {
810
            bits,
811 812
            size: size.bytes() as u8,
        }))
813 814
    }

815
    pub fn read_ptr_sized(&self, ptr: Pointer, ptr_align: Align) -> EvalResult<'tcx, ScalarMaybeUndef> {
O
Oliver Schneider 已提交
816
        self.read_scalar(ptr, ptr_align, self.pointer_size())
S
Scott Olson 已提交
817 818
    }

819
    /// Write a *non-ZST* scalar
820 821
    pub fn write_scalar(
        &mut self,
822
        ptr: Pointer,
823 824 825 826
        ptr_align: Align,
        val: ScalarMaybeUndef,
        type_size: Size,
    ) -> EvalResult<'tcx> {
827
        let endianness = self.endianness();
S
Scott Olson 已提交
828

829 830 831 832 833
        let val = match val {
            ScalarMaybeUndef::Scalar(scalar) => scalar,
            ScalarMaybeUndef::Undef => return self.mark_definedness(ptr, type_size, false),
        };

834
        let bytes = match val {
O
Oliver Schneider 已提交
835
            Scalar::Ptr(val) => {
836
                assert_eq!(type_size, self.pointer_size());
837
                val.offset.bytes() as u128
838 839
            }

840 841
            Scalar::Bits { bits, size } => {
                assert_eq!(size as u64, type_size.bytes());
842 843
                assert_eq!(truncate(bits, Size::from_bytes(size.into())), bits,
                    "Unexpected value of size {} when writing to memory", size);
844 845
                bits
            },
846 847 848
        };

        {
849 850
            // get_bytes_mut checks alignment
            let dst = self.get_bytes_mut(ptr, type_size, ptr_align)?;
851
            write_target_uint(endianness, dst, bytes).unwrap();
852 853 854 855
        }

        // See if we have to also write a relocation
        match val {
O
Oliver Schneider 已提交
856
            Scalar::Ptr(val) => {
857 858 859 860 861 862
                self.get_mut(ptr.alloc_id)?.relocations.insert(
                    ptr.offset,
                    val.alloc_id,
                );
            }
            _ => {}
863
        }
864 865 866 867

        Ok(())
    }

868
    pub fn write_ptr_sized(&mut self, ptr: Pointer, ptr_align: Align, val: ScalarMaybeUndef) -> EvalResult<'tcx> {
869
        let ptr_size = self.pointer_size();
870
        self.write_scalar(ptr.into(), ptr_align, val, ptr_size)
S
Scott Olson 已提交
871 872
    }

873
    fn int_align(&self, size: Size) -> Align {
874
        // We assume pointer-sized integers have the same alignment as pointers.
875
        // We also assume signed and unsigned integers of the same size have the same alignment.
876
        let ity = match size.bytes() {
877 878 879 880 881
            1 => layout::I8,
            2 => layout::I16,
            4 => layout::I32,
            8 => layout::I64,
            16 => layout::I128,
882
            _ => bug!("bad integer size: {}", size.bytes()),
883 884
        };
        ity.align(self)
885
    }
O
Oliver Schneider 已提交
886
}
887

O
Oliver Schneider 已提交
888
/// Relocations
O
Oliver Schneider 已提交
889
impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
R
rustfmt  
Ralf Jung 已提交
890 891
    fn relocations(
        &self,
892
        ptr: Pointer,
893
        size: Size,
894
    ) -> EvalResult<'tcx, &[(Size, AllocId)]> {
895
        let start = ptr.offset.bytes().saturating_sub(self.pointer_size().bytes() - 1);
896
        let end = ptr.offset + size;
897
        Ok(self.get(ptr.alloc_id)?.relocations.range(Size::from_bytes(start)..end))
898 899
    }

900
    fn clear_relocations(&mut self, ptr: Pointer, size: Size) -> EvalResult<'tcx> {
901
        // Find the start and end of the given range and its outermost relocations.
902 903 904 905 906 907 908 909 910 911
        let (first, last) = {
            // Find all relocations overlapping the given range.
            let relocations = self.relocations(ptr, size)?;
            if relocations.is_empty() {
                return Ok(());
            }

            (relocations.first().unwrap().0,
             relocations.last().unwrap().0 + self.pointer_size())
        };
912 913 914
        let start = ptr.offset;
        let end = start + size;

S
Scott Olson 已提交
915
        let alloc = self.get_mut(ptr.alloc_id)?;
916 917 918

        // Mark parts of the outermost relocations as undefined if they partially fall outside the
        // given range.
R
rustfmt  
Ralf Jung 已提交
919 920 921 922 923 924
        if first < start {
            alloc.undef_mask.set_range(first, start, false);
        }
        if last > end {
            alloc.undef_mask.set_range(end, last, false);
        }
925 926

        // Forget all the relocations.
O
Oliver Schneider 已提交
927
        alloc.relocations.remove_range(first..last);
928

S
Scott Olson 已提交
929 930 931
        Ok(())
    }

932
    fn check_relocation_edges(&self, ptr: Pointer, size: Size) -> EvalResult<'tcx> {
933 934
        let overlapping_start = self.relocations(ptr, Size::ZERO)?.len();
        let overlapping_end = self.relocations(ptr.offset(size, self)?, Size::ZERO)?.len();
S
Scott Olson 已提交
935
        if overlapping_start + overlapping_end != 0 {
936
            return err!(ReadPointerAsBytes);
S
Scott Olson 已提交
937 938 939
        }
        Ok(())
    }
O
Oliver Schneider 已提交
940
}
S
Scott Olson 已提交
941

O
Oliver Schneider 已提交
942
/// Undefined bytes
O
Oliver Schneider 已提交
943
impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
944
    // FIXME(solson): This is a very naive, slow version.
R
rustfmt  
Ralf Jung 已提交
945 946
    fn copy_undef_mask(
        &mut self,
947 948
        src: Pointer,
        dest: Pointer,
949
        size: Size,
950
        repeat: u64,
R
rustfmt  
Ralf Jung 已提交
951
    ) -> EvalResult<'tcx> {
952
        // The bits have to be saved locally before writing to dest in case src and dest overlap.
953
        assert_eq!(size.bytes() as usize as u64, size.bytes());
954

955 956
        let undef_mask = self.get(src.alloc_id)?.undef_mask.clone();
        let dest_allocation = self.get_mut(dest.alloc_id)?;
957

958
        for i in 0..size.bytes() {
959
            let defined = undef_mask.get(src.offset + Size::from_bytes(i));
960

961 962 963 964 965 966
            for j in 0..repeat {
                dest_allocation.undef_mask.set(
                    dest.offset + Size::from_bytes(i + (size.bytes() * j)),
                    defined
                );
            }
967
        }
968

969 970 971
        Ok(())
    }

972
    fn check_defined(&self, ptr: Pointer, size: Size) -> EvalResult<'tcx> {
S
Scott Olson 已提交
973
        let alloc = self.get(ptr.alloc_id)?;
R
rustfmt  
Ralf Jung 已提交
974 975 976 977 978
        if !alloc.undef_mask.is_range_defined(
            ptr.offset,
            ptr.offset + size,
        )
        {
979
            return err!(ReadUndefBytes);
980 981 982 983
        }
        Ok(())
    }

984 985
    pub fn mark_definedness(
        &mut self,
986
        ptr: Pointer,
987
        size: Size,
R
rustfmt  
Ralf Jung 已提交
988
        new_state: bool,
989
    ) -> EvalResult<'tcx> {
990
        if size.bytes() == 0 {
R
rustfmt  
Ralf Jung 已提交
991
            return Ok(());
992
        }
993
        let alloc = self.get_mut(ptr.alloc_id)?;
R
rustfmt  
Ralf Jung 已提交
994 995 996 997 998
        alloc.undef_mask.set_range(
            ptr.offset,
            ptr.offset + size,
            new_state,
        );
S
Scott Olson 已提交
999 1000 1001 1002
        Ok(())
    }
}

1003 1004 1005 1006
////////////////////////////////////////////////////////////////////////////////
// Unaligned accesses
////////////////////////////////////////////////////////////////////////////////

O
Oliver Schneider 已提交
1007 1008 1009
pub trait HasMemory<'a, 'mir, 'tcx: 'a + 'mir, M: Machine<'mir, 'tcx>> {
    fn memory_mut(&mut self) -> &mut Memory<'a, 'mir, 'tcx, M>;
    fn memory(&self) -> &Memory<'a, 'mir, 'tcx, M>;
1010 1011
}

O
Oliver Schneider 已提交
1012
impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> HasMemory<'a, 'mir, 'tcx, M> for Memory<'a, 'mir, 'tcx, M> {
1013
    #[inline]
O
Oliver Schneider 已提交
1014
    fn memory_mut(&mut self) -> &mut Memory<'a, 'mir, 'tcx, M> {
1015 1016
        self
    }
1017 1018

    #[inline]
O
Oliver Schneider 已提交
1019
    fn memory(&self) -> &Memory<'a, 'mir, 'tcx, M> {
1020 1021
        self
    }
1022 1023
}

O
Oliver Schneider 已提交
1024
impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> HasMemory<'a, 'mir, 'tcx, M> for EvalContext<'a, 'mir, 'tcx, M> {
1025
    #[inline]
O
Oliver Schneider 已提交
1026
    fn memory_mut(&mut self) -> &mut Memory<'a, 'mir, 'tcx, M> {
1027
        &mut self.memory
1028
    }
1029 1030

    #[inline]
O
Oliver Schneider 已提交
1031
    fn memory(&self) -> &Memory<'a, 'mir, 'tcx, M> {
1032
        &self.memory
1033 1034 1035
    }
}

O
Oliver Schneider 已提交
1036
impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> layout::HasDataLayout for &'a Memory<'a, 'mir, 'tcx, M> {
1037
    #[inline]
1038
    fn data_layout(&self) -> &TargetDataLayout {
O
Oliver Schneider 已提交
1039
        &self.tcx.data_layout
1040 1041
    }
}