]> git.lizzy.rs Git - rust.git/blob - src/memory.rs
2a2956bbb4c468592e33a7106fd8d7761e36ff46
[rust.git] / src / memory.rs
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};
5
6 use error::{EvalError, EvalResult};
7 use primval::PrimVal;
8
9 ////////////////////////////////////////////////////////////////////////////////
10 // Value representations
11 ////////////////////////////////////////////////////////////////////////////////
12
13 #[derive(Clone, Debug, Eq, PartialEq)]
14 pub enum Repr {
15     /// Representation for a non-aggregate type such as a boolean, integer, character or pointer.
16     Primitive {
17         size: usize
18     },
19
20     /// The representation for aggregate types including structs, enums, and tuples.
21     Aggregate {
22         /// The size of the discriminant (an integer). Should be between 0 and 8. Always 0 for
23         /// structs and tuples.
24         discr_size: usize,
25
26         /// The size of the entire aggregate, including the discriminant.
27         size: usize,
28
29         /// The representations of the contents of each variant.
30         variants: Vec<Vec<FieldRepr>>,
31     },
32
33     Array {
34         elem_size: usize,
35
36         /// Number of elements.
37         length: usize,
38     },
39 }
40
41 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
42 pub struct FieldRepr {
43     pub offset: usize,
44     pub size: usize,
45 }
46
47 impl Repr {
48     pub fn size(&self) -> usize {
49         match *self {
50             Repr::Primitive { size } => size,
51             Repr::Aggregate { size, .. } => size,
52             Repr::Array { elem_size, length } => elem_size * length,
53         }
54     }
55 }
56
57 ////////////////////////////////////////////////////////////////////////////////
58 // Allocations and pointers
59 ////////////////////////////////////////////////////////////////////////////////
60
61 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
62 pub struct AllocId(u64);
63
64 #[derive(Debug)]
65 pub struct Allocation {
66     pub bytes: Vec<u8>,
67     pub relocations: BTreeMap<usize, AllocId>,
68     pub undef_mask: UndefMask,
69 }
70
71 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
72 pub struct Pointer {
73     pub alloc_id: AllocId,
74     pub offset: usize,
75 }
76
77 impl Pointer {
78     pub fn offset(self, i: isize) -> Self {
79         Pointer { offset: (self.offset as isize + i) as usize, ..self }
80     }
81 }
82
83 ////////////////////////////////////////////////////////////////////////////////
84 // Top-level interpreter memory
85 ////////////////////////////////////////////////////////////////////////////////
86
87 pub struct Memory {
88     alloc_map: HashMap<u64, Allocation>,
89     next_id: u64,
90     pub pointer_size: usize,
91 }
92
93 impl Memory {
94     pub fn new() -> Self {
95         Memory {
96             alloc_map: HashMap::new(),
97             next_id: 0,
98
99             // TODO(tsion): Should this be host's or target's usize?
100             pointer_size: mem::size_of::<usize>(),
101         }
102     }
103
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),
110         };
111         self.alloc_map.insert(self.next_id, alloc);
112         self.next_id += 1;
113         Pointer {
114             alloc_id: id,
115             offset: 0,
116         }
117     }
118
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<()> {
122         if ptr.offset != 0 {
123             // TODO(tsion): Report error about non-__rust_allocate'd pointer.
124             panic!()
125         }
126
127         let alloc = try!(self.get_mut(ptr.alloc_id));
128         let size = alloc.bytes.len();
129         if new_size > size {
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 {
134             unimplemented!()
135             // alloc.bytes.truncate(new_size);
136             // alloc.undef_mask.len = new_size;
137             // TODO: potentially remove relocations
138         }
139
140         Ok(())
141     }
142
143     // TODO(tsion): See comment on `reallocate`.
144     pub fn deallocate(&mut self, ptr: Pointer) -> EvalResult<()> {
145         if ptr.offset != 0 {
146             // TODO(tsion): Report error about non-__rust_allocate'd pointer.
147             panic!()
148         }
149
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
153             // it.
154         }
155
156         Ok(())
157     }
158
159     ////////////////////////////////////////////////////////////////////////////////
160     // Allocation accessors
161     ////////////////////////////////////////////////////////////////////////////////
162
163     pub fn get(&self, id: AllocId) -> EvalResult<&Allocation> {
164         self.alloc_map.get(&id.0).ok_or(EvalError::DanglingPointerDeref)
165     }
166
167     pub fn get_mut(&mut self, id: AllocId) -> EvalResult<&mut Allocation> {
168         self.alloc_map.get_mut(&id.0).ok_or(EvalError::DanglingPointerDeref)
169     }
170
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);
176
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![];
182
183             let alloc = match self.alloc_map.get(&id.0) {
184                 Some(a) => a,
185                 None => {
186                     println!("(deallocated)");
187                     continue;
188                 }
189             };
190
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);
195                     }
196                     relocations.push((i, target_id.0));
197                 }
198                 if alloc.undef_mask.is_range_defined(i, i+1) {
199                     print!("{:02x} ", alloc.bytes[i]);
200                 } else {
201                     print!("__ ");
202                 }
203             }
204             println!("({} bytes)", alloc.bytes.len());
205
206             if !relocations.is_empty() {
207                 print!("{:1$}", "", prefix.len()); // Print spaces.
208                 let mut pos = 0;
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;
214                 }
215                 println!("");
216             }
217         }
218     }
219
220     ////////////////////////////////////////////////////////////////////////////////
221     // Byte accessors
222     ////////////////////////////////////////////////////////////////////////////////
223
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);
228         }
229         Ok(&alloc.bytes[ptr.offset..ptr.offset + size])
230     }
231
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);
236         }
237         Ok(&mut alloc.bytes[ptr.offset..ptr.offset + size])
238     }
239
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);
243         }
244         try!(self.check_defined(ptr, size));
245         self.get_bytes_unchecked(ptr, size)
246     }
247
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)
252     }
253
254     ////////////////////////////////////////////////////////////////////////////////
255     // Reading and writing
256     ////////////////////////////////////////////////////////////////////////////////
257
258     pub fn copy(&mut self, src: Pointer, dest: Pointer, size: usize) -> EvalResult<()> {
259         try!(self.check_relocation_edges(src, size));
260
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();
263
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.
267         unsafe {
268             if src.alloc_id == dest.alloc_id {
269                 ptr::copy(src_bytes, dest_bytes, size);
270             } else {
271                 ptr::copy_nonoverlapping(src_bytes, dest_bytes, size);
272             }
273         }
274
275         try!(self.copy_undef_mask(src, dest, size));
276         try!(self.copy_relocations(src, dest, size));
277
278         Ok(())
279     }
280
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);
284         Ok(())
285     }
286
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; }
290         Ok(())
291     }
292
293     pub fn drop_fill(&mut self, ptr: Pointer, size: usize) -> EvalResult<()> {
294         self.write_repeat(ptr, mem::POST_DROP_U8, size)
295     }
296
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),
306         }
307     }
308
309     pub fn write_ptr(&mut self, dest: Pointer, ptr: Pointer) -> EvalResult<()> {
310         {
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();
314         }
315         try!(self.get_mut(dest.alloc_id)).relocations.insert(dest.offset, ptr.alloc_id);
316         Ok(())
317     }
318
319     pub fn write_primval(&mut self, ptr: Pointer, val: PrimVal) -> EvalResult<()> {
320         let pointer_size = self.pointer_size;
321         match val {
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!(),
333         }
334     }
335
336     pub fn read_bool(&self, ptr: Pointer) -> EvalResult<bool> {
337         let bytes = try!(self.get_bytes(ptr, 1));
338         match bytes[0] {
339             0 => Ok(false),
340             1 => Ok(true),
341             _ => Err(EvalError::InvalidBool),
342         }
343     }
344
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)
347     }
348
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())
351     }
352
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())
355     }
356
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())
359     }
360
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())
363     }
364
365     pub fn read_isize(&self, ptr: Pointer) -> EvalResult<i64> {
366         self.read_int(ptr, self.pointer_size)
367     }
368
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)
372     }
373
374     pub fn read_usize(&self, ptr: Pointer) -> EvalResult<u64> {
375         self.read_uint(ptr, self.pointer_size)
376     }
377
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)
381     }
382
383     ////////////////////////////////////////////////////////////////////////////////
384     // Relocations
385     ////////////////////////////////////////////////////////////////////////////////
386
387     fn relocations(&self, ptr: Pointer, size: usize)
388         -> EvalResult<btree_map::Range<usize, AllocId>>
389     {
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)))
393     }
394
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(()); }
399
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;
405
406         let alloc = try!(self.get_mut(ptr.alloc_id));
407
408         // Mark parts of the outermost relocations as undefined if they partially fall outside the
409         // given range.
410         if first < start { alloc.undef_mask.set_range(first, start, false); }
411         if last > end { alloc.undef_mask.set_range(end, last, false); }
412
413         // Forget all the relocations.
414         for k in keys { alloc.relocations.remove(&k); }
415
416         Ok(())
417     }
418
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);
424         }
425         Ok(())
426     }
427
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)
433             })
434             .collect();
435         try!(self.get_mut(dest.alloc_id)).relocations.extend(relocations);
436         Ok(())
437     }
438
439     ////////////////////////////////////////////////////////////////////////////////
440     // Undefined bytes
441     ////////////////////////////////////////////////////////////////////////////////
442
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);
447         for i in 0..size {
448             let defined = try!(self.get(src.alloc_id)).undef_mask.get(src.offset + i);
449             v.push(defined);
450         }
451         for (i, defined) in v.into_iter().enumerate() {
452             try!(self.get_mut(dest.alloc_id)).undef_mask.set(dest.offset + i, defined);
453         }
454         Ok(())
455     }
456
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);
461         }
462         Ok(())
463     }
464
465     pub fn mark_definedness(&mut self, ptr: Pointer, size: usize, new_state: bool)
466         -> EvalResult<()>
467     {
468         let mut alloc = try!(self.get_mut(ptr.alloc_id));
469         alloc.undef_mask.set_range(ptr.offset, ptr.offset + size, new_state);
470         Ok(())
471     }
472 }
473
474 ////////////////////////////////////////////////////////////////////////////////
475 // Undefined byte tracking
476 ////////////////////////////////////////////////////////////////////////////////
477
478 type Block = u64;
479 const BLOCK_SIZE: usize = 64;
480
481 #[derive(Clone, Debug)]
482 pub struct UndefMask {
483     blocks: Vec<Block>,
484     len: usize,
485 }
486
487 impl UndefMask {
488     fn new(size: usize) -> Self {
489         let mut m = UndefMask {
490             blocks: vec![],
491             len: 0,
492         };
493         m.grow(size, false);
494         m
495     }
496
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; }
502         }
503         true
504     }
505
506     fn set_range(&mut self, start: usize, end: usize, new_state: bool) {
507         let len = self.len;
508         if end > len { self.grow(end - len, new_state); }
509         self.set_range_inbounds(start, end, new_state);
510     }
511
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); }
514     }
515
516     fn get(&self, i: usize) -> bool {
517         let (block, bit) = bit_index(i);
518         (self.blocks[block] & 1 << bit) != 0
519     }
520
521     fn set(&mut self, i: usize, new_state: bool) {
522         let (block, bit) = bit_index(i);
523         if new_state {
524             self.blocks[block] |= 1 << bit;
525         } else {
526             self.blocks[block] &= !(1 << bit);
527         }
528     }
529
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));
535         }
536         let start = self.len;
537         self.len += amount;
538         self.set_range_inbounds(start, start + amount, new_state);
539     }
540 }
541
542 // fn uniform_block(state: bool) -> Block {
543 //     if state { !0 } else { 0 }
544 // }
545
546 fn bit_index(bits: usize) -> (usize, usize) {
547     (bits / BLOCK_SIZE, bits % BLOCK_SIZE)
548 }