]> git.lizzy.rs Git - rust.git/blob - src/memory.rs
21ab8e36c563fd0ad3f887bf9b799d77a44d43ce
[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::{fmt, 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, Hash, PartialEq)]
62 pub struct AllocId(u64);
63
64 impl fmt::Display for AllocId {
65     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66         write!(f, "{}", self.0)
67     }
68 }
69
70 #[derive(Debug)]
71 pub struct Allocation {
72     pub bytes: Vec<u8>,
73     pub relocations: BTreeMap<usize, AllocId>,
74     pub undef_mask: UndefMask,
75 }
76
77 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
78 pub struct Pointer {
79     pub alloc_id: AllocId,
80     pub offset: usize,
81 }
82
83 impl Pointer {
84     pub fn offset(self, i: isize) -> Self {
85         Pointer { offset: (self.offset as isize + i) as usize, ..self }
86     }
87 }
88
89 ////////////////////////////////////////////////////////////////////////////////
90 // Top-level interpreter memory
91 ////////////////////////////////////////////////////////////////////////////////
92
93 pub struct Memory {
94     alloc_map: HashMap<AllocId, Allocation>,
95     next_id: AllocId,
96     pub pointer_size: usize,
97 }
98
99 impl Memory {
100     pub fn new() -> Self {
101         Memory {
102             alloc_map: HashMap::new(),
103             next_id: AllocId(0),
104
105             // TODO(tsion): Should this be host's or target's usize?
106             pointer_size: mem::size_of::<usize>(),
107         }
108     }
109
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),
115         };
116         let id = self.next_id;
117         self.next_id.0 += 1;
118         self.alloc_map.insert(id, alloc);
119         Pointer {
120             alloc_id: id,
121             offset: 0,
122         }
123     }
124
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<()> {
128         if ptr.offset != 0 {
129             // TODO(tsion): Report error about non-__rust_allocate'd pointer.
130             panic!()
131         }
132
133         let alloc = try!(self.get_mut(ptr.alloc_id));
134         let size = alloc.bytes.len();
135         if new_size > size {
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 {
140             unimplemented!()
141             // alloc.bytes.truncate(new_size);
142             // alloc.undef_mask.len = new_size;
143             // TODO: potentially remove relocations
144         }
145
146         Ok(())
147     }
148
149     // TODO(tsion): See comment on `reallocate`.
150     pub fn deallocate(&mut self, ptr: Pointer) -> EvalResult<()> {
151         if ptr.offset != 0 {
152             // TODO(tsion): Report error about non-__rust_allocate'd pointer.
153             panic!()
154         }
155
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
159             // it.
160         }
161
162         Ok(())
163     }
164
165     ////////////////////////////////////////////////////////////////////////////////
166     // Allocation accessors
167     ////////////////////////////////////////////////////////////////////////////////
168
169     pub fn get(&self, id: AllocId) -> EvalResult<&Allocation> {
170         self.alloc_map.get(&id).ok_or(EvalError::DanglingPointerDeref)
171     }
172
173     pub fn get_mut(&mut self, id: AllocId) -> EvalResult<&mut Allocation> {
174         self.alloc_map.get_mut(&id).ok_or(EvalError::DanglingPointerDeref)
175     }
176
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);
182
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![];
188
189             let alloc = match self.alloc_map.get(&id) {
190                 Some(a) => a,
191                 None => {
192                     println!("(deallocated)");
193                     continue;
194                 }
195             };
196
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);
201                     }
202                     relocations.push((i, target_id));
203                 }
204                 if alloc.undef_mask.is_range_defined(i, i + 1) {
205                     print!("{:02x} ", alloc.bytes[i]);
206                 } else {
207                     print!("__ ");
208                 }
209             }
210             println!("({} bytes)", alloc.bytes.len());
211
212             if !relocations.is_empty() {
213                 print!("{:1$}", "", prefix.len()); // Print spaces.
214                 let mut pos = 0;
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;
220                 }
221                 println!("");
222             }
223         }
224     }
225
226     ////////////////////////////////////////////////////////////////////////////////
227     // Byte accessors
228     ////////////////////////////////////////////////////////////////////////////////
229
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);
234         }
235         Ok(&alloc.bytes[ptr.offset..ptr.offset + size])
236     }
237
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);
242         }
243         Ok(&mut alloc.bytes[ptr.offset..ptr.offset + size])
244     }
245
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);
249         }
250         try!(self.check_defined(ptr, size));
251         self.get_bytes_unchecked(ptr, size)
252     }
253
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)
258     }
259
260     ////////////////////////////////////////////////////////////////////////////////
261     // Reading and writing
262     ////////////////////////////////////////////////////////////////////////////////
263
264     pub fn copy(&mut self, src: Pointer, dest: Pointer, size: usize) -> EvalResult<()> {
265         try!(self.check_relocation_edges(src, size));
266
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();
269
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.
273         unsafe {
274             if src.alloc_id == dest.alloc_id {
275                 ptr::copy(src_bytes, dest_bytes, size);
276             } else {
277                 ptr::copy_nonoverlapping(src_bytes, dest_bytes, size);
278             }
279         }
280
281         try!(self.copy_undef_mask(src, dest, size));
282         try!(self.copy_relocations(src, dest, size));
283
284         Ok(())
285     }
286
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);
290         Ok(())
291     }
292
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; }
296         Ok(())
297     }
298
299     pub fn drop_fill(&mut self, ptr: Pointer, size: usize) -> EvalResult<()> {
300         self.write_repeat(ptr, mem::POST_DROP_U8, size)
301     }
302
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),
312         }
313     }
314
315     pub fn write_ptr(&mut self, dest: Pointer, ptr: Pointer) -> EvalResult<()> {
316         {
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();
320         }
321         try!(self.get_mut(dest.alloc_id)).relocations.insert(dest.offset, ptr.alloc_id);
322         Ok(())
323     }
324
325     pub fn write_primval(&mut self, ptr: Pointer, val: PrimVal) -> EvalResult<()> {
326         let pointer_size = self.pointer_size;
327         match val {
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!(),
339         }
340     }
341
342     pub fn read_bool(&self, ptr: Pointer) -> EvalResult<bool> {
343         let bytes = try!(self.get_bytes(ptr, 1));
344         match bytes[0] {
345             0 => Ok(false),
346             1 => Ok(true),
347             _ => Err(EvalError::InvalidBool),
348         }
349     }
350
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)
353     }
354
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())
357     }
358
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())
361     }
362
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())
365     }
366
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())
369     }
370
371     pub fn read_isize(&self, ptr: Pointer) -> EvalResult<i64> {
372         self.read_int(ptr, self.pointer_size)
373     }
374
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)
378     }
379
380     pub fn read_usize(&self, ptr: Pointer) -> EvalResult<u64> {
381         self.read_uint(ptr, self.pointer_size)
382     }
383
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)
387     }
388
389     ////////////////////////////////////////////////////////////////////////////////
390     // Relocations
391     ////////////////////////////////////////////////////////////////////////////////
392
393     fn relocations(&self, ptr: Pointer, size: usize)
394         -> EvalResult<btree_map::Range<usize, AllocId>>
395     {
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)))
399     }
400
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(()); }
405
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;
411
412         let alloc = try!(self.get_mut(ptr.alloc_id));
413
414         // Mark parts of the outermost relocations as undefined if they partially fall outside the
415         // given range.
416         if first < start { alloc.undef_mask.set_range(first, start, false); }
417         if last > end { alloc.undef_mask.set_range(end, last, false); }
418
419         // Forget all the relocations.
420         for k in keys { alloc.relocations.remove(&k); }
421
422         Ok(())
423     }
424
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);
430         }
431         Ok(())
432     }
433
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)
439             })
440             .collect();
441         try!(self.get_mut(dest.alloc_id)).relocations.extend(relocations);
442         Ok(())
443     }
444
445     ////////////////////////////////////////////////////////////////////////////////
446     // Undefined bytes
447     ////////////////////////////////////////////////////////////////////////////////
448
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);
453         for i in 0..size {
454             let defined = try!(self.get(src.alloc_id)).undef_mask.get(src.offset + i);
455             v.push(defined);
456         }
457         for (i, defined) in v.into_iter().enumerate() {
458             try!(self.get_mut(dest.alloc_id)).undef_mask.set(dest.offset + i, defined);
459         }
460         Ok(())
461     }
462
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);
467         }
468         Ok(())
469     }
470
471     pub fn mark_definedness(&mut self, ptr: Pointer, size: usize, new_state: bool)
472         -> EvalResult<()>
473     {
474         let mut alloc = try!(self.get_mut(ptr.alloc_id));
475         alloc.undef_mask.set_range(ptr.offset, ptr.offset + size, new_state);
476         Ok(())
477     }
478 }
479
480 ////////////////////////////////////////////////////////////////////////////////
481 // Undefined byte tracking
482 ////////////////////////////////////////////////////////////////////////////////
483
484 type Block = u64;
485 const BLOCK_SIZE: usize = 64;
486
487 #[derive(Clone, Debug)]
488 pub struct UndefMask {
489     blocks: Vec<Block>,
490     len: usize,
491 }
492
493 impl UndefMask {
494     fn new(size: usize) -> Self {
495         let mut m = UndefMask {
496             blocks: vec![],
497             len: 0,
498         };
499         m.grow(size, false);
500         m
501     }
502
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; }
508         }
509         true
510     }
511
512     fn set_range(&mut self, start: usize, end: usize, new_state: bool) {
513         let len = self.len;
514         if end > len { self.grow(end - len, new_state); }
515         self.set_range_inbounds(start, end, new_state);
516     }
517
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); }
520     }
521
522     fn get(&self, i: usize) -> bool {
523         let (block, bit) = bit_index(i);
524         (self.blocks[block] & 1 << bit) != 0
525     }
526
527     fn set(&mut self, i: usize, new_state: bool) {
528         let (block, bit) = bit_index(i);
529         if new_state {
530             self.blocks[block] |= 1 << bit;
531         } else {
532             self.blocks[block] &= !(1 << bit);
533         }
534     }
535
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));
541         }
542         let start = self.len;
543         self.len += amount;
544         self.set_range_inbounds(start, start + amount, new_state);
545     }
546 }
547
548 // fn uniform_block(state: bool) -> Block {
549 //     if state { !0 } else { 0 }
550 // }
551
552 fn bit_index(bits: usize) -> (usize, usize) {
553     (bits / BLOCK_SIZE, bits % BLOCK_SIZE)
554 }