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::{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, PartialEq)]
62 pub struct AllocId(u64);
65 pub struct Allocation {
67 pub relocations: BTreeMap<usize, AllocId>,
68 pub undef_mask: UndefMask,
71 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
73 pub alloc_id: AllocId,
78 pub fn offset(self, i: isize) -> Self {
79 Pointer { offset: (self.offset as isize + i) as usize, ..self }
83 ////////////////////////////////////////////////////////////////////////////////
84 // Top-level interpreter memory
85 ////////////////////////////////////////////////////////////////////////////////
88 alloc_map: HashMap<u64, Allocation>,
90 pub pointer_size: usize,
94 pub fn new() -> Self {
96 alloc_map: HashMap::new(),
99 // TODO(tsion): Should this be host's or target's usize?
100 pointer_size: mem::size_of::<usize>(),
104 pub fn allocate(&mut self, size: usize) -> Pointer {
105 let id = AllocId(self.next_id);
106 let alloc = Allocation {
107 bytes: vec![0; size],
108 relocations: BTreeMap::new(),
109 undef_mask: UndefMask::new(size),
111 self.alloc_map.insert(self.next_id, alloc);
119 // TODO(tsion): Track which allocations were returned from __rust_allocate and report an error
120 // when reallocating/deallocating any others.
121 pub fn reallocate(&mut self, ptr: Pointer, new_size: usize) -> EvalResult<()> {
123 // TODO(tsion): Report error about non-__rust_allocate'd pointer.
127 let alloc = try!(self.get_mut(ptr.alloc_id));
128 let size = alloc.bytes.len();
130 let amount = new_size - size;
131 alloc.bytes.extend(iter::repeat(0).take(amount));
132 alloc.undef_mask.grow(amount, false);
133 } else if size > new_size {
135 // alloc.bytes.truncate(new_size);
136 // alloc.undef_mask.len = new_size;
137 // TODO: potentially remove relocations
143 // TODO(tsion): See comment on `reallocate`.
144 pub fn deallocate(&mut self, ptr: Pointer) -> EvalResult<()> {
146 // TODO(tsion): Report error about non-__rust_allocate'd pointer.
150 if self.alloc_map.remove(&ptr.alloc_id.0).is_none() {
151 // TODO(tsion): Report error about erroneous free. This is blocked on properly tracking
152 // already-dropped state since this if-statement is entered even in safe code without
159 ////////////////////////////////////////////////////////////////////////////////
160 // Allocation accessors
161 ////////////////////////////////////////////////////////////////////////////////
163 pub fn get(&self, id: AllocId) -> EvalResult<&Allocation> {
164 self.alloc_map.get(&id.0).ok_or(EvalError::DanglingPointerDeref)
167 pub fn get_mut(&mut self, id: AllocId) -> EvalResult<&mut Allocation> {
168 self.alloc_map.get_mut(&id.0).ok_or(EvalError::DanglingPointerDeref)
171 /// Print an allocation and all allocations it points to, recursively.
172 pub fn dump(&self, id: AllocId) {
173 let mut allocs_seen = HashSet::new();
174 let mut allocs_to_print = VecDeque::new();
175 allocs_to_print.push_back(id);
177 while let Some(id) = allocs_to_print.pop_front() {
178 allocs_seen.insert(id.0);
179 let prefix = format!("Alloc {:<5} ", format!("{}:", id.0));
180 print!("{}", prefix);
181 let mut relocations = vec![];
183 let alloc = match self.alloc_map.get(&id.0) {
186 println!("(deallocated)");
191 for i in 0..alloc.bytes.len() {
192 if let Some(&target_id) = alloc.relocations.get(&i) {
193 if !allocs_seen.contains(&target_id.0) {
194 allocs_to_print.push_back(target_id);
196 relocations.push((i, target_id.0));
198 if alloc.undef_mask.is_range_defined(i, i+1) {
199 print!("{:02x} ", alloc.bytes[i]);
204 println!("({} bytes)", alloc.bytes.len());
206 if !relocations.is_empty() {
207 print!("{:1$}", "", prefix.len()); // Print spaces.
209 let relocation_width = (self.pointer_size - 1) * 3;
210 for (i, target_id) in relocations {
211 print!("{:1$}", "", (i - pos) * 3);
212 print!("└{0:─^1$}┘ ", format!("({})", target_id), relocation_width);
213 pos = i + self.pointer_size;
220 ////////////////////////////////////////////////////////////////////////////////
222 ////////////////////////////////////////////////////////////////////////////////
224 fn get_bytes_unchecked(&self, ptr: Pointer, size: usize) -> EvalResult<&[u8]> {
225 let alloc = try!(self.get(ptr.alloc_id));
226 if ptr.offset + size > alloc.bytes.len() {
227 return Err(EvalError::PointerOutOfBounds);
229 Ok(&alloc.bytes[ptr.offset..ptr.offset + size])
232 fn get_bytes_unchecked_mut(&mut self, ptr: Pointer, size: usize) -> EvalResult<&mut [u8]> {
233 let alloc = try!(self.get_mut(ptr.alloc_id));
234 if ptr.offset + size > alloc.bytes.len() {
235 return Err(EvalError::PointerOutOfBounds);
237 Ok(&mut alloc.bytes[ptr.offset..ptr.offset + size])
240 fn get_bytes(&self, ptr: Pointer, size: usize) -> EvalResult<&[u8]> {
241 if try!(self.relocations(ptr, size)).count() != 0 {
242 return Err(EvalError::ReadPointerAsBytes);
244 try!(self.check_defined(ptr, size));
245 self.get_bytes_unchecked(ptr, size)
248 fn get_bytes_mut(&mut self, ptr: Pointer, size: usize) -> EvalResult<&mut [u8]> {
249 try!(self.clear_relocations(ptr, size));
250 try!(self.mark_definedness(ptr, size, true));
251 self.get_bytes_unchecked_mut(ptr, size)
254 ////////////////////////////////////////////////////////////////////////////////
255 // Reading and writing
256 ////////////////////////////////////////////////////////////////////////////////
258 pub fn copy(&mut self, src: Pointer, dest: Pointer, size: usize) -> EvalResult<()> {
259 try!(self.check_relocation_edges(src, size));
261 let src_bytes = try!(self.get_bytes_unchecked_mut(src, size)).as_mut_ptr();
262 let dest_bytes = try!(self.get_bytes_mut(dest, size)).as_mut_ptr();
264 // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
265 // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
266 // `dest` could possibly overlap.
268 if src.alloc_id == dest.alloc_id {
269 ptr::copy(src_bytes, dest_bytes, size);
271 ptr::copy_nonoverlapping(src_bytes, dest_bytes, size);
275 try!(self.copy_undef_mask(src, dest, size));
276 try!(self.copy_relocations(src, dest, size));
281 pub fn write_bytes(&mut self, ptr: Pointer, src: &[u8]) -> EvalResult<()> {
282 let bytes = try!(self.get_bytes_mut(ptr, src.len()));
283 bytes.clone_from_slice(src);
287 pub fn write_repeat(&mut self, ptr: Pointer, val: u8, count: usize) -> EvalResult<()> {
288 let bytes = try!(self.get_bytes_mut(ptr, count));
289 for b in bytes { *b = val; }
293 pub fn drop_fill(&mut self, ptr: Pointer, size: usize) -> EvalResult<()> {
294 self.write_repeat(ptr, mem::POST_DROP_U8, size)
297 pub fn read_ptr(&self, ptr: Pointer) -> EvalResult<Pointer> {
298 let size = self.pointer_size;
299 try!(self.check_defined(ptr, size));
300 let offset = try!(self.get_bytes_unchecked(ptr, size))
301 .read_uint::<NativeEndian>(size).unwrap() as usize;
302 let alloc = try!(self.get(ptr.alloc_id));
303 match alloc.relocations.get(&ptr.offset) {
304 Some(&alloc_id) => Ok(Pointer { alloc_id: alloc_id, offset: offset }),
305 None => Err(EvalError::ReadBytesAsPointer),
309 pub fn write_ptr(&mut self, dest: Pointer, ptr: Pointer) -> EvalResult<()> {
311 let size = self.pointer_size;
312 let mut bytes = try!(self.get_bytes_mut(dest, size));
313 bytes.write_uint::<NativeEndian>(ptr.offset as u64, size).unwrap();
315 try!(self.get_mut(dest.alloc_id)).relocations.insert(dest.offset, ptr.alloc_id);
319 pub fn write_primval(&mut self, ptr: Pointer, val: PrimVal) -> EvalResult<()> {
320 let pointer_size = self.pointer_size;
322 PrimVal::Bool(b) => self.write_bool(ptr, b),
323 PrimVal::I8(n) => self.write_int(ptr, n as i64, 1),
324 PrimVal::I16(n) => self.write_int(ptr, n as i64, 2),
325 PrimVal::I32(n) => self.write_int(ptr, n as i64, 4),
326 PrimVal::I64(n) => self.write_int(ptr, n as i64, 8),
327 PrimVal::U8(n) => self.write_uint(ptr, n as u64, 1),
328 PrimVal::U16(n) => self.write_uint(ptr, n as u64, 2),
329 PrimVal::U32(n) => self.write_uint(ptr, n as u64, 4),
330 PrimVal::U64(n) => self.write_uint(ptr, n as u64, 8),
331 PrimVal::IntegerPtr(n) => self.write_uint(ptr, n as u64, pointer_size),
332 PrimVal::AbstractPtr(_p) => unimplemented!(),
336 pub fn read_bool(&self, ptr: Pointer) -> EvalResult<bool> {
337 let bytes = try!(self.get_bytes(ptr, 1));
341 _ => Err(EvalError::InvalidBool),
345 pub fn write_bool(&mut self, ptr: Pointer, b: bool) -> EvalResult<()> {
346 self.get_bytes_mut(ptr, 1).map(|bytes| bytes[0] = b as u8)
349 pub fn read_int(&self, ptr: Pointer, size: usize) -> EvalResult<i64> {
350 self.get_bytes(ptr, size).map(|mut b| b.read_int::<NativeEndian>(size).unwrap())
353 pub fn write_int(&mut self, ptr: Pointer, n: i64, size: usize) -> EvalResult<()> {
354 self.get_bytes_mut(ptr, size).map(|mut b| b.write_int::<NativeEndian>(n, size).unwrap())
357 pub fn read_uint(&self, ptr: Pointer, size: usize) -> EvalResult<u64> {
358 self.get_bytes(ptr, size).map(|mut b| b.read_uint::<NativeEndian>(size).unwrap())
361 pub fn write_uint(&mut self, ptr: Pointer, n: u64, size: usize) -> EvalResult<()> {
362 self.get_bytes_mut(ptr, size).map(|mut b| b.write_uint::<NativeEndian>(n, size).unwrap())
365 pub fn read_isize(&self, ptr: Pointer) -> EvalResult<i64> {
366 self.read_int(ptr, self.pointer_size)
369 pub fn write_isize(&mut self, ptr: Pointer, n: i64) -> EvalResult<()> {
370 let size = self.pointer_size;
371 self.write_int(ptr, n, size)
374 pub fn read_usize(&self, ptr: Pointer) -> EvalResult<u64> {
375 self.read_uint(ptr, self.pointer_size)
378 pub fn write_usize(&mut self, ptr: Pointer, n: u64) -> EvalResult<()> {
379 let size = self.pointer_size;
380 self.write_uint(ptr, n, size)
383 ////////////////////////////////////////////////////////////////////////////////
385 ////////////////////////////////////////////////////////////////////////////////
387 fn relocations(&self, ptr: Pointer, size: usize)
388 -> EvalResult<btree_map::Range<usize, AllocId>>
390 let start = ptr.offset.saturating_sub(self.pointer_size - 1);
391 let end = start + size;
392 Ok(try!(self.get(ptr.alloc_id)).relocations.range(Included(&start), Excluded(&end)))
395 fn clear_relocations(&mut self, ptr: Pointer, size: usize) -> EvalResult<()> {
396 // Find all relocations overlapping the given range.
397 let keys: Vec<_> = try!(self.relocations(ptr, size)).map(|(&k, _)| k).collect();
398 if keys.len() == 0 { return Ok(()); }
400 // Find the start and end of the given range and its outermost relocations.
401 let start = ptr.offset;
402 let end = start + size;
403 let first = *keys.first().unwrap();
404 let last = *keys.last().unwrap() + self.pointer_size;
406 let alloc = try!(self.get_mut(ptr.alloc_id));
408 // Mark parts of the outermost relocations as undefined if they partially fall outside the
410 if first < start { alloc.undef_mask.set_range(first, start, false); }
411 if last > end { alloc.undef_mask.set_range(end, last, false); }
413 // Forget all the relocations.
414 for k in keys { alloc.relocations.remove(&k); }
419 fn check_relocation_edges(&self, ptr: Pointer, size: usize) -> EvalResult<()> {
420 let overlapping_start = try!(self.relocations(ptr, 0)).count();
421 let overlapping_end = try!(self.relocations(ptr.offset(size as isize), 0)).count();
422 if overlapping_start + overlapping_end != 0 {
423 return Err(EvalError::ReadPointerAsBytes);
428 fn copy_relocations(&mut self, src: Pointer, dest: Pointer, size: usize) -> EvalResult<()> {
429 let relocations: Vec<_> = try!(self.relocations(src, size))
430 .map(|(&offset, &alloc_id)| {
431 // Update relocation offsets for the new positions in the destination allocation.
432 (offset + dest.offset - src.offset, alloc_id)
435 try!(self.get_mut(dest.alloc_id)).relocations.extend(relocations);
439 ////////////////////////////////////////////////////////////////////////////////
441 ////////////////////////////////////////////////////////////////////////////////
443 // FIXME(tsino): This is a very naive, slow version.
444 fn copy_undef_mask(&mut self, src: Pointer, dest: Pointer, size: usize) -> EvalResult<()> {
445 // The bits have to be saved locally before writing to dest in case src and dest overlap.
446 let mut v = Vec::with_capacity(size);
448 let defined = try!(self.get(src.alloc_id)).undef_mask.get(src.offset + i);
451 for (i, defined) in v.into_iter().enumerate() {
452 try!(self.get_mut(dest.alloc_id)).undef_mask.set(dest.offset + i, defined);
457 fn check_defined(&self, ptr: Pointer, size: usize) -> EvalResult<()> {
458 let alloc = try!(self.get(ptr.alloc_id));
459 if !alloc.undef_mask.is_range_defined(ptr.offset, ptr.offset + size) {
460 return Err(EvalError::ReadUndefBytes);
465 pub fn mark_definedness(&mut self, ptr: Pointer, size: usize, new_state: bool)
468 let mut alloc = try!(self.get_mut(ptr.alloc_id));
469 alloc.undef_mask.set_range(ptr.offset, ptr.offset + size, new_state);
474 ////////////////////////////////////////////////////////////////////////////////
475 // Undefined byte tracking
476 ////////////////////////////////////////////////////////////////////////////////
479 const BLOCK_SIZE: usize = 64;
481 #[derive(Clone, Debug)]
482 pub struct UndefMask {
488 fn new(size: usize) -> Self {
489 let mut m = UndefMask {
497 /// Check whether the range `start..end` (end-exclusive) is entirely defined.
498 fn is_range_defined(&self, start: usize, end: usize) -> bool {
499 if end > self.len { return false; }
500 for i in start..end {
501 if !self.get(i) { return false; }
506 fn set_range(&mut self, start: usize, end: usize, new_state: bool) {
508 if end > len { self.grow(end - len, new_state); }
509 self.set_range_inbounds(start, end, new_state);
512 fn set_range_inbounds(&mut self, start: usize, end: usize, new_state: bool) {
513 for i in start..end { self.set(i, new_state); }
516 fn get(&self, i: usize) -> bool {
517 let (block, bit) = bit_index(i);
518 (self.blocks[block] & 1 << bit) != 0
521 fn set(&mut self, i: usize, new_state: bool) {
522 let (block, bit) = bit_index(i);
524 self.blocks[block] |= 1 << bit;
526 self.blocks[block] &= !(1 << bit);
530 fn grow(&mut self, amount: usize, new_state: bool) {
531 let unused_trailing_bits = self.blocks.len() * BLOCK_SIZE - self.len;
532 if amount > unused_trailing_bits {
533 let additional_blocks = amount / BLOCK_SIZE + 1;
534 self.blocks.extend(iter::repeat(0).take(additional_blocks));
536 let start = self.len;
538 self.set_range_inbounds(start, start + amount, new_state);
542 // fn uniform_block(state: bool) -> Block {
543 // if state { !0 } else { 0 }
546 fn bit_index(bits: usize) -> (usize, usize) {
547 (bits / BLOCK_SIZE, bits % BLOCK_SIZE)