1 use 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 // Allocations and pointers
11 ////////////////////////////////////////////////////////////////////////////////
13 #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
14 pub struct AllocId(u64);
16 impl fmt::Display for AllocId {
17 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
18 write!(f, "{}", self.0)
23 pub struct Allocation {
25 pub relocations: BTreeMap<usize, AllocId>,
26 pub undef_mask: UndefMask,
29 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
31 pub alloc_id: AllocId,
36 pub fn offset(self, i: isize) -> Self {
37 Pointer { offset: (self.offset as isize + i) as usize, ..self }
41 ////////////////////////////////////////////////////////////////////////////////
42 // Top-level interpreter memory
43 ////////////////////////////////////////////////////////////////////////////////
46 alloc_map: HashMap<AllocId, Allocation>,
48 pub pointer_size: usize,
52 pub fn new(pointer_size: usize) -> Self {
54 alloc_map: HashMap::new(),
56 pointer_size: pointer_size,
60 pub fn allocate(&mut self, size: usize) -> Pointer {
61 let alloc = Allocation {
63 relocations: BTreeMap::new(),
64 undef_mask: UndefMask::new(size),
66 let id = self.next_id;
68 self.alloc_map.insert(id, alloc);
75 // TODO(solson): Track which allocations were returned from __rust_allocate and report an error
76 // when reallocating/deallocating any others.
77 pub fn reallocate(&mut self, ptr: Pointer, new_size: usize) -> EvalResult<()> {
79 // TODO(solson): Report error about non-__rust_allocate'd pointer.
80 return Err(EvalError::Unimplemented(format!("bad pointer offset: {}", ptr.offset)));
83 let alloc = self.get_mut(ptr.alloc_id)?;
84 let size = alloc.bytes.len();
86 let amount = new_size - size;
87 alloc.bytes.extend(iter::repeat(0).take(amount));
88 alloc.undef_mask.grow(amount, false);
89 } else if size > new_size {
90 return Err(EvalError::Unimplemented(format!("unimplemented allocation relocation")));
91 // alloc.bytes.truncate(new_size);
92 // alloc.undef_mask.len = new_size;
93 // TODO: potentially remove relocations
99 // TODO(solson): See comment on `reallocate`.
100 pub fn deallocate(&mut self, ptr: Pointer) -> EvalResult<()> {
102 // TODO(solson): Report error about non-__rust_allocate'd pointer.
103 return Err(EvalError::Unimplemented(format!("bad pointer offset: {}", ptr.offset)));
106 if self.alloc_map.remove(&ptr.alloc_id).is_none() {
107 // TODO(solson): Report error about erroneous free. This is blocked on properly tracking
108 // already-dropped state since this if-statement is entered even in safe code without
115 ////////////////////////////////////////////////////////////////////////////////
116 // Allocation accessors
117 ////////////////////////////////////////////////////////////////////////////////
119 pub fn get(&self, id: AllocId) -> EvalResult<&Allocation> {
120 self.alloc_map.get(&id).ok_or(EvalError::DanglingPointerDeref)
123 pub fn get_mut(&mut self, id: AllocId) -> EvalResult<&mut Allocation> {
124 self.alloc_map.get_mut(&id).ok_or(EvalError::DanglingPointerDeref)
127 /// Print an allocation and all allocations it points to, recursively.
128 pub fn dump(&self, id: AllocId) {
129 let mut allocs_seen = HashSet::new();
130 let mut allocs_to_print = VecDeque::new();
131 allocs_to_print.push_back(id);
133 while let Some(id) = allocs_to_print.pop_front() {
134 allocs_seen.insert(id);
135 let prefix = format!("Alloc {:<5} ", format!("{}:", id));
136 print!("{}", prefix);
137 let mut relocations = vec![];
139 let alloc = match self.alloc_map.get(&id) {
142 println!("(deallocated)");
147 for i in 0..alloc.bytes.len() {
148 if let Some(&target_id) = alloc.relocations.get(&i) {
149 if !allocs_seen.contains(&target_id) {
150 allocs_to_print.push_back(target_id);
152 relocations.push((i, target_id));
154 if alloc.undef_mask.is_range_defined(i, i + 1) {
155 print!("{:02x} ", alloc.bytes[i]);
160 println!("({} bytes)", alloc.bytes.len());
162 if !relocations.is_empty() {
163 print!("{:1$}", "", prefix.len()); // Print spaces.
165 let relocation_width = (self.pointer_size - 1) * 3;
166 for (i, target_id) in relocations {
167 print!("{:1$}", "", (i - pos) * 3);
168 print!("└{0:─^1$}┘ ", format!("({})", target_id), relocation_width);
169 pos = i + self.pointer_size;
176 ////////////////////////////////////////////////////////////////////////////////
178 ////////////////////////////////////////////////////////////////////////////////
180 fn get_bytes_unchecked(&self, ptr: Pointer, size: usize) -> EvalResult<&[u8]> {
181 let alloc = self.get(ptr.alloc_id)?;
182 if ptr.offset + size > alloc.bytes.len() {
183 return Err(EvalError::PointerOutOfBounds {
186 len: alloc.bytes.len(),
189 Ok(&alloc.bytes[ptr.offset..ptr.offset + size])
192 fn get_bytes_unchecked_mut(&mut self, ptr: Pointer, size: usize) -> EvalResult<&mut [u8]> {
193 let alloc = self.get_mut(ptr.alloc_id)?;
194 if ptr.offset + size > alloc.bytes.len() {
195 return Err(EvalError::PointerOutOfBounds {
198 len: alloc.bytes.len(),
201 Ok(&mut alloc.bytes[ptr.offset..ptr.offset + size])
204 fn get_bytes(&self, ptr: Pointer, size: usize) -> EvalResult<&[u8]> {
205 if self.relocations(ptr, size)?.count() != 0 {
206 return Err(EvalError::ReadPointerAsBytes);
208 self.check_defined(ptr, size)?;
209 self.get_bytes_unchecked(ptr, size)
212 fn get_bytes_mut(&mut self, ptr: Pointer, size: usize) -> EvalResult<&mut [u8]> {
213 self.clear_relocations(ptr, size)?;
214 self.mark_definedness(ptr, size, true)?;
215 self.get_bytes_unchecked_mut(ptr, size)
218 ////////////////////////////////////////////////////////////////////////////////
219 // Reading and writing
220 ////////////////////////////////////////////////////////////////////////////////
222 pub fn copy(&mut self, src: Pointer, dest: Pointer, size: usize) -> EvalResult<()> {
223 self.check_relocation_edges(src, size)?;
225 let src_bytes = self.get_bytes_unchecked_mut(src, size)?.as_mut_ptr();
226 let dest_bytes = self.get_bytes_mut(dest, size)?.as_mut_ptr();
228 // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
229 // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
230 // `dest` could possibly overlap.
232 if src.alloc_id == dest.alloc_id {
233 ptr::copy(src_bytes, dest_bytes, size);
235 ptr::copy_nonoverlapping(src_bytes, dest_bytes, size);
239 self.copy_undef_mask(src, dest, size)?;
240 self.copy_relocations(src, dest, size)?;
245 pub fn read_bytes(&self, ptr: Pointer, size: usize) -> EvalResult<&[u8]> {
246 self.get_bytes(ptr, size)
249 pub fn write_bytes(&mut self, ptr: Pointer, src: &[u8]) -> EvalResult<()> {
250 let bytes = self.get_bytes_mut(ptr, src.len())?;
251 bytes.clone_from_slice(src);
255 pub fn write_repeat(&mut self, ptr: Pointer, val: u8, count: usize) -> EvalResult<()> {
256 let bytes = self.get_bytes_mut(ptr, count)?;
257 for b in bytes { *b = val; }
261 pub fn drop_fill(&mut self, ptr: Pointer, size: usize) -> EvalResult<()> {
262 self.write_repeat(ptr, mem::POST_DROP_U8, size)
265 pub fn read_ptr(&self, ptr: Pointer) -> EvalResult<Pointer> {
266 let size = self.pointer_size;
267 self.check_defined(ptr, size)?;
268 let offset = self.get_bytes_unchecked(ptr, size)?
269 .read_uint::<NativeEndian>(size).unwrap() as usize;
270 let alloc = self.get(ptr.alloc_id)?;
271 match alloc.relocations.get(&ptr.offset) {
272 Some(&alloc_id) => Ok(Pointer { alloc_id: alloc_id, offset: offset }),
273 None => Err(EvalError::ReadBytesAsPointer),
277 pub fn write_ptr(&mut self, dest: Pointer, ptr: Pointer) -> EvalResult<()> {
279 let size = self.pointer_size;
280 let mut bytes = self.get_bytes_mut(dest, size)?;
281 bytes.write_uint::<NativeEndian>(ptr.offset as u64, size).unwrap();
283 self.get_mut(dest.alloc_id)?.relocations.insert(dest.offset, ptr.alloc_id);
287 pub fn write_primval(&mut self, ptr: Pointer, val: PrimVal) -> EvalResult<()> {
288 let pointer_size = self.pointer_size;
290 PrimVal::Bool(b) => self.write_bool(ptr, b),
291 PrimVal::I8(n) => self.write_int(ptr, n as i64, 1),
292 PrimVal::I16(n) => self.write_int(ptr, n as i64, 2),
293 PrimVal::I32(n) => self.write_int(ptr, n as i64, 4),
294 PrimVal::I64(n) => self.write_int(ptr, n as i64, 8),
295 PrimVal::U8(n) => self.write_uint(ptr, n as u64, 1),
296 PrimVal::U16(n) => self.write_uint(ptr, n as u64, 2),
297 PrimVal::U32(n) => self.write_uint(ptr, n as u64, 4),
298 PrimVal::U64(n) => self.write_uint(ptr, n as u64, 8),
299 PrimVal::IntegerPtr(n) => self.write_uint(ptr, n as u64, pointer_size),
300 PrimVal::AbstractPtr(_p) => unimplemented!(),
304 pub fn read_bool(&self, ptr: Pointer) -> EvalResult<bool> {
305 let bytes = self.get_bytes(ptr, 1)?;
309 _ => Err(EvalError::InvalidBool),
313 pub fn write_bool(&mut self, ptr: Pointer, b: bool) -> EvalResult<()> {
314 self.get_bytes_mut(ptr, 1).map(|bytes| bytes[0] = b as u8)
317 pub fn read_int(&self, ptr: Pointer, size: usize) -> EvalResult<i64> {
318 self.get_bytes(ptr, size).map(|mut b| b.read_int::<NativeEndian>(size).unwrap())
321 pub fn write_int(&mut self, ptr: Pointer, n: i64, size: usize) -> EvalResult<()> {
322 self.get_bytes_mut(ptr, size).map(|mut b| b.write_int::<NativeEndian>(n, size).unwrap())
325 pub fn read_uint(&self, ptr: Pointer, size: usize) -> EvalResult<u64> {
326 self.get_bytes(ptr, size).map(|mut b| b.read_uint::<NativeEndian>(size).unwrap())
329 pub fn write_uint(&mut self, ptr: Pointer, n: u64, size: usize) -> EvalResult<()> {
330 self.get_bytes_mut(ptr, size).map(|mut b| b.write_uint::<NativeEndian>(n, size).unwrap())
333 pub fn read_isize(&self, ptr: Pointer) -> EvalResult<i64> {
334 self.read_int(ptr, self.pointer_size)
337 pub fn write_isize(&mut self, ptr: Pointer, n: i64) -> EvalResult<()> {
338 let size = self.pointer_size;
339 self.write_int(ptr, n, size)
342 pub fn read_usize(&self, ptr: Pointer) -> EvalResult<u64> {
343 self.read_uint(ptr, self.pointer_size)
346 pub fn write_usize(&mut self, ptr: Pointer, n: u64) -> EvalResult<()> {
347 let size = self.pointer_size;
348 self.write_uint(ptr, n, size)
351 ////////////////////////////////////////////////////////////////////////////////
353 ////////////////////////////////////////////////////////////////////////////////
355 fn relocations(&self, ptr: Pointer, size: usize)
356 -> EvalResult<btree_map::Range<usize, AllocId>>
358 let start = ptr.offset.saturating_sub(self.pointer_size - 1);
359 let end = start + size;
360 Ok(self.get(ptr.alloc_id)?.relocations.range(Included(&start), Excluded(&end)))
363 fn clear_relocations(&mut self, ptr: Pointer, size: usize) -> EvalResult<()> {
364 // Find all relocations overlapping the given range.
365 let keys: Vec<_> = self.relocations(ptr, size)?.map(|(&k, _)| k).collect();
366 if keys.is_empty() { return Ok(()); }
368 // Find the start and end of the given range and its outermost relocations.
369 let start = ptr.offset;
370 let end = start + size;
371 let first = *keys.first().unwrap();
372 let last = *keys.last().unwrap() + self.pointer_size;
374 let alloc = self.get_mut(ptr.alloc_id)?;
376 // Mark parts of the outermost relocations as undefined if they partially fall outside the
378 if first < start { alloc.undef_mask.set_range(first, start, false); }
379 if last > end { alloc.undef_mask.set_range(end, last, false); }
381 // Forget all the relocations.
382 for k in keys { alloc.relocations.remove(&k); }
387 fn check_relocation_edges(&self, ptr: Pointer, size: usize) -> EvalResult<()> {
388 let overlapping_start = self.relocations(ptr, 0)?.count();
389 let overlapping_end = self.relocations(ptr.offset(size as isize), 0)?.count();
390 if overlapping_start + overlapping_end != 0 {
391 return Err(EvalError::ReadPointerAsBytes);
396 fn copy_relocations(&mut self, src: Pointer, dest: Pointer, size: usize) -> EvalResult<()> {
397 let relocations: Vec<_> = self.relocations(src, size)?
398 .map(|(&offset, &alloc_id)| {
399 // Update relocation offsets for the new positions in the destination allocation.
400 (offset + dest.offset - src.offset, alloc_id)
403 self.get_mut(dest.alloc_id)?.relocations.extend(relocations);
407 ////////////////////////////////////////////////////////////////////////////////
409 ////////////////////////////////////////////////////////////////////////////////
411 // FIXME(solson): This is a very naive, slow version.
412 fn copy_undef_mask(&mut self, src: Pointer, dest: Pointer, size: usize) -> EvalResult<()> {
413 // The bits have to be saved locally before writing to dest in case src and dest overlap.
414 let mut v = Vec::with_capacity(size);
416 let defined = self.get(src.alloc_id)?.undef_mask.get(src.offset + i);
419 for (i, defined) in v.into_iter().enumerate() {
420 self.get_mut(dest.alloc_id)?.undef_mask.set(dest.offset + i, defined);
425 fn check_defined(&self, ptr: Pointer, size: usize) -> EvalResult<()> {
426 let alloc = self.get(ptr.alloc_id)?;
427 if !alloc.undef_mask.is_range_defined(ptr.offset, ptr.offset + size) {
428 return Err(EvalError::ReadUndefBytes);
433 pub fn mark_definedness(&mut self, ptr: Pointer, size: usize, new_state: bool)
436 let mut alloc = self.get_mut(ptr.alloc_id)?;
437 alloc.undef_mask.set_range(ptr.offset, ptr.offset + size, new_state);
442 ////////////////////////////////////////////////////////////////////////////////
443 // Undefined byte tracking
444 ////////////////////////////////////////////////////////////////////////////////
447 const BLOCK_SIZE: usize = 64;
449 #[derive(Clone, Debug)]
450 pub struct UndefMask {
456 fn new(size: usize) -> Self {
457 let mut m = UndefMask {
465 /// Check whether the range `start..end` (end-exclusive) is entirely defined.
466 fn is_range_defined(&self, start: usize, end: usize) -> bool {
467 if end > self.len { return false; }
468 for i in start..end {
469 if !self.get(i) { return false; }
474 fn set_range(&mut self, start: usize, end: usize, new_state: bool) {
476 if end > len { self.grow(end - len, new_state); }
477 self.set_range_inbounds(start, end, new_state);
480 fn set_range_inbounds(&mut self, start: usize, end: usize, new_state: bool) {
481 for i in start..end { self.set(i, new_state); }
484 fn get(&self, i: usize) -> bool {
485 let (block, bit) = bit_index(i);
486 (self.blocks[block] & 1 << bit) != 0
489 fn set(&mut self, i: usize, new_state: bool) {
490 let (block, bit) = bit_index(i);
492 self.blocks[block] |= 1 << bit;
494 self.blocks[block] &= !(1 << bit);
498 fn grow(&mut self, amount: usize, new_state: bool) {
499 let unused_trailing_bits = self.blocks.len() * BLOCK_SIZE - self.len;
500 if amount > unused_trailing_bits {
501 let additional_blocks = amount / BLOCK_SIZE + 1;
502 self.blocks.extend(iter::repeat(0).take(additional_blocks));
504 let start = self.len;
506 self.set_range_inbounds(start, start + amount, new_state);
510 // fn uniform_block(state: bool) -> Block {
511 // if state { !0 } else { 0 }
514 fn bit_index(bits: usize) -> (usize, usize) {
515 (bits / BLOCK_SIZE, bits % BLOCK_SIZE)