1 use byteorder::{ByteOrder, NativeEndian, ReadBytesExt, WriteBytesExt};
2 use std::collections::Bound::{Included, Excluded};
3 use std::collections::{btree_map, BTreeMap, HashMap, HashSet, VecDeque};
4 use std::{fmt, iter, mem, ptr};
6 use error::{EvalError, EvalResult};
9 ////////////////////////////////////////////////////////////////////////////////
10 // Value representations
11 ////////////////////////////////////////////////////////////////////////////////
13 #[derive(Clone, Debug, Eq, PartialEq)]
15 /// Representation for a non-aggregate type such as a boolean, integer, character or pointer.
20 /// The representation for aggregate types including structs, enums, and tuples.
22 /// The size of the discriminant (an integer). Should be between 0 and 8. Always 0 for
23 /// structs and tuples.
26 /// The size of the entire aggregate, including the discriminant.
29 /// The representations of the contents of each variant.
30 variants: Vec<Vec<FieldRepr>>,
36 /// Number of elements.
41 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
42 pub struct FieldRepr {
48 pub fn size(&self) -> usize {
50 Repr::Primitive { size } => size,
51 Repr::Aggregate { size, .. } => size,
52 Repr::Array { elem_size, length } => elem_size * length,
57 ////////////////////////////////////////////////////////////////////////////////
58 // Allocations and pointers
59 ////////////////////////////////////////////////////////////////////////////////
61 #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
62 pub struct AllocId(u64);
64 impl fmt::Display for AllocId {
65 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66 write!(f, "{}", self.0)
71 pub struct Allocation {
73 pub relocations: BTreeMap<usize, AllocId>,
74 pub undef_mask: UndefMask,
77 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
79 pub alloc_id: AllocId,
84 pub fn offset(self, i: isize) -> Self {
85 Pointer { offset: (self.offset as isize + i) as usize, ..self }
89 ////////////////////////////////////////////////////////////////////////////////
90 // Top-level interpreter memory
91 ////////////////////////////////////////////////////////////////////////////////
94 alloc_map: HashMap<AllocId, Allocation>,
96 pub pointer_size: usize,
100 pub fn new() -> Self {
102 alloc_map: HashMap::new(),
105 // TODO(tsion): Should this be host's or target's usize?
106 pointer_size: mem::size_of::<usize>(),
110 pub fn allocate(&mut self, size: usize) -> Pointer {
111 let alloc = Allocation {
112 bytes: vec![0; size],
113 relocations: BTreeMap::new(),
114 undef_mask: UndefMask::new(size),
116 let id = self.next_id;
118 self.alloc_map.insert(id, alloc);
125 // TODO(tsion): Track which allocations were returned from __rust_allocate and report an error
126 // when reallocating/deallocating any others.
127 pub fn reallocate(&mut self, ptr: Pointer, new_size: usize) -> EvalResult<()> {
129 // TODO(tsion): Report error about non-__rust_allocate'd pointer.
133 let alloc = try!(self.get_mut(ptr.alloc_id));
134 let size = alloc.bytes.len();
136 let amount = new_size - size;
137 alloc.bytes.extend(iter::repeat(0).take(amount));
138 alloc.undef_mask.grow(amount, false);
139 } else if size > new_size {
141 // alloc.bytes.truncate(new_size);
142 // alloc.undef_mask.len = new_size;
143 // TODO: potentially remove relocations
149 // TODO(tsion): See comment on `reallocate`.
150 pub fn deallocate(&mut self, ptr: Pointer) -> EvalResult<()> {
152 // TODO(tsion): Report error about non-__rust_allocate'd pointer.
156 if self.alloc_map.remove(&ptr.alloc_id).is_none() {
157 // TODO(tsion): Report error about erroneous free. This is blocked on properly tracking
158 // already-dropped state since this if-statement is entered even in safe code without
165 ////////////////////////////////////////////////////////////////////////////////
166 // Allocation accessors
167 ////////////////////////////////////////////////////////////////////////////////
169 pub fn get(&self, id: AllocId) -> EvalResult<&Allocation> {
170 self.alloc_map.get(&id).ok_or(EvalError::DanglingPointerDeref)
173 pub fn get_mut(&mut self, id: AllocId) -> EvalResult<&mut Allocation> {
174 self.alloc_map.get_mut(&id).ok_or(EvalError::DanglingPointerDeref)
177 /// Print an allocation and all allocations it points to, recursively.
178 pub fn dump(&self, id: AllocId) {
179 let mut allocs_seen = HashSet::new();
180 let mut allocs_to_print = VecDeque::new();
181 allocs_to_print.push_back(id);
183 while let Some(id) = allocs_to_print.pop_front() {
184 allocs_seen.insert(id);
185 let prefix = format!("Alloc {:<5} ", format!("{}:", id));
186 print!("{}", prefix);
187 let mut relocations = vec![];
189 let alloc = match self.alloc_map.get(&id) {
192 println!("(deallocated)");
197 for i in 0..alloc.bytes.len() {
198 if let Some(&target_id) = alloc.relocations.get(&i) {
199 if !allocs_seen.contains(&target_id) {
200 allocs_to_print.push_back(target_id);
202 relocations.push((i, target_id));
204 if alloc.undef_mask.is_range_defined(i, i + 1) {
205 print!("{:02x} ", alloc.bytes[i]);
210 println!("({} bytes)", alloc.bytes.len());
212 if !relocations.is_empty() {
213 print!("{:1$}", "", prefix.len()); // Print spaces.
215 let relocation_width = (self.pointer_size - 1) * 3;
216 for (i, target_id) in relocations {
217 print!("{:1$}", "", (i - pos) * 3);
218 print!("└{0:─^1$}┘ ", format!("({})", target_id), relocation_width);
219 pos = i + self.pointer_size;
226 ////////////////////////////////////////////////////////////////////////////////
228 ////////////////////////////////////////////////////////////////////////////////
230 fn get_bytes_unchecked(&self, ptr: Pointer, size: usize) -> EvalResult<&[u8]> {
231 let alloc = try!(self.get(ptr.alloc_id));
232 if ptr.offset + size > alloc.bytes.len() {
233 return Err(EvalError::PointerOutOfBounds);
235 Ok(&alloc.bytes[ptr.offset..ptr.offset + size])
238 fn get_bytes_unchecked_mut(&mut self, ptr: Pointer, size: usize) -> EvalResult<&mut [u8]> {
239 let alloc = try!(self.get_mut(ptr.alloc_id));
240 if ptr.offset + size > alloc.bytes.len() {
241 return Err(EvalError::PointerOutOfBounds);
243 Ok(&mut alloc.bytes[ptr.offset..ptr.offset + size])
246 fn get_bytes(&self, ptr: Pointer, size: usize) -> EvalResult<&[u8]> {
247 if try!(self.relocations(ptr, size)).count() != 0 {
248 return Err(EvalError::ReadPointerAsBytes);
250 try!(self.check_defined(ptr, size));
251 self.get_bytes_unchecked(ptr, size)
254 fn get_bytes_mut(&mut self, ptr: Pointer, size: usize) -> EvalResult<&mut [u8]> {
255 try!(self.clear_relocations(ptr, size));
256 try!(self.mark_definedness(ptr, size, true));
257 self.get_bytes_unchecked_mut(ptr, size)
260 ////////////////////////////////////////////////////////////////////////////////
261 // Reading and writing
262 ////////////////////////////////////////////////////////////////////////////////
264 pub fn copy(&mut self, src: Pointer, dest: Pointer, size: usize) -> EvalResult<()> {
265 try!(self.check_relocation_edges(src, size));
267 let src_bytes = try!(self.get_bytes_unchecked_mut(src, size)).as_mut_ptr();
268 let dest_bytes = try!(self.get_bytes_mut(dest, size)).as_mut_ptr();
270 // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
271 // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
272 // `dest` could possibly overlap.
274 if src.alloc_id == dest.alloc_id {
275 ptr::copy(src_bytes, dest_bytes, size);
277 ptr::copy_nonoverlapping(src_bytes, dest_bytes, size);
281 try!(self.copy_undef_mask(src, dest, size));
282 try!(self.copy_relocations(src, dest, size));
287 pub fn write_bytes(&mut self, ptr: Pointer, src: &[u8]) -> EvalResult<()> {
288 let bytes = try!(self.get_bytes_mut(ptr, src.len()));
289 bytes.clone_from_slice(src);
293 pub fn write_repeat(&mut self, ptr: Pointer, val: u8, count: usize) -> EvalResult<()> {
294 let bytes = try!(self.get_bytes_mut(ptr, count));
295 for b in bytes { *b = val; }
299 pub fn drop_fill(&mut self, ptr: Pointer, size: usize) -> EvalResult<()> {
300 self.write_repeat(ptr, mem::POST_DROP_U8, size)
303 pub fn read_ptr(&self, ptr: Pointer) -> EvalResult<Pointer> {
304 let size = self.pointer_size;
305 try!(self.check_defined(ptr, size));
306 let offset = try!(self.get_bytes_unchecked(ptr, size))
307 .read_uint::<NativeEndian>(size).unwrap() as usize;
308 let alloc = try!(self.get(ptr.alloc_id));
309 match alloc.relocations.get(&ptr.offset) {
310 Some(&alloc_id) => Ok(Pointer { alloc_id: alloc_id, offset: offset }),
311 None => Err(EvalError::ReadBytesAsPointer),
315 pub fn write_ptr(&mut self, dest: Pointer, ptr: Pointer) -> EvalResult<()> {
317 let size = self.pointer_size;
318 let mut bytes = try!(self.get_bytes_mut(dest, size));
319 bytes.write_uint::<NativeEndian>(ptr.offset as u64, size).unwrap();
321 try!(self.get_mut(dest.alloc_id)).relocations.insert(dest.offset, ptr.alloc_id);
325 pub fn write_primval(&mut self, ptr: Pointer, val: PrimVal) -> EvalResult<()> {
326 let pointer_size = self.pointer_size;
328 PrimVal::Bool(b) => self.write_bool(ptr, b),
329 PrimVal::I8(n) => self.write_int(ptr, n as i64, 1),
330 PrimVal::I16(n) => self.write_int(ptr, n as i64, 2),
331 PrimVal::I32(n) => self.write_int(ptr, n as i64, 4),
332 PrimVal::I64(n) => self.write_int(ptr, n as i64, 8),
333 PrimVal::U8(n) => self.write_uint(ptr, n as u64, 1),
334 PrimVal::U16(n) => self.write_uint(ptr, n as u64, 2),
335 PrimVal::U32(n) => self.write_uint(ptr, n as u64, 4),
336 PrimVal::U64(n) => self.write_uint(ptr, n as u64, 8),
337 PrimVal::IntegerPtr(n) => self.write_uint(ptr, n as u64, pointer_size),
338 PrimVal::AbstractPtr(_p) => unimplemented!(),
342 pub fn read_bool(&self, ptr: Pointer) -> EvalResult<bool> {
343 let bytes = try!(self.get_bytes(ptr, 1));
347 _ => Err(EvalError::InvalidBool),
351 pub fn write_bool(&mut self, ptr: Pointer, b: bool) -> EvalResult<()> {
352 self.get_bytes_mut(ptr, 1).map(|bytes| bytes[0] = b as u8)
355 pub fn read_int(&self, ptr: Pointer, size: usize) -> EvalResult<i64> {
356 self.get_bytes(ptr, size).map(|mut b| b.read_int::<NativeEndian>(size).unwrap())
359 pub fn write_int(&mut self, ptr: Pointer, n: i64, size: usize) -> EvalResult<()> {
360 self.get_bytes_mut(ptr, size).map(|mut b| b.write_int::<NativeEndian>(n, size).unwrap())
363 pub fn read_uint(&self, ptr: Pointer, size: usize) -> EvalResult<u64> {
364 self.get_bytes(ptr, size).map(|mut b| b.read_uint::<NativeEndian>(size).unwrap())
367 pub fn write_uint(&mut self, ptr: Pointer, n: u64, size: usize) -> EvalResult<()> {
368 self.get_bytes_mut(ptr, size).map(|mut b| b.write_uint::<NativeEndian>(n, size).unwrap())
371 pub fn read_isize(&self, ptr: Pointer) -> EvalResult<i64> {
372 self.read_int(ptr, self.pointer_size)
375 pub fn write_isize(&mut self, ptr: Pointer, n: i64) -> EvalResult<()> {
376 let size = self.pointer_size;
377 self.write_int(ptr, n, size)
380 pub fn read_usize(&self, ptr: Pointer) -> EvalResult<u64> {
381 self.read_uint(ptr, self.pointer_size)
384 pub fn write_usize(&mut self, ptr: Pointer, n: u64) -> EvalResult<()> {
385 let size = self.pointer_size;
386 self.write_uint(ptr, n, size)
389 ////////////////////////////////////////////////////////////////////////////////
391 ////////////////////////////////////////////////////////////////////////////////
393 fn relocations(&self, ptr: Pointer, size: usize)
394 -> EvalResult<btree_map::Range<usize, AllocId>>
396 let start = ptr.offset.saturating_sub(self.pointer_size - 1);
397 let end = start + size;
398 Ok(try!(self.get(ptr.alloc_id)).relocations.range(Included(&start), Excluded(&end)))
401 fn clear_relocations(&mut self, ptr: Pointer, size: usize) -> EvalResult<()> {
402 // Find all relocations overlapping the given range.
403 let keys: Vec<_> = try!(self.relocations(ptr, size)).map(|(&k, _)| k).collect();
404 if keys.len() == 0 { return Ok(()); }
406 // Find the start and end of the given range and its outermost relocations.
407 let start = ptr.offset;
408 let end = start + size;
409 let first = *keys.first().unwrap();
410 let last = *keys.last().unwrap() + self.pointer_size;
412 let alloc = try!(self.get_mut(ptr.alloc_id));
414 // Mark parts of the outermost relocations as undefined if they partially fall outside the
416 if first < start { alloc.undef_mask.set_range(first, start, false); }
417 if last > end { alloc.undef_mask.set_range(end, last, false); }
419 // Forget all the relocations.
420 for k in keys { alloc.relocations.remove(&k); }
425 fn check_relocation_edges(&self, ptr: Pointer, size: usize) -> EvalResult<()> {
426 let overlapping_start = try!(self.relocations(ptr, 0)).count();
427 let overlapping_end = try!(self.relocations(ptr.offset(size as isize), 0)).count();
428 if overlapping_start + overlapping_end != 0 {
429 return Err(EvalError::ReadPointerAsBytes);
434 fn copy_relocations(&mut self, src: Pointer, dest: Pointer, size: usize) -> EvalResult<()> {
435 let relocations: Vec<_> = try!(self.relocations(src, size))
436 .map(|(&offset, &alloc_id)| {
437 // Update relocation offsets for the new positions in the destination allocation.
438 (offset + dest.offset - src.offset, alloc_id)
441 try!(self.get_mut(dest.alloc_id)).relocations.extend(relocations);
445 ////////////////////////////////////////////////////////////////////////////////
447 ////////////////////////////////////////////////////////////////////////////////
449 // FIXME(tsino): This is a very naive, slow version.
450 fn copy_undef_mask(&mut self, src: Pointer, dest: Pointer, size: usize) -> EvalResult<()> {
451 // The bits have to be saved locally before writing to dest in case src and dest overlap.
452 let mut v = Vec::with_capacity(size);
454 let defined = try!(self.get(src.alloc_id)).undef_mask.get(src.offset + i);
457 for (i, defined) in v.into_iter().enumerate() {
458 try!(self.get_mut(dest.alloc_id)).undef_mask.set(dest.offset + i, defined);
463 fn check_defined(&self, ptr: Pointer, size: usize) -> EvalResult<()> {
464 let alloc = try!(self.get(ptr.alloc_id));
465 if !alloc.undef_mask.is_range_defined(ptr.offset, ptr.offset + size) {
466 return Err(EvalError::ReadUndefBytes);
471 pub fn mark_definedness(&mut self, ptr: Pointer, size: usize, new_state: bool)
474 let mut alloc = try!(self.get_mut(ptr.alloc_id));
475 alloc.undef_mask.set_range(ptr.offset, ptr.offset + size, new_state);
480 ////////////////////////////////////////////////////////////////////////////////
481 // Undefined byte tracking
482 ////////////////////////////////////////////////////////////////////////////////
485 const BLOCK_SIZE: usize = 64;
487 #[derive(Clone, Debug)]
488 pub struct UndefMask {
494 fn new(size: usize) -> Self {
495 let mut m = UndefMask {
503 /// Check whether the range `start..end` (end-exclusive) is entirely defined.
504 fn is_range_defined(&self, start: usize, end: usize) -> bool {
505 if end > self.len { return false; }
506 for i in start..end {
507 if !self.get(i) { return false; }
512 fn set_range(&mut self, start: usize, end: usize, new_state: bool) {
514 if end > len { self.grow(end - len, new_state); }
515 self.set_range_inbounds(start, end, new_state);
518 fn set_range_inbounds(&mut self, start: usize, end: usize, new_state: bool) {
519 for i in start..end { self.set(i, new_state); }
522 fn get(&self, i: usize) -> bool {
523 let (block, bit) = bit_index(i);
524 (self.blocks[block] & 1 << bit) != 0
527 fn set(&mut self, i: usize, new_state: bool) {
528 let (block, bit) = bit_index(i);
530 self.blocks[block] |= 1 << bit;
532 self.blocks[block] &= !(1 << bit);
536 fn grow(&mut self, amount: usize, new_state: bool) {
537 let unused_trailing_bits = self.blocks.len() * BLOCK_SIZE - self.len;
538 if amount > unused_trailing_bits {
539 let additional_blocks = amount / BLOCK_SIZE + 1;
540 self.blocks.extend(iter::repeat(0).take(additional_blocks));
542 let start = self.len;
544 self.set_range_inbounds(start, start + amount, new_state);
548 // fn uniform_block(state: bool) -> Block {
549 // if state { !0 } else { 0 }
552 fn bit_index(bits: usize) -> (usize, usize) {
553 (bits / BLOCK_SIZE, bits % BLOCK_SIZE)