]> git.proxmox.com Git - rustc.git/blob - src/librustc/mir/interpret/allocation.rs
New upstream version 1.43.0+dfsg1
[rustc.git] / src / librustc / mir / interpret / allocation.rs
1 //! The virtual memory representation of the MIR interpreter.
2
3 use super::{
4 read_target_uint, write_target_uint, AllocId, InterpResult, Pointer, Scalar, ScalarMaybeUndef,
5 };
6
7 use crate::ty::layout::{Align, Size};
8
9 use rustc_ast::ast::Mutability;
10 use rustc_data_structures::sorted_map::SortedMap;
11 use rustc_target::abi::HasDataLayout;
12 use std::borrow::Cow;
13 use std::iter;
14 use std::ops::{Deref, DerefMut, Range};
15
16 // NOTE: When adding new fields, make sure to adjust the `Snapshot` impl in
17 // `src/librustc_mir/interpret/snapshot.rs`.
18 #[derive(
19 Clone,
20 Debug,
21 Eq,
22 PartialEq,
23 PartialOrd,
24 Ord,
25 Hash,
26 RustcEncodable,
27 RustcDecodable,
28 HashStable
29 )]
30 pub struct Allocation<Tag = (), Extra = ()> {
31 /// The actual bytes of the allocation.
32 /// Note that the bytes of a pointer represent the offset of the pointer.
33 bytes: Vec<u8>,
34 /// Maps from byte addresses to extra data for each pointer.
35 /// Only the first byte of a pointer is inserted into the map; i.e.,
36 /// every entry in this map applies to `pointer_size` consecutive bytes starting
37 /// at the given offset.
38 relocations: Relocations<Tag>,
39 /// Denotes which part of this allocation is initialized.
40 undef_mask: UndefMask,
41 /// The size of the allocation. Currently, must always equal `bytes.len()`.
42 pub size: Size,
43 /// The alignment of the allocation to detect unaligned reads.
44 pub align: Align,
45 /// `true` if the allocation is mutable.
46 /// Also used by codegen to determine if a static should be put into mutable memory,
47 /// which happens for `static mut` and `static` with interior mutability.
48 pub mutability: Mutability,
49 /// Extra state for the machine.
50 pub extra: Extra,
51 }
52
53 pub trait AllocationExtra<Tag>: ::std::fmt::Debug + Clone {
54 // There is no constructor in here because the constructor's type depends
55 // on `MemoryKind`, and making things sufficiently generic leads to painful
56 // inference failure.
57
58 /// Hook for performing extra checks on a memory read access.
59 ///
60 /// Takes read-only access to the allocation so we can keep all the memory read
61 /// operations take `&self`. Use a `RefCell` in `AllocExtra` if you
62 /// need to mutate.
63 #[inline(always)]
64 fn memory_read(
65 _alloc: &Allocation<Tag, Self>,
66 _ptr: Pointer<Tag>,
67 _size: Size,
68 ) -> InterpResult<'tcx> {
69 Ok(())
70 }
71
72 /// Hook for performing extra checks on a memory write access.
73 #[inline(always)]
74 fn memory_written(
75 _alloc: &mut Allocation<Tag, Self>,
76 _ptr: Pointer<Tag>,
77 _size: Size,
78 ) -> InterpResult<'tcx> {
79 Ok(())
80 }
81
82 /// Hook for performing extra checks on a memory deallocation.
83 /// `size` will be the size of the allocation.
84 #[inline(always)]
85 fn memory_deallocated(
86 _alloc: &mut Allocation<Tag, Self>,
87 _ptr: Pointer<Tag>,
88 _size: Size,
89 ) -> InterpResult<'tcx> {
90 Ok(())
91 }
92 }
93
94 // For `Tag = ()` and no extra state, we have a trivial implementation.
95 impl AllocationExtra<()> for () {}
96
97 // The constructors are all without extra; the extra gets added by a machine hook later.
98 impl<Tag> Allocation<Tag> {
99 /// Creates a read-only allocation initialized by the given bytes
100 pub fn from_bytes<'a>(slice: impl Into<Cow<'a, [u8]>>, align: Align) -> Self {
101 let bytes = slice.into().into_owned();
102 let size = Size::from_bytes(bytes.len() as u64);
103 Self {
104 bytes,
105 relocations: Relocations::new(),
106 undef_mask: UndefMask::new(size, true),
107 size,
108 align,
109 mutability: Mutability::Not,
110 extra: (),
111 }
112 }
113
114 pub fn from_byte_aligned_bytes<'a>(slice: impl Into<Cow<'a, [u8]>>) -> Self {
115 Allocation::from_bytes(slice, Align::from_bytes(1).unwrap())
116 }
117
118 pub fn undef(size: Size, align: Align) -> Self {
119 assert_eq!(size.bytes() as usize as u64, size.bytes());
120 Allocation {
121 bytes: vec![0; size.bytes() as usize],
122 relocations: Relocations::new(),
123 undef_mask: UndefMask::new(size, false),
124 size,
125 align,
126 mutability: Mutability::Mut,
127 extra: (),
128 }
129 }
130 }
131
132 impl Allocation<(), ()> {
133 /// Add Tag and Extra fields
134 pub fn with_tags_and_extra<T, E>(
135 self,
136 mut tagger: impl FnMut(AllocId) -> T,
137 extra: E,
138 ) -> Allocation<T, E> {
139 Allocation {
140 bytes: self.bytes,
141 size: self.size,
142 relocations: Relocations::from_presorted(
143 self.relocations
144 .iter()
145 // The allocations in the relocations (pointers stored *inside* this allocation)
146 // all get the base pointer tag.
147 .map(|&(offset, ((), alloc))| {
148 let tag = tagger(alloc);
149 (offset, (tag, alloc))
150 })
151 .collect(),
152 ),
153 undef_mask: self.undef_mask,
154 align: self.align,
155 mutability: self.mutability,
156 extra,
157 }
158 }
159 }
160
161 /// Raw accessors. Provide access to otherwise private bytes.
162 impl<Tag, Extra> Allocation<Tag, Extra> {
163 pub fn len(&self) -> usize {
164 self.size.bytes() as usize
165 }
166
167 /// Looks at a slice which may describe undefined bytes or describe a relocation. This differs
168 /// from `get_bytes_with_undef_and_ptr` in that it does no relocation checks (even on the
169 /// edges) at all. It further ignores `AllocationExtra` callbacks.
170 /// This must not be used for reads affecting the interpreter execution.
171 pub fn inspect_with_undef_and_ptr_outside_interpreter(&self, range: Range<usize>) -> &[u8] {
172 &self.bytes[range]
173 }
174
175 /// Returns the undef mask.
176 pub fn undef_mask(&self) -> &UndefMask {
177 &self.undef_mask
178 }
179
180 /// Returns the relocation list.
181 pub fn relocations(&self) -> &Relocations<Tag> {
182 &self.relocations
183 }
184 }
185
186 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx Allocation {}
187
188 /// Byte accessors.
189 impl<'tcx, Tag: Copy, Extra: AllocationExtra<Tag>> Allocation<Tag, Extra> {
190 /// Just a small local helper function to avoid a bit of code repetition.
191 /// Returns the range of this allocation that was meant.
192 #[inline]
193 fn check_bounds(&self, offset: Size, size: Size) -> Range<usize> {
194 let end = offset + size; // This does overflow checking.
195 assert_eq!(
196 end.bytes() as usize as u64,
197 end.bytes(),
198 "cannot handle this access on this host architecture"
199 );
200 let end = end.bytes() as usize;
201 assert!(
202 end <= self.len(),
203 "Out-of-bounds access at offset {}, size {} in allocation of size {}",
204 offset.bytes(),
205 size.bytes(),
206 self.len()
207 );
208 (offset.bytes() as usize)..end
209 }
210
211 /// The last argument controls whether we error out when there are undefined
212 /// or pointer bytes. You should never call this, call `get_bytes` or
213 /// `get_bytes_with_undef_and_ptr` instead,
214 ///
215 /// This function also guarantees that the resulting pointer will remain stable
216 /// even when new allocations are pushed to the `HashMap`. `copy_repeatedly` relies
217 /// on that.
218 ///
219 /// It is the caller's responsibility to check bounds and alignment beforehand.
220 fn get_bytes_internal(
221 &self,
222 cx: &impl HasDataLayout,
223 ptr: Pointer<Tag>,
224 size: Size,
225 check_defined_and_ptr: bool,
226 ) -> InterpResult<'tcx, &[u8]> {
227 let range = self.check_bounds(ptr.offset, size);
228
229 if check_defined_and_ptr {
230 self.check_defined(ptr, size)?;
231 self.check_relocations(cx, ptr, size)?;
232 } else {
233 // We still don't want relocations on the *edges*.
234 self.check_relocation_edges(cx, ptr, size)?;
235 }
236
237 AllocationExtra::memory_read(self, ptr, size)?;
238
239 Ok(&self.bytes[range])
240 }
241
242 /// Checks that these bytes are initialized and not pointer bytes, and then return them
243 /// as a slice.
244 ///
245 /// It is the caller's responsibility to check bounds and alignment beforehand.
246 /// Most likely, you want to use the `PlaceTy` and `OperandTy`-based methods
247 /// on `InterpCx` instead.
248 #[inline]
249 pub fn get_bytes(
250 &self,
251 cx: &impl HasDataLayout,
252 ptr: Pointer<Tag>,
253 size: Size,
254 ) -> InterpResult<'tcx, &[u8]> {
255 self.get_bytes_internal(cx, ptr, size, true)
256 }
257
258 /// It is the caller's responsibility to handle undefined and pointer bytes.
259 /// However, this still checks that there are no relocations on the *edges*.
260 ///
261 /// It is the caller's responsibility to check bounds and alignment beforehand.
262 #[inline]
263 pub fn get_bytes_with_undef_and_ptr(
264 &self,
265 cx: &impl HasDataLayout,
266 ptr: Pointer<Tag>,
267 size: Size,
268 ) -> InterpResult<'tcx, &[u8]> {
269 self.get_bytes_internal(cx, ptr, size, false)
270 }
271
272 /// Just calling this already marks everything as defined and removes relocations,
273 /// so be sure to actually put data there!
274 ///
275 /// It is the caller's responsibility to check bounds and alignment beforehand.
276 /// Most likely, you want to use the `PlaceTy` and `OperandTy`-based methods
277 /// on `InterpCx` instead.
278 pub fn get_bytes_mut(
279 &mut self,
280 cx: &impl HasDataLayout,
281 ptr: Pointer<Tag>,
282 size: Size,
283 ) -> InterpResult<'tcx, &mut [u8]> {
284 let range = self.check_bounds(ptr.offset, size);
285
286 self.mark_definedness(ptr, size, true);
287 self.clear_relocations(cx, ptr, size)?;
288
289 AllocationExtra::memory_written(self, ptr, size)?;
290
291 Ok(&mut self.bytes[range])
292 }
293 }
294
295 /// Reading and writing.
296 impl<'tcx, Tag: Copy, Extra: AllocationExtra<Tag>> Allocation<Tag, Extra> {
297 /// Reads bytes until a `0` is encountered. Will error if the end of the allocation is reached
298 /// before a `0` is found.
299 ///
300 /// Most likely, you want to call `Memory::read_c_str` instead of this method.
301 pub fn read_c_str(
302 &self,
303 cx: &impl HasDataLayout,
304 ptr: Pointer<Tag>,
305 ) -> InterpResult<'tcx, &[u8]> {
306 assert_eq!(ptr.offset.bytes() as usize as u64, ptr.offset.bytes());
307 let offset = ptr.offset.bytes() as usize;
308 Ok(match self.bytes[offset..].iter().position(|&c| c == 0) {
309 Some(size) => {
310 let size_with_null = Size::from_bytes((size + 1) as u64);
311 // Go through `get_bytes` for checks and AllocationExtra hooks.
312 // We read the null, so we include it in the request, but we want it removed
313 // from the result, so we do subslicing.
314 &self.get_bytes(cx, ptr, size_with_null)?[..size]
315 }
316 // This includes the case where `offset` is out-of-bounds to begin with.
317 None => throw_unsup!(UnterminatedCString(ptr.erase_tag())),
318 })
319 }
320
321 /// Validates that `ptr.offset` and `ptr.offset + size` do not point to the middle of a
322 /// relocation. If `allow_ptr_and_undef` is `false`, also enforces that the memory in the
323 /// given range contains neither relocations nor undef bytes.
324 pub fn check_bytes(
325 &self,
326 cx: &impl HasDataLayout,
327 ptr: Pointer<Tag>,
328 size: Size,
329 allow_ptr_and_undef: bool,
330 ) -> InterpResult<'tcx> {
331 // Check bounds and relocations on the edges.
332 self.get_bytes_with_undef_and_ptr(cx, ptr, size)?;
333 // Check undef and ptr.
334 if !allow_ptr_and_undef {
335 self.check_defined(ptr, size)?;
336 self.check_relocations(cx, ptr, size)?;
337 }
338 Ok(())
339 }
340
341 /// Writes `src` to the memory starting at `ptr.offset`.
342 ///
343 /// It is the caller's responsibility to check bounds and alignment beforehand.
344 /// Most likely, you want to call `Memory::write_bytes` instead of this method.
345 pub fn write_bytes(
346 &mut self,
347 cx: &impl HasDataLayout,
348 ptr: Pointer<Tag>,
349 src: impl IntoIterator<Item = u8>,
350 ) -> InterpResult<'tcx> {
351 let mut src = src.into_iter();
352 let (lower, upper) = src.size_hint();
353 let len = upper.expect("can only write bounded iterators");
354 assert_eq!(lower, len, "can only write iterators with a precise length");
355 let bytes = self.get_bytes_mut(cx, ptr, Size::from_bytes(len as u64))?;
356 // `zip` would stop when the first iterator ends; we want to definitely
357 // cover all of `bytes`.
358 for dest in bytes {
359 *dest = src.next().expect("iterator was shorter than it said it would be");
360 }
361 src.next().expect_none("iterator was longer than it said it would be");
362 Ok(())
363 }
364
365 /// Reads a *non-ZST* scalar.
366 ///
367 /// ZSTs can't be read for two reasons:
368 /// * byte-order cannot work with zero-element buffers;
369 /// * in order to obtain a `Pointer`, we need to check for ZSTness anyway due to integer
370 /// pointers being valid for ZSTs.
371 ///
372 /// It is the caller's responsibility to check bounds and alignment beforehand.
373 /// Most likely, you want to call `InterpCx::read_scalar` instead of this method.
374 pub fn read_scalar(
375 &self,
376 cx: &impl HasDataLayout,
377 ptr: Pointer<Tag>,
378 size: Size,
379 ) -> InterpResult<'tcx, ScalarMaybeUndef<Tag>> {
380 // `get_bytes_unchecked` tests relocation edges.
381 let bytes = self.get_bytes_with_undef_and_ptr(cx, ptr, size)?;
382 // Undef check happens *after* we established that the alignment is correct.
383 // We must not return `Ok()` for unaligned pointers!
384 if self.check_defined(ptr, size).is_err() {
385 // This inflates undefined bytes to the entire scalar, even if only a few
386 // bytes are undefined.
387 return Ok(ScalarMaybeUndef::Undef);
388 }
389 // Now we do the actual reading.
390 let bits = read_target_uint(cx.data_layout().endian, bytes).unwrap();
391 // See if we got a pointer.
392 if size != cx.data_layout().pointer_size {
393 // *Now*, we better make sure that the inside is free of relocations too.
394 self.check_relocations(cx, ptr, size)?;
395 } else {
396 match self.relocations.get(&ptr.offset) {
397 Some(&(tag, alloc_id)) => {
398 let ptr = Pointer::new_with_tag(alloc_id, Size::from_bytes(bits as u64), tag);
399 return Ok(ScalarMaybeUndef::Scalar(ptr.into()));
400 }
401 None => {}
402 }
403 }
404 // We don't. Just return the bits.
405 Ok(ScalarMaybeUndef::Scalar(Scalar::from_uint(bits, size)))
406 }
407
408 /// Reads a pointer-sized scalar.
409 ///
410 /// It is the caller's responsibility to check bounds and alignment beforehand.
411 /// Most likely, you want to call `InterpCx::read_scalar` instead of this method.
412 pub fn read_ptr_sized(
413 &self,
414 cx: &impl HasDataLayout,
415 ptr: Pointer<Tag>,
416 ) -> InterpResult<'tcx, ScalarMaybeUndef<Tag>> {
417 self.read_scalar(cx, ptr, cx.data_layout().pointer_size)
418 }
419
420 /// Writes a *non-ZST* scalar.
421 ///
422 /// ZSTs can't be read for two reasons:
423 /// * byte-order cannot work with zero-element buffers;
424 /// * in order to obtain a `Pointer`, we need to check for ZSTness anyway due to integer
425 /// pointers being valid for ZSTs.
426 ///
427 /// It is the caller's responsibility to check bounds and alignment beforehand.
428 /// Most likely, you want to call `InterpCx::write_scalar` instead of this method.
429 pub fn write_scalar(
430 &mut self,
431 cx: &impl HasDataLayout,
432 ptr: Pointer<Tag>,
433 val: ScalarMaybeUndef<Tag>,
434 type_size: Size,
435 ) -> InterpResult<'tcx> {
436 let val = match val {
437 ScalarMaybeUndef::Scalar(scalar) => scalar,
438 ScalarMaybeUndef::Undef => {
439 self.mark_definedness(ptr, type_size, false);
440 return Ok(());
441 }
442 };
443
444 let bytes = match val.to_bits_or_ptr(type_size, cx) {
445 Err(val) => val.offset.bytes() as u128,
446 Ok(data) => data,
447 };
448
449 let endian = cx.data_layout().endian;
450 let dst = self.get_bytes_mut(cx, ptr, type_size)?;
451 write_target_uint(endian, dst, bytes).unwrap();
452
453 // See if we have to also write a relocation.
454 match val {
455 Scalar::Ptr(val) => {
456 self.relocations.insert(ptr.offset, (val.tag, val.alloc_id));
457 }
458 _ => {}
459 }
460
461 Ok(())
462 }
463
464 /// Writes a pointer-sized scalar.
465 ///
466 /// It is the caller's responsibility to check bounds and alignment beforehand.
467 /// Most likely, you want to call `InterpCx::write_scalar` instead of this method.
468 pub fn write_ptr_sized(
469 &mut self,
470 cx: &impl HasDataLayout,
471 ptr: Pointer<Tag>,
472 val: ScalarMaybeUndef<Tag>,
473 ) -> InterpResult<'tcx> {
474 let ptr_size = cx.data_layout().pointer_size;
475 self.write_scalar(cx, ptr, val, ptr_size)
476 }
477 }
478
479 /// Relocations.
480 impl<'tcx, Tag: Copy, Extra> Allocation<Tag, Extra> {
481 /// Returns all relocations overlapping with the given pointer-offset pair.
482 pub fn get_relocations(
483 &self,
484 cx: &impl HasDataLayout,
485 ptr: Pointer<Tag>,
486 size: Size,
487 ) -> &[(Size, (Tag, AllocId))] {
488 // We have to go back `pointer_size - 1` bytes, as that one would still overlap with
489 // the beginning of this range.
490 let start = ptr.offset.bytes().saturating_sub(cx.data_layout().pointer_size.bytes() - 1);
491 let end = ptr.offset + size; // This does overflow checking.
492 self.relocations.range(Size::from_bytes(start)..end)
493 }
494
495 /// Checks that there are no relocations overlapping with the given range.
496 #[inline(always)]
497 fn check_relocations(
498 &self,
499 cx: &impl HasDataLayout,
500 ptr: Pointer<Tag>,
501 size: Size,
502 ) -> InterpResult<'tcx> {
503 if self.get_relocations(cx, ptr, size).is_empty() {
504 Ok(())
505 } else {
506 throw_unsup!(ReadPointerAsBytes)
507 }
508 }
509
510 /// Removes all relocations inside the given range.
511 /// If there are relocations overlapping with the edges, they
512 /// are removed as well *and* the bytes they cover are marked as
513 /// uninitialized. This is a somewhat odd "spooky action at a distance",
514 /// but it allows strictly more code to run than if we would just error
515 /// immediately in that case.
516 fn clear_relocations(
517 &mut self,
518 cx: &impl HasDataLayout,
519 ptr: Pointer<Tag>,
520 size: Size,
521 ) -> InterpResult<'tcx> {
522 // Find the start and end of the given range and its outermost relocations.
523 let (first, last) = {
524 // Find all relocations overlapping the given range.
525 let relocations = self.get_relocations(cx, ptr, size);
526 if relocations.is_empty() {
527 return Ok(());
528 }
529
530 (
531 relocations.first().unwrap().0,
532 relocations.last().unwrap().0 + cx.data_layout().pointer_size,
533 )
534 };
535 let start = ptr.offset;
536 let end = start + size;
537
538 // Mark parts of the outermost relocations as undefined if they partially fall outside the
539 // given range.
540 if first < start {
541 self.undef_mask.set_range(first, start, false);
542 }
543 if last > end {
544 self.undef_mask.set_range(end, last, false);
545 }
546
547 // Forget all the relocations.
548 self.relocations.remove_range(first..last);
549
550 Ok(())
551 }
552
553 /// Errors if there are relocations overlapping with the edges of the
554 /// given memory range.
555 #[inline]
556 fn check_relocation_edges(
557 &self,
558 cx: &impl HasDataLayout,
559 ptr: Pointer<Tag>,
560 size: Size,
561 ) -> InterpResult<'tcx> {
562 self.check_relocations(cx, ptr, Size::ZERO)?;
563 self.check_relocations(cx, ptr.offset(size, cx)?, Size::ZERO)?;
564 Ok(())
565 }
566 }
567
568 /// Undefined bytes.
569 impl<'tcx, Tag, Extra> Allocation<Tag, Extra> {
570 /// Checks that a range of bytes is defined. If not, returns the `ReadUndefBytes`
571 /// error which will report the first byte which is undefined.
572 #[inline]
573 fn check_defined(&self, ptr: Pointer<Tag>, size: Size) -> InterpResult<'tcx> {
574 self.undef_mask
575 .is_range_defined(ptr.offset, ptr.offset + size)
576 .or_else(|idx| throw_unsup!(ReadUndefBytes(idx)))
577 }
578
579 pub fn mark_definedness(&mut self, ptr: Pointer<Tag>, size: Size, new_state: bool) {
580 if size.bytes() == 0 {
581 return;
582 }
583 self.undef_mask.set_range(ptr.offset, ptr.offset + size, new_state);
584 }
585 }
586
587 /// Run-length encoding of the undef mask.
588 /// Used to copy parts of a mask multiple times to another allocation.
589 pub struct AllocationDefinedness {
590 /// The definedness of the first range.
591 initial: bool,
592 /// The lengths of ranges that are run-length encoded.
593 /// The definedness of the ranges alternate starting with `initial`.
594 ranges: smallvec::SmallVec<[u64; 1]>,
595 }
596
597 impl AllocationDefinedness {
598 pub fn all_bytes_undef(&self) -> bool {
599 // The `ranges` are run-length encoded and of alternating definedness.
600 // So if `ranges.len() > 1` then the second block is a range of defined.
601 !self.initial && self.ranges.len() == 1
602 }
603 }
604
605 /// Transferring the definedness mask to other allocations.
606 impl<Tag, Extra> Allocation<Tag, Extra> {
607 /// Creates a run-length encoding of the undef mask.
608 pub fn compress_undef_range(&self, src: Pointer<Tag>, size: Size) -> AllocationDefinedness {
609 // Since we are copying `size` bytes from `src` to `dest + i * size` (`for i in 0..repeat`),
610 // a naive undef mask copying algorithm would repeatedly have to read the undef mask from
611 // the source and write it to the destination. Even if we optimized the memory accesses,
612 // we'd be doing all of this `repeat` times.
613 // Therefore we precompute a compressed version of the undef mask of the source value and
614 // then write it back `repeat` times without computing any more information from the source.
615
616 // A precomputed cache for ranges of defined/undefined bits
617 // 0000010010001110 will become
618 // `[5, 1, 2, 1, 3, 3, 1]`,
619 // where each element toggles the state.
620
621 let mut ranges = smallvec::SmallVec::<[u64; 1]>::new();
622 let initial = self.undef_mask.get(src.offset);
623 let mut cur_len = 1;
624 let mut cur = initial;
625
626 for i in 1..size.bytes() {
627 // FIXME: optimize to bitshift the current undef block's bits and read the top bit.
628 if self.undef_mask.get(src.offset + Size::from_bytes(i)) == cur {
629 cur_len += 1;
630 } else {
631 ranges.push(cur_len);
632 cur_len = 1;
633 cur = !cur;
634 }
635 }
636
637 ranges.push(cur_len);
638
639 AllocationDefinedness { ranges, initial }
640 }
641
642 /// Applies multiple instances of the run-length encoding to the undef mask.
643 pub fn mark_compressed_undef_range(
644 &mut self,
645 defined: &AllocationDefinedness,
646 dest: Pointer<Tag>,
647 size: Size,
648 repeat: u64,
649 ) {
650 // An optimization where we can just overwrite an entire range of definedness bits if
651 // they are going to be uniformly `1` or `0`.
652 if defined.ranges.len() <= 1 {
653 self.undef_mask.set_range_inbounds(
654 dest.offset,
655 dest.offset + size * repeat,
656 defined.initial,
657 );
658 return;
659 }
660
661 for mut j in 0..repeat {
662 j *= size.bytes();
663 j += dest.offset.bytes();
664 let mut cur = defined.initial;
665 for range in &defined.ranges {
666 let old_j = j;
667 j += range;
668 self.undef_mask.set_range_inbounds(
669 Size::from_bytes(old_j),
670 Size::from_bytes(j),
671 cur,
672 );
673 cur = !cur;
674 }
675 }
676 }
677 }
678
679 /// Relocations.
680 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
681 pub struct Relocations<Tag = (), Id = AllocId>(SortedMap<Size, (Tag, Id)>);
682
683 impl<Tag, Id> Relocations<Tag, Id> {
684 pub fn new() -> Self {
685 Relocations(SortedMap::new())
686 }
687
688 // The caller must guarantee that the given relocations are already sorted
689 // by address and contain no duplicates.
690 pub fn from_presorted(r: Vec<(Size, (Tag, Id))>) -> Self {
691 Relocations(SortedMap::from_presorted_elements(r))
692 }
693 }
694
695 impl<Tag> Deref for Relocations<Tag> {
696 type Target = SortedMap<Size, (Tag, AllocId)>;
697
698 fn deref(&self) -> &Self::Target {
699 &self.0
700 }
701 }
702
703 impl<Tag> DerefMut for Relocations<Tag> {
704 fn deref_mut(&mut self) -> &mut Self::Target {
705 &mut self.0
706 }
707 }
708
709 /// A partial, owned list of relocations to transfer into another allocation.
710 pub struct AllocationRelocations<Tag> {
711 relative_relocations: Vec<(Size, (Tag, AllocId))>,
712 }
713
714 impl<Tag: Copy, Extra> Allocation<Tag, Extra> {
715 pub fn prepare_relocation_copy(
716 &self,
717 cx: &impl HasDataLayout,
718 src: Pointer<Tag>,
719 size: Size,
720 dest: Pointer<Tag>,
721 length: u64,
722 ) -> AllocationRelocations<Tag> {
723 let relocations = self.get_relocations(cx, src, size);
724 if relocations.is_empty() {
725 return AllocationRelocations { relative_relocations: Vec::new() };
726 }
727
728 let mut new_relocations = Vec::with_capacity(relocations.len() * (length as usize));
729
730 for i in 0..length {
731 new_relocations.extend(relocations.iter().map(|&(offset, reloc)| {
732 // compute offset for current repetition
733 let dest_offset = dest.offset + (i * size);
734 (
735 // shift offsets from source allocation to destination allocation
736 offset + dest_offset - src.offset,
737 reloc,
738 )
739 }));
740 }
741
742 AllocationRelocations { relative_relocations: new_relocations }
743 }
744
745 /// Applies a relocation copy.
746 /// The affected range, as defined in the parameters to `prepare_relocation_copy` is expected
747 /// to be clear of relocations.
748 pub fn mark_relocation_range(&mut self, relocations: AllocationRelocations<Tag>) {
749 self.relocations.insert_presorted(relocations.relative_relocations);
750 }
751 }
752
753 ////////////////////////////////////////////////////////////////////////////////
754 // Undefined byte tracking
755 ////////////////////////////////////////////////////////////////////////////////
756
757 type Block = u64;
758
759 /// A bitmask where each bit refers to the byte with the same index. If the bit is `true`, the byte
760 /// is defined. If it is `false` the byte is undefined.
761 #[derive(
762 Clone,
763 Debug,
764 Eq,
765 PartialEq,
766 PartialOrd,
767 Ord,
768 Hash,
769 RustcEncodable,
770 RustcDecodable,
771 HashStable
772 )]
773 pub struct UndefMask {
774 blocks: Vec<Block>,
775 len: Size,
776 }
777
778 impl UndefMask {
779 pub const BLOCK_SIZE: u64 = 64;
780
781 pub fn new(size: Size, state: bool) -> Self {
782 let mut m = UndefMask { blocks: vec![], len: Size::ZERO };
783 m.grow(size, state);
784 m
785 }
786
787 /// Checks whether the range `start..end` (end-exclusive) is entirely defined.
788 ///
789 /// Returns `Ok(())` if it's defined. Otherwise returns the index of the byte
790 /// at which the first undefined access begins.
791 #[inline]
792 pub fn is_range_defined(&self, start: Size, end: Size) -> Result<(), Size> {
793 if end > self.len {
794 return Err(self.len);
795 }
796
797 // FIXME(oli-obk): optimize this for allocations larger than a block.
798 let idx = (start.bytes()..end.bytes()).map(|i| Size::from_bytes(i)).find(|&i| !self.get(i));
799
800 match idx {
801 Some(idx) => Err(idx),
802 None => Ok(()),
803 }
804 }
805
806 pub fn set_range(&mut self, start: Size, end: Size, new_state: bool) {
807 let len = self.len;
808 if end > len {
809 self.grow(end - len, new_state);
810 }
811 self.set_range_inbounds(start, end, new_state);
812 }
813
814 pub fn set_range_inbounds(&mut self, start: Size, end: Size, new_state: bool) {
815 let (blocka, bita) = bit_index(start);
816 let (blockb, bitb) = bit_index(end);
817 if blocka == blockb {
818 // First set all bits except the first `bita`,
819 // then unset the last `64 - bitb` bits.
820 let range = if bitb == 0 {
821 u64::MAX << bita
822 } else {
823 (u64::MAX << bita) & (u64::MAX >> (64 - bitb))
824 };
825 if new_state {
826 self.blocks[blocka] |= range;
827 } else {
828 self.blocks[blocka] &= !range;
829 }
830 return;
831 }
832 // across block boundaries
833 if new_state {
834 // Set `bita..64` to `1`.
835 self.blocks[blocka] |= u64::MAX << bita;
836 // Set `0..bitb` to `1`.
837 if bitb != 0 {
838 self.blocks[blockb] |= u64::MAX >> (64 - bitb);
839 }
840 // Fill in all the other blocks (much faster than one bit at a time).
841 for block in (blocka + 1)..blockb {
842 self.blocks[block] = u64::MAX;
843 }
844 } else {
845 // Set `bita..64` to `0`.
846 self.blocks[blocka] &= !(u64::MAX << bita);
847 // Set `0..bitb` to `0`.
848 if bitb != 0 {
849 self.blocks[blockb] &= !(u64::MAX >> (64 - bitb));
850 }
851 // Fill in all the other blocks (much faster than one bit at a time).
852 for block in (blocka + 1)..blockb {
853 self.blocks[block] = 0;
854 }
855 }
856 }
857
858 #[inline]
859 pub fn get(&self, i: Size) -> bool {
860 let (block, bit) = bit_index(i);
861 (self.blocks[block] & (1 << bit)) != 0
862 }
863
864 #[inline]
865 pub fn set(&mut self, i: Size, new_state: bool) {
866 let (block, bit) = bit_index(i);
867 self.set_bit(block, bit, new_state);
868 }
869
870 #[inline]
871 fn set_bit(&mut self, block: usize, bit: usize, new_state: bool) {
872 if new_state {
873 self.blocks[block] |= 1 << bit;
874 } else {
875 self.blocks[block] &= !(1 << bit);
876 }
877 }
878
879 pub fn grow(&mut self, amount: Size, new_state: bool) {
880 if amount.bytes() == 0 {
881 return;
882 }
883 let unused_trailing_bits = self.blocks.len() as u64 * Self::BLOCK_SIZE - self.len.bytes();
884 if amount.bytes() > unused_trailing_bits {
885 let additional_blocks = amount.bytes() / Self::BLOCK_SIZE + 1;
886 assert_eq!(additional_blocks as usize as u64, additional_blocks);
887 self.blocks.extend(
888 // FIXME(oli-obk): optimize this by repeating `new_state as Block`.
889 iter::repeat(0).take(additional_blocks as usize),
890 );
891 }
892 let start = self.len;
893 self.len += amount;
894 self.set_range_inbounds(start, start + amount, new_state);
895 }
896 }
897
898 #[inline]
899 fn bit_index(bits: Size) -> (usize, usize) {
900 let bits = bits.bytes();
901 let a = bits / UndefMask::BLOCK_SIZE;
902 let b = bits % UndefMask::BLOCK_SIZE;
903 assert_eq!(a as usize as u64, a);
904 assert_eq!(b as usize as u64, b);
905 (a as usize, b as usize)
906 }