]> git.lizzy.rs Git - rust.git/blob - src/memory.rs
7cc6a9a8e9d1f0612f9c4e8d914c016327bf2077
[rust.git] / src / memory.rs
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};
5
6 use error::{EvalError, EvalResult};
7 use primval::PrimVal;
8
9 ////////////////////////////////////////////////////////////////////////////////
10 // Allocations and pointers
11 ////////////////////////////////////////////////////////////////////////////////
12
13 #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
14 pub struct AllocId(u64);
15
16 impl fmt::Display for AllocId {
17     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
18         write!(f, "{}", self.0)
19     }
20 }
21
22 #[derive(Debug)]
23 pub struct Allocation {
24     pub bytes: Vec<u8>,
25     pub relocations: BTreeMap<usize, AllocId>,
26     pub undef_mask: UndefMask,
27 }
28
29 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
30 pub struct Pointer {
31     pub alloc_id: AllocId,
32     pub offset: usize,
33 }
34
35 impl Pointer {
36     pub fn offset(self, i: isize) -> Self {
37         Pointer { offset: (self.offset as isize + i) as usize, ..self }
38     }
39 }
40
41 ////////////////////////////////////////////////////////////////////////////////
42 // Top-level interpreter memory
43 ////////////////////////////////////////////////////////////////////////////////
44
45 pub struct Memory {
46     alloc_map: HashMap<AllocId, Allocation>,
47     next_id: AllocId,
48     pub pointer_size: usize,
49 }
50
51 impl Memory {
52     pub fn new(pointer_size: usize) -> Self {
53         Memory {
54             alloc_map: HashMap::new(),
55             next_id: AllocId(0),
56             pointer_size: pointer_size,
57         }
58     }
59
60     pub fn allocate(&mut self, size: usize) -> Pointer {
61         let alloc = Allocation {
62             bytes: vec![0; size],
63             relocations: BTreeMap::new(),
64             undef_mask: UndefMask::new(size),
65         };
66         let id = self.next_id;
67         self.next_id.0 += 1;
68         self.alloc_map.insert(id, alloc);
69         Pointer {
70             alloc_id: id,
71             offset: 0,
72         }
73     }
74
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<()> {
78         if ptr.offset != 0 {
79             // TODO(solson): Report error about non-__rust_allocate'd pointer.
80             return Err(EvalError::Unimplemented(format!("bad pointer offset: {}", ptr.offset)));
81         }
82
83         let alloc = self.get_mut(ptr.alloc_id)?;
84         let size = alloc.bytes.len();
85         if new_size > size {
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
94         }
95
96         Ok(())
97     }
98
99     // TODO(solson): See comment on `reallocate`.
100     pub fn deallocate(&mut self, ptr: Pointer) -> EvalResult<()> {
101         if ptr.offset != 0 {
102             // TODO(solson): Report error about non-__rust_allocate'd pointer.
103             return Err(EvalError::Unimplemented(format!("bad pointer offset: {}", ptr.offset)));
104         }
105
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
109             // it.
110         }
111
112         Ok(())
113     }
114
115     ////////////////////////////////////////////////////////////////////////////////
116     // Allocation accessors
117     ////////////////////////////////////////////////////////////////////////////////
118
119     pub fn get(&self, id: AllocId) -> EvalResult<&Allocation> {
120         self.alloc_map.get(&id).ok_or(EvalError::DanglingPointerDeref)
121     }
122
123     pub fn get_mut(&mut self, id: AllocId) -> EvalResult<&mut Allocation> {
124         self.alloc_map.get_mut(&id).ok_or(EvalError::DanglingPointerDeref)
125     }
126
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);
132
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![];
138
139             let alloc = match self.alloc_map.get(&id) {
140                 Some(a) => a,
141                 None => {
142                     println!("(deallocated)");
143                     continue;
144                 }
145             };
146
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);
151                     }
152                     relocations.push((i, target_id));
153                 }
154                 if alloc.undef_mask.is_range_defined(i, i + 1) {
155                     print!("{:02x} ", alloc.bytes[i]);
156                 } else {
157                     print!("__ ");
158                 }
159             }
160             println!("({} bytes)", alloc.bytes.len());
161
162             if !relocations.is_empty() {
163                 print!("{:1$}", "", prefix.len()); // Print spaces.
164                 let mut pos = 0;
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;
170                 }
171                 println!("");
172             }
173         }
174     }
175
176     ////////////////////////////////////////////////////////////////////////////////
177     // Byte accessors
178     ////////////////////////////////////////////////////////////////////////////////
179
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 {
184                 offset: ptr.offset,
185                 size: size,
186                 len: alloc.bytes.len(),
187             });
188         }
189         Ok(&alloc.bytes[ptr.offset..ptr.offset + size])
190     }
191
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 {
196                 offset: ptr.offset,
197                 size: size,
198                 len: alloc.bytes.len(),
199             });
200         }
201         Ok(&mut alloc.bytes[ptr.offset..ptr.offset + size])
202     }
203
204     fn get_bytes(&self, ptr: Pointer, size: usize) -> EvalResult<&[u8]> {
205         if self.relocations(ptr, size)?.count() != 0 {
206             return Err(EvalError::ReadPointerAsBytes);
207         }
208         self.check_defined(ptr, size)?;
209         self.get_bytes_unchecked(ptr, size)
210     }
211
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)
216     }
217
218     ////////////////////////////////////////////////////////////////////////////////
219     // Reading and writing
220     ////////////////////////////////////////////////////////////////////////////////
221
222     pub fn copy(&mut self, src: Pointer, dest: Pointer, size: usize) -> EvalResult<()> {
223         self.check_relocation_edges(src, size)?;
224
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();
227
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.
231         unsafe {
232             if src.alloc_id == dest.alloc_id {
233                 ptr::copy(src_bytes, dest_bytes, size);
234             } else {
235                 ptr::copy_nonoverlapping(src_bytes, dest_bytes, size);
236             }
237         }
238
239         self.copy_undef_mask(src, dest, size)?;
240         self.copy_relocations(src, dest, size)?;
241
242         Ok(())
243     }
244
245     pub fn read_bytes(&self, ptr: Pointer, size: usize) -> EvalResult<&[u8]> {
246         self.get_bytes(ptr, size)
247     }
248
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);
252         Ok(())
253     }
254
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; }
258         Ok(())
259     }
260
261     pub fn drop_fill(&mut self, ptr: Pointer, size: usize) -> EvalResult<()> {
262         self.write_repeat(ptr, mem::POST_DROP_U8, size)
263     }
264
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),
274         }
275     }
276
277     pub fn write_ptr(&mut self, dest: Pointer, ptr: Pointer) -> EvalResult<()> {
278         {
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();
282         }
283         self.get_mut(dest.alloc_id)?.relocations.insert(dest.offset, ptr.alloc_id);
284         Ok(())
285     }
286
287     pub fn write_primval(&mut self, ptr: Pointer, val: PrimVal) -> EvalResult<()> {
288         let pointer_size = self.pointer_size;
289         match val {
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!(),
301         }
302     }
303
304     pub fn read_bool(&self, ptr: Pointer) -> EvalResult<bool> {
305         let bytes = self.get_bytes(ptr, 1)?;
306         match bytes[0] {
307             0 => Ok(false),
308             1 => Ok(true),
309             _ => Err(EvalError::InvalidBool),
310         }
311     }
312
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)
315     }
316
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())
319     }
320
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())
323     }
324
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())
327     }
328
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())
331     }
332
333     pub fn read_isize(&self, ptr: Pointer) -> EvalResult<i64> {
334         self.read_int(ptr, self.pointer_size)
335     }
336
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)
340     }
341
342     pub fn read_usize(&self, ptr: Pointer) -> EvalResult<u64> {
343         self.read_uint(ptr, self.pointer_size)
344     }
345
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)
349     }
350
351     ////////////////////////////////////////////////////////////////////////////////
352     // Relocations
353     ////////////////////////////////////////////////////////////////////////////////
354
355     fn relocations(&self, ptr: Pointer, size: usize)
356         -> EvalResult<btree_map::Range<usize, AllocId>>
357     {
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)))
361     }
362
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(()); }
367
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;
373
374         let alloc = self.get_mut(ptr.alloc_id)?;
375
376         // Mark parts of the outermost relocations as undefined if they partially fall outside the
377         // given range.
378         if first < start { alloc.undef_mask.set_range(first, start, false); }
379         if last > end { alloc.undef_mask.set_range(end, last, false); }
380
381         // Forget all the relocations.
382         for k in keys { alloc.relocations.remove(&k); }
383
384         Ok(())
385     }
386
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);
392         }
393         Ok(())
394     }
395
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)
401             })
402             .collect();
403         self.get_mut(dest.alloc_id)?.relocations.extend(relocations);
404         Ok(())
405     }
406
407     ////////////////////////////////////////////////////////////////////////////////
408     // Undefined bytes
409     ////////////////////////////////////////////////////////////////////////////////
410
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);
415         for i in 0..size {
416             let defined = self.get(src.alloc_id)?.undef_mask.get(src.offset + i);
417             v.push(defined);
418         }
419         for (i, defined) in v.into_iter().enumerate() {
420             self.get_mut(dest.alloc_id)?.undef_mask.set(dest.offset + i, defined);
421         }
422         Ok(())
423     }
424
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);
429         }
430         Ok(())
431     }
432
433     pub fn mark_definedness(&mut self, ptr: Pointer, size: usize, new_state: bool)
434         -> EvalResult<()>
435     {
436         let mut alloc = self.get_mut(ptr.alloc_id)?;
437         alloc.undef_mask.set_range(ptr.offset, ptr.offset + size, new_state);
438         Ok(())
439     }
440 }
441
442 ////////////////////////////////////////////////////////////////////////////////
443 // Undefined byte tracking
444 ////////////////////////////////////////////////////////////////////////////////
445
446 type Block = u64;
447 const BLOCK_SIZE: usize = 64;
448
449 #[derive(Clone, Debug)]
450 pub struct UndefMask {
451     blocks: Vec<Block>,
452     len: usize,
453 }
454
455 impl UndefMask {
456     fn new(size: usize) -> Self {
457         let mut m = UndefMask {
458             blocks: vec![],
459             len: 0,
460         };
461         m.grow(size, false);
462         m
463     }
464
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; }
470         }
471         true
472     }
473
474     fn set_range(&mut self, start: usize, end: usize, new_state: bool) {
475         let len = self.len;
476         if end > len { self.grow(end - len, new_state); }
477         self.set_range_inbounds(start, end, new_state);
478     }
479
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); }
482     }
483
484     fn get(&self, i: usize) -> bool {
485         let (block, bit) = bit_index(i);
486         (self.blocks[block] & 1 << bit) != 0
487     }
488
489     fn set(&mut self, i: usize, new_state: bool) {
490         let (block, bit) = bit_index(i);
491         if new_state {
492             self.blocks[block] |= 1 << bit;
493         } else {
494             self.blocks[block] &= !(1 << bit);
495         }
496     }
497
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));
503         }
504         let start = self.len;
505         self.len += amount;
506         self.set_range_inbounds(start, start + amount, new_state);
507     }
508 }
509
510 // fn uniform_block(state: bool) -> Block {
511 //     if state { !0 } else { 0 }
512 // }
513
514 fn bit_index(bits: usize) -> (usize, usize) {
515     (bits / BLOCK_SIZE, bits % BLOCK_SIZE)
516 }