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 self.get_bytes_mut(ptr, src.len()).map(|dest| dest.clone_from_slice(src))
285 pub fn read_ptr(&self, ptr: Pointer) -> EvalResult<Pointer> {
286 let size = self.pointer_size;
287 try!(self.check_defined(ptr, size));
288 let offset = try!(self.get_bytes_unchecked(ptr, size))
289 .read_uint::<NativeEndian>(size).unwrap() as usize;
290 let alloc = try!(self.get(ptr.alloc_id));
291 match alloc.relocations.get(&ptr.offset) {
292 Some(&alloc_id) => Ok(Pointer { alloc_id: alloc_id, offset: offset }),
293 None => Err(EvalError::ReadBytesAsPointer),
297 pub fn write_ptr(&mut self, dest: Pointer, ptr: Pointer) -> EvalResult<()> {
299 let size = self.pointer_size;
300 let mut bytes = try!(self.get_bytes_mut(dest, size));
301 bytes.write_uint::<NativeEndian>(ptr.offset as u64, size).unwrap();
303 try!(self.get_mut(dest.alloc_id)).relocations.insert(dest.offset, ptr.alloc_id);
307 pub fn write_primval(&mut self, ptr: Pointer, val: PrimVal) -> EvalResult<()> {
308 let pointer_size = self.pointer_size;
310 PrimVal::Bool(b) => self.write_bool(ptr, b),
311 PrimVal::I8(n) => self.write_int(ptr, n as i64, 1),
312 PrimVal::I16(n) => self.write_int(ptr, n as i64, 2),
313 PrimVal::I32(n) => self.write_int(ptr, n as i64, 4),
314 PrimVal::I64(n) => self.write_int(ptr, n as i64, 8),
315 PrimVal::U8(n) => self.write_uint(ptr, n as u64, 1),
316 PrimVal::U16(n) => self.write_uint(ptr, n as u64, 2),
317 PrimVal::U32(n) => self.write_uint(ptr, n as u64, 4),
318 PrimVal::U64(n) => self.write_uint(ptr, n as u64, 8),
319 PrimVal::IntegerPtr(n) => self.write_uint(ptr, n as u64, pointer_size),
320 PrimVal::AbstractPtr(_p) => unimplemented!(),
324 pub fn read_bool(&self, ptr: Pointer) -> EvalResult<bool> {
325 let bytes = try!(self.get_bytes(ptr, 1));
329 _ => Err(EvalError::InvalidBool),
333 pub fn write_bool(&mut self, ptr: Pointer, b: bool) -> EvalResult<()> {
334 self.get_bytes_mut(ptr, 1).map(|bytes| bytes[0] = b as u8)
337 pub fn read_int(&self, ptr: Pointer, size: usize) -> EvalResult<i64> {
338 self.get_bytes(ptr, size).map(|mut b| b.read_int::<NativeEndian>(size).unwrap())
341 pub fn write_int(&mut self, ptr: Pointer, n: i64, size: usize) -> EvalResult<()> {
342 self.get_bytes_mut(ptr, size).map(|mut b| b.write_int::<NativeEndian>(n, size).unwrap())
345 pub fn read_uint(&self, ptr: Pointer, size: usize) -> EvalResult<u64> {
346 self.get_bytes(ptr, size).map(|mut b| b.read_uint::<NativeEndian>(size).unwrap())
349 pub fn write_uint(&mut self, ptr: Pointer, n: u64, size: usize) -> EvalResult<()> {
350 self.get_bytes_mut(ptr, size).map(|mut b| b.write_uint::<NativeEndian>(n, size).unwrap())
353 pub fn read_isize(&self, ptr: Pointer) -> EvalResult<i64> {
354 self.read_int(ptr, self.pointer_size)
357 pub fn write_isize(&mut self, ptr: Pointer, n: i64) -> EvalResult<()> {
358 let size = self.pointer_size;
359 self.write_int(ptr, n, size)
362 pub fn read_usize(&self, ptr: Pointer) -> EvalResult<u64> {
363 self.read_uint(ptr, self.pointer_size)
366 pub fn write_usize(&mut self, ptr: Pointer, n: u64) -> EvalResult<()> {
367 let size = self.pointer_size;
368 self.write_uint(ptr, n, size)
371 ////////////////////////////////////////////////////////////////////////////////
373 ////////////////////////////////////////////////////////////////////////////////
375 fn relocations(&self, ptr: Pointer, size: usize)
376 -> EvalResult<btree_map::Range<usize, AllocId>>
378 let start = ptr.offset.saturating_sub(self.pointer_size - 1);
379 let end = start + size;
380 Ok(try!(self.get(ptr.alloc_id)).relocations.range(Included(&start), Excluded(&end)))
383 fn clear_relocations(&mut self, ptr: Pointer, size: usize) -> EvalResult<()> {
384 // Find all relocations overlapping the given range.
385 let keys: Vec<_> = try!(self.relocations(ptr, size)).map(|(&k, _)| k).collect();
386 if keys.len() == 0 { return Ok(()); }
388 // Find the start and end of the given range and its outermost relocations.
389 let start = ptr.offset;
390 let end = start + size;
391 let first = *keys.first().unwrap();
392 let last = *keys.last().unwrap() + self.pointer_size;
394 let alloc = try!(self.get_mut(ptr.alloc_id));
396 // Mark parts of the outermost relocations as undefined if they partially fall outside the
398 if first < start { alloc.undef_mask.set_range(first, start, false); }
399 if last > end { alloc.undef_mask.set_range(end, last, false); }
401 // Forget all the relocations.
402 for k in keys { alloc.relocations.remove(&k); }
407 fn check_relocation_edges(&self, ptr: Pointer, size: usize) -> EvalResult<()> {
408 let overlapping_start = try!(self.relocations(ptr, 0)).count();
409 let overlapping_end = try!(self.relocations(ptr.offset(size as isize), 0)).count();
410 if overlapping_start + overlapping_end != 0 {
411 return Err(EvalError::ReadPointerAsBytes);
416 fn copy_relocations(&mut self, src: Pointer, dest: Pointer, size: usize) -> EvalResult<()> {
417 let relocations: Vec<_> = try!(self.relocations(src, size))
418 .map(|(&offset, &alloc_id)| {
419 // Update relocation offsets for the new positions in the destination allocation.
420 (offset + dest.offset - src.offset, alloc_id)
423 try!(self.get_mut(dest.alloc_id)).relocations.extend(relocations);
427 ////////////////////////////////////////////////////////////////////////////////
429 ////////////////////////////////////////////////////////////////////////////////
431 // FIXME(tsino): This is a very naive, slow version.
432 fn copy_undef_mask(&mut self, src: Pointer, dest: Pointer, size: usize) -> EvalResult<()> {
433 // The bits have to be saved locally before writing to dest in case src and dest overlap.
434 let mut v = Vec::with_capacity(size);
436 let defined = try!(self.get(src.alloc_id)).undef_mask.get(src.offset + i);
439 for (i, defined) in v.into_iter().enumerate() {
440 try!(self.get_mut(dest.alloc_id)).undef_mask.set(dest.offset + i, defined);
445 fn check_defined(&self, ptr: Pointer, size: usize) -> EvalResult<()> {
446 let alloc = try!(self.get(ptr.alloc_id));
447 if !alloc.undef_mask.is_range_defined(ptr.offset, ptr.offset + size) {
448 return Err(EvalError::ReadUndefBytes);
453 pub fn mark_definedness(&mut self, ptr: Pointer, size: usize, new_state: bool)
456 let mut alloc = try!(self.get_mut(ptr.alloc_id));
457 alloc.undef_mask.set_range(ptr.offset, ptr.offset + size, new_state);
462 ////////////////////////////////////////////////////////////////////////////////
463 // Undefined byte tracking
464 ////////////////////////////////////////////////////////////////////////////////
467 const BLOCK_SIZE: usize = 64;
469 #[derive(Clone, Debug)]
470 pub struct UndefMask {
476 fn new(size: usize) -> Self {
477 let mut m = UndefMask {
485 /// Check whether the range `start..end` (end-exclusive) is entirely defined.
486 fn is_range_defined(&self, start: usize, end: usize) -> bool {
487 if end > self.len { return false; }
488 for i in start..end {
489 if !self.get(i) { return false; }
494 fn set_range(&mut self, start: usize, end: usize, new_state: bool) {
496 if end > len { self.grow(end - len, new_state); }
497 self.set_range_inbounds(start, end, new_state);
500 fn set_range_inbounds(&mut self, start: usize, end: usize, new_state: bool) {
501 for i in start..end { self.set(i, new_state); }
504 fn get(&self, i: usize) -> bool {
505 let (block, bit) = bit_index(i);
506 (self.blocks[block] & 1 << bit) != 0
509 fn set(&mut self, i: usize, new_state: bool) {
510 let (block, bit) = bit_index(i);
512 self.blocks[block] |= 1 << bit;
514 self.blocks[block] &= !(1 << bit);
518 fn grow(&mut self, amount: usize, new_state: bool) {
519 let unused_trailing_bits = self.blocks.len() * BLOCK_SIZE - self.len;
520 if amount > unused_trailing_bits {
521 let additional_blocks = amount / BLOCK_SIZE + 1;
522 self.blocks.extend(iter::repeat(0).take(additional_blocks));
524 let start = self.len;
526 self.set_range_inbounds(start, start + amount, new_state);
530 // fn uniform_block(state: bool) -> Block {
531 // if state { !0 } else { 0 }
534 fn bit_index(bits: usize) -> (usize, usize) {
535 (bits / BLOCK_SIZE, bits % BLOCK_SIZE)