]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/interpret/allocation.rs
004804f7c211e043aec3588876d390bed6b6fec0
[rust.git] / src / librustc / mir / interpret / allocation.rs
1 //! The virtual memory representation of the MIR interpreter.
2
3 use super::{
4     Pointer, EvalResult, AllocId, ScalarMaybeUndef, write_target_uint, read_target_uint, Scalar,
5     truncate,
6 };
7
8 use crate::ty::layout::{Size, Align};
9 use syntax::ast::Mutability;
10 use std::iter;
11 use crate::mir;
12 use std::ops::{Deref, DerefMut};
13 use rustc_data_structures::sorted_map::SortedMap;
14 use rustc_target::abi::HasDataLayout;
15
16 /// Used by `check_bounds` to indicate whether the pointer needs to be just inbounds
17 /// or also inbounds of a *live* allocation.
18 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
19 pub enum InboundsCheck {
20     Live,
21     MaybeDead,
22 }
23
24 #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
25 pub struct Allocation<Tag=(),Extra=()> {
26     /// The actual bytes of the allocation.
27     /// Note that the bytes of a pointer represent the offset of the pointer
28     pub bytes: Vec<u8>,
29     /// Maps from byte addresses to extra data for each pointer.
30     /// Only the first byte of a pointer is inserted into the map; i.e.,
31     /// every entry in this map applies to `pointer_size` consecutive bytes starting
32     /// at the given offset.
33     pub relocations: Relocations<Tag>,
34     /// Denotes undefined memory. Reading from undefined memory is forbidden in miri
35     pub undef_mask: UndefMask,
36     /// The alignment of the allocation to detect unaligned reads.
37     pub align: Align,
38     /// Whether the allocation is mutable.
39     /// Also used by codegen to determine if a static should be put into mutable memory,
40     /// which happens for `static mut` and `static` with interior mutability.
41     pub mutability: Mutability,
42     /// Extra state for the machine.
43     pub extra: Extra,
44 }
45
46
47 pub trait AllocationExtra<Tag, MemoryExtra>: ::std::fmt::Debug + Clone {
48     /// Hook to initialize the extra data when an allocation gets created.
49     fn memory_allocated(
50         _size: Size,
51         _memory_extra: &MemoryExtra
52     ) -> Self;
53
54     /// Hook for performing extra checks on a memory read access.
55     ///
56     /// Takes read-only access to the allocation so we can keep all the memory read
57     /// operations take `&self`. Use a `RefCell` in `AllocExtra` if you
58     /// need to mutate.
59     #[inline(always)]
60     fn memory_read(
61         _alloc: &Allocation<Tag, Self>,
62         _ptr: Pointer<Tag>,
63         _size: Size,
64     ) -> EvalResult<'tcx> {
65         Ok(())
66     }
67
68     /// Hook for performing extra checks on a memory write access.
69     #[inline(always)]
70     fn memory_written(
71         _alloc: &mut Allocation<Tag, Self>,
72         _ptr: Pointer<Tag>,
73         _size: Size,
74     ) -> EvalResult<'tcx> {
75         Ok(())
76     }
77
78     /// Hook for performing extra checks on a memory deallocation.
79     /// `size` will be the size of the allocation.
80     #[inline(always)]
81     fn memory_deallocated(
82         _alloc: &mut Allocation<Tag, Self>,
83         _ptr: Pointer<Tag>,
84         _size: Size,
85     ) -> EvalResult<'tcx> {
86         Ok(())
87     }
88 }
89
90 impl AllocationExtra<(), ()> for () {
91     #[inline(always)]
92     fn memory_allocated(
93         _size: Size,
94         _memory_extra: &()
95     ) -> Self {
96         ()
97     }
98 }
99
100 impl<Tag, Extra> Allocation<Tag, Extra> {
101     /// Creates a read-only allocation initialized by the given bytes
102     pub fn from_bytes(slice: &[u8], align: Align, extra: Extra) -> Self {
103         let undef_mask = UndefMask::new(Size::from_bytes(slice.len() as u64), true);
104         Self {
105             bytes: slice.to_owned(),
106             relocations: Relocations::new(),
107             undef_mask,
108             align,
109             mutability: Mutability::Immutable,
110             extra,
111         }
112     }
113
114     pub fn from_byte_aligned_bytes(slice: &[u8], extra: Extra) -> Self {
115         Allocation::from_bytes(slice, Align::from_bytes(1).unwrap(), extra)
116     }
117
118     pub fn undef(size: Size, align: Align, extra: Extra) -> 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             align,
125             mutability: Mutability::Mutable,
126             extra,
127         }
128     }
129 }
130
131 impl<'tcx> ::serialize::UseSpecializedDecodable for &'tcx Allocation {}
132
133 /// Alignment and bounds checks
134 impl<'tcx, Tag, Extra> Allocation<Tag, Extra> {
135     /// Checks if the pointer is "in-bounds". Notice that a pointer pointing at the end
136     /// of an allocation (i.e., at the first *inaccessible* location) *is* considered
137     /// in-bounds!  This follows C's/LLVM's rules.
138     /// If you want to check bounds before doing a memory access, better use `check_bounds`.
139     fn check_bounds_ptr(
140         &self,
141         ptr: Pointer<Tag>,
142     ) -> EvalResult<'tcx> {
143         let allocation_size = self.bytes.len() as u64;
144         ptr.check_in_alloc(Size::from_bytes(allocation_size), InboundsCheck::Live)
145     }
146
147     /// Checks if the memory range beginning at `ptr` and of size `Size` is "in-bounds".
148     #[inline(always)]
149     pub fn check_bounds(
150         &self,
151         cx: &impl HasDataLayout,
152         ptr: Pointer<Tag>,
153         size: Size,
154     ) -> EvalResult<'tcx> {
155         // if ptr.offset is in bounds, then so is ptr (because offset checks for overflow)
156         self.check_bounds_ptr(ptr.offset(size, cx)?)
157     }
158 }
159
160 /// Byte accessors
161 impl<'tcx, Tag: Copy, Extra> Allocation<Tag, Extra> {
162     /// The last argument controls whether we error out when there are undefined
163     /// or pointer bytes. You should never call this, call `get_bytes` or
164     /// `get_bytes_with_undef_and_ptr` instead,
165     ///
166     /// This function also guarantees that the resulting pointer will remain stable
167     /// even when new allocations are pushed to the `HashMap`. `copy_repeatedly` relies
168     /// on that.
169     fn get_bytes_internal<MemoryExtra>(
170         &self,
171         cx: &impl HasDataLayout,
172         ptr: Pointer<Tag>,
173         size: Size,
174         check_defined_and_ptr: bool,
175     ) -> EvalResult<'tcx, &[u8]>
176         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
177         where Extra: AllocationExtra<Tag, MemoryExtra>
178     {
179         self.check_bounds(cx, ptr, size)?;
180
181         if check_defined_and_ptr {
182             self.check_defined(ptr, size)?;
183             self.check_relocations(cx, ptr, size)?;
184         } else {
185             // We still don't want relocations on the *edges*
186             self.check_relocation_edges(cx, ptr, size)?;
187         }
188
189         AllocationExtra::memory_read(self, ptr, size)?;
190
191         assert_eq!(ptr.offset.bytes() as usize as u64, ptr.offset.bytes());
192         assert_eq!(size.bytes() as usize as u64, size.bytes());
193         let offset = ptr.offset.bytes() as usize;
194         Ok(&self.bytes[offset..offset + size.bytes() as usize])
195     }
196
197     #[inline]
198     pub fn get_bytes<MemoryExtra>(
199         &self,
200         cx: &impl HasDataLayout,
201         ptr: Pointer<Tag>,
202         size: Size,
203     ) -> EvalResult<'tcx, &[u8]>
204         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
205         where Extra: AllocationExtra<Tag, MemoryExtra>
206     {
207         self.get_bytes_internal(cx, ptr, size, true)
208     }
209
210     /// It is the caller's responsibility to handle undefined and pointer bytes.
211     /// However, this still checks that there are no relocations on the *edges*.
212     #[inline]
213     pub fn get_bytes_with_undef_and_ptr<MemoryExtra>(
214         &self,
215         cx: &impl HasDataLayout,
216         ptr: Pointer<Tag>,
217         size: Size,
218     ) -> EvalResult<'tcx, &[u8]>
219         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
220         where Extra: AllocationExtra<Tag, MemoryExtra>
221     {
222         self.get_bytes_internal(cx, ptr, size, false)
223     }
224
225     /// Just calling this already marks everything as defined and removes relocations,
226     /// so be sure to actually put data there!
227     pub fn get_bytes_mut<MemoryExtra>(
228         &mut self,
229         cx: &impl HasDataLayout,
230         ptr: Pointer<Tag>,
231         size: Size,
232     ) -> EvalResult<'tcx, &mut [u8]>
233         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
234         where Extra: AllocationExtra<Tag, MemoryExtra>
235     {
236         assert_ne!(size.bytes(), 0, "0-sized accesses should never even get a `Pointer`");
237         self.check_bounds(cx, ptr, size)?;
238
239         self.mark_definedness(ptr, size, true)?;
240         self.clear_relocations(cx, ptr, size)?;
241
242         AllocationExtra::memory_written(self, ptr, size)?;
243
244         assert_eq!(ptr.offset.bytes() as usize as u64, ptr.offset.bytes());
245         assert_eq!(size.bytes() as usize as u64, size.bytes());
246         let offset = ptr.offset.bytes() as usize;
247         Ok(&mut self.bytes[offset..offset + size.bytes() as usize])
248     }
249 }
250
251 /// Reading and writing
252 impl<'tcx, Tag: Copy, Extra> Allocation<Tag, Extra> {
253     /// Reads bytes until a `0` is encountered. Will error if the end of the allocation is reached
254     /// before a `0` is found.
255     pub fn read_c_str<MemoryExtra>(
256         &self,
257         cx: &impl HasDataLayout,
258         ptr: Pointer<Tag>,
259     ) -> EvalResult<'tcx, &[u8]>
260         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
261         where Extra: AllocationExtra<Tag, MemoryExtra>
262     {
263         assert_eq!(ptr.offset.bytes() as usize as u64, ptr.offset.bytes());
264         let offset = ptr.offset.bytes() as usize;
265         match self.bytes[offset..].iter().position(|&c| c == 0) {
266             Some(size) => {
267                 let size_with_null = Size::from_bytes((size + 1) as u64);
268                 // Go through `get_bytes` for checks and AllocationExtra hooks.
269                 // We read the null, so we include it in the request, but we want it removed
270                 // from the result!
271                 Ok(&self.get_bytes(cx, ptr, size_with_null)?[..size])
272             }
273             None => err!(UnterminatedCString(ptr.erase_tag())),
274         }
275     }
276
277     /// Validates that `ptr.offset` and `ptr.offset + size` do not point to the middle of a
278     /// relocation. If `allow_ptr_and_undef` is `false`, also enforces that the memory in the
279     /// given range contains neither relocations nor undef bytes.
280     pub fn check_bytes<MemoryExtra>(
281         &self,
282         cx: &impl HasDataLayout,
283         ptr: Pointer<Tag>,
284         size: Size,
285         allow_ptr_and_undef: bool,
286     ) -> EvalResult<'tcx>
287         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
288         where Extra: AllocationExtra<Tag, MemoryExtra>
289     {
290         // Check bounds and relocations on the edges
291         self.get_bytes_with_undef_and_ptr(cx, ptr, size)?;
292         // Check undef and ptr
293         if !allow_ptr_and_undef {
294             self.check_defined(ptr, size)?;
295             self.check_relocations(cx, ptr, size)?;
296         }
297         Ok(())
298     }
299
300     /// Writes `src` to the memory starting at `ptr.offset`.
301     ///
302     /// Will do bounds checks on the allocation.
303     pub fn write_bytes<MemoryExtra>(
304         &mut self,
305         cx: &impl HasDataLayout,
306         ptr: Pointer<Tag>,
307         src: &[u8],
308     ) -> EvalResult<'tcx>
309         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
310         where Extra: AllocationExtra<Tag, MemoryExtra>
311     {
312         let bytes = self.get_bytes_mut(cx, ptr, Size::from_bytes(src.len() as u64))?;
313         bytes.clone_from_slice(src);
314         Ok(())
315     }
316
317     /// Sets `count` bytes starting at `ptr.offset` with `val`. Basically `memset`.
318     pub fn write_repeat<MemoryExtra>(
319         &mut self,
320         cx: &impl HasDataLayout,
321         ptr: Pointer<Tag>,
322         val: u8,
323         count: Size
324     ) -> EvalResult<'tcx>
325         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
326         where Extra: AllocationExtra<Tag, MemoryExtra>
327     {
328         let bytes = self.get_bytes_mut(cx, ptr, count)?;
329         for b in bytes {
330             *b = val;
331         }
332         Ok(())
333     }
334
335     /// Read a *non-ZST* scalar
336     ///
337     /// zsts can't be read out of two reasons:
338     /// * byteorder cannot work with zero element buffers
339     /// * in oder to obtain a `Pointer` we need to check for ZSTness anyway due to integer pointers
340     ///   being valid for ZSTs
341     ///
342     /// Note: This function does not do *any* alignment checks, you need to do these before calling
343     pub fn read_scalar<MemoryExtra>(
344         &self,
345         cx: &impl HasDataLayout,
346         ptr: Pointer<Tag>,
347         size: Size
348     ) -> EvalResult<'tcx, ScalarMaybeUndef<Tag>>
349         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
350         where Extra: AllocationExtra<Tag, MemoryExtra>
351     {
352         // get_bytes_unchecked tests relocation edges
353         let bytes = self.get_bytes_with_undef_and_ptr(cx, ptr, size)?;
354         // Undef check happens *after* we established that the alignment is correct.
355         // We must not return Ok() for unaligned pointers!
356         if self.check_defined(ptr, size).is_err() {
357             // this inflates undefined bytes to the entire scalar, even if only a few
358             // bytes are undefined
359             return Ok(ScalarMaybeUndef::Undef);
360         }
361         // Now we do the actual reading
362         let bits = read_target_uint(cx.data_layout().endian, bytes).unwrap();
363         // See if we got a pointer
364         if size != cx.data_layout().pointer_size {
365             // *Now* better make sure that the inside also is free of relocations.
366             self.check_relocations(cx, ptr, size)?;
367         } else {
368             match self.relocations.get(&ptr.offset) {
369                 Some(&(tag, alloc_id)) => {
370                     let ptr = Pointer::new_with_tag(alloc_id, Size::from_bytes(bits as u64), tag);
371                     return Ok(ScalarMaybeUndef::Scalar(ptr.into()))
372                 }
373                 None => {},
374             }
375         }
376         // We don't. Just return the bits.
377         Ok(ScalarMaybeUndef::Scalar(Scalar::from_uint(bits, size)))
378     }
379
380     /// Note: This function does not do *any* alignment checks, you need to do these before calling
381     pub fn read_ptr_sized<MemoryExtra>(
382         &self,
383         cx: &impl HasDataLayout,
384         ptr: Pointer<Tag>,
385     ) -> EvalResult<'tcx, ScalarMaybeUndef<Tag>>
386         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
387         where Extra: AllocationExtra<Tag, MemoryExtra>
388     {
389         self.read_scalar(cx, ptr, cx.data_layout().pointer_size)
390     }
391
392     /// Write a *non-ZST* scalar
393     ///
394     /// zsts can't be read out of two reasons:
395     /// * byteorder cannot work with zero element buffers
396     /// * in oder to obtain a `Pointer` we need to check for ZSTness anyway due to integer pointers
397     ///   being valid for ZSTs
398     ///
399     /// Note: This function does not do *any* alignment checks, you need to do these before calling
400     pub fn write_scalar<MemoryExtra>(
401         &mut self,
402         cx: &impl HasDataLayout,
403         ptr: Pointer<Tag>,
404         val: ScalarMaybeUndef<Tag>,
405         type_size: Size,
406     ) -> EvalResult<'tcx>
407         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
408         where Extra: AllocationExtra<Tag, MemoryExtra>
409     {
410         let val = match val {
411             ScalarMaybeUndef::Scalar(scalar) => scalar,
412             ScalarMaybeUndef::Undef => return self.mark_definedness(ptr, type_size, false),
413         };
414
415         let bytes = match val {
416             Scalar::Ptr(val) => {
417                 assert_eq!(type_size, cx.data_layout().pointer_size);
418                 val.offset.bytes() as u128
419             }
420
421             Scalar::Bits { bits, size } => {
422                 assert_eq!(size as u64, type_size.bytes());
423                 debug_assert_eq!(truncate(bits, Size::from_bytes(size.into())), bits,
424                     "Unexpected value of size {} when writing to memory", size);
425                 bits
426             },
427         };
428
429         let endian = cx.data_layout().endian;
430         let dst = self.get_bytes_mut(cx, ptr, type_size)?;
431         write_target_uint(endian, dst, bytes).unwrap();
432
433         // See if we have to also write a relocation
434         match val {
435             Scalar::Ptr(val) => {
436                 self.relocations.insert(
437                     ptr.offset,
438                     (val.tag, val.alloc_id),
439                 );
440             }
441             _ => {}
442         }
443
444         Ok(())
445     }
446
447     /// Note: This function does not do *any* alignment checks, you need to do these before calling
448     pub fn write_ptr_sized<MemoryExtra>(
449         &mut self,
450         cx: &impl HasDataLayout,
451         ptr: Pointer<Tag>,
452         val: ScalarMaybeUndef<Tag>
453     ) -> EvalResult<'tcx>
454         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
455         where Extra: AllocationExtra<Tag, MemoryExtra>
456     {
457         let ptr_size = cx.data_layout().pointer_size;
458         self.write_scalar(cx, ptr.into(), val, ptr_size)
459     }
460 }
461
462 /// Relocations
463 impl<'tcx, Tag: Copy, Extra> Allocation<Tag, Extra> {
464     /// Returns all relocations overlapping with the given ptr-offset pair.
465     pub fn relocations(
466         &self,
467         cx: &impl HasDataLayout,
468         ptr: Pointer<Tag>,
469         size: Size,
470     ) -> &[(Size, (Tag, AllocId))] {
471         // We have to go back `pointer_size - 1` bytes, as that one would still overlap with
472         // the beginning of this range.
473         let start = ptr.offset.bytes().saturating_sub(cx.data_layout().pointer_size.bytes() - 1);
474         let end = ptr.offset + size; // this does overflow checking
475         self.relocations.range(Size::from_bytes(start)..end)
476     }
477
478     /// Checks that there are no relocations overlapping with the given range.
479     #[inline(always)]
480     fn check_relocations(
481         &self,
482         cx: &impl HasDataLayout,
483         ptr: Pointer<Tag>,
484         size: Size,
485     ) -> EvalResult<'tcx> {
486         if self.relocations(cx, ptr, size).is_empty() {
487             Ok(())
488         } else {
489             err!(ReadPointerAsBytes)
490         }
491     }
492
493     /// Removes all relocations inside the given range.
494     /// If there are relocations overlapping with the edges, they
495     /// are removed as well *and* the bytes they cover are marked as
496     /// uninitialized. This is a somewhat odd "spooky action at a distance",
497     /// but it allows strictly more code to run than if we would just error
498     /// immediately in that case.
499     fn clear_relocations(
500         &mut self,
501         cx: &impl HasDataLayout,
502         ptr: Pointer<Tag>,
503         size: Size,
504     ) -> EvalResult<'tcx> {
505         // Find the start and end of the given range and its outermost relocations.
506         let (first, last) = {
507             // Find all relocations overlapping the given range.
508             let relocations = self.relocations(cx, ptr, size);
509             if relocations.is_empty() {
510                 return Ok(());
511             }
512
513             (relocations.first().unwrap().0,
514              relocations.last().unwrap().0 + cx.data_layout().pointer_size)
515         };
516         let start = ptr.offset;
517         let end = start + size;
518
519         // Mark parts of the outermost relocations as undefined if they partially fall outside the
520         // given range.
521         if first < start {
522             self.undef_mask.set_range(first, start, false);
523         }
524         if last > end {
525             self.undef_mask.set_range(end, last, false);
526         }
527
528         // Forget all the relocations.
529         self.relocations.remove_range(first..last);
530
531         Ok(())
532     }
533
534     /// Error if there are relocations overlapping with the edges of the
535     /// given memory range.
536     #[inline]
537     fn check_relocation_edges(
538         &self,
539         cx: &impl HasDataLayout,
540         ptr: Pointer<Tag>,
541         size: Size,
542     ) -> EvalResult<'tcx> {
543         self.check_relocations(cx, ptr, Size::ZERO)?;
544         self.check_relocations(cx, ptr.offset(size, cx)?, Size::ZERO)?;
545         Ok(())
546     }
547 }
548
549
550 /// Undefined bytes
551 impl<'tcx, Tag, Extra> Allocation<Tag, Extra> {
552     /// Checks that a range of bytes is defined. If not, returns the `ReadUndefBytes`
553     /// error which will report the first byte which is undefined.
554     #[inline]
555     fn check_defined(&self, ptr: Pointer<Tag>, size: Size) -> EvalResult<'tcx> {
556         self.undef_mask.is_range_defined(
557             ptr.offset,
558             ptr.offset + size,
559         ).or_else(|idx| err!(ReadUndefBytes(idx)))
560     }
561
562     pub fn mark_definedness(
563         &mut self,
564         ptr: Pointer<Tag>,
565         size: Size,
566         new_state: bool,
567     ) -> EvalResult<'tcx> {
568         if size.bytes() == 0 {
569             return Ok(());
570         }
571         self.undef_mask.set_range(
572             ptr.offset,
573             ptr.offset + size,
574             new_state,
575         );
576         Ok(())
577     }
578 }
579
580 /// Relocations
581 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
582 pub struct Relocations<Tag=(), Id=AllocId>(SortedMap<Size, (Tag, Id)>);
583
584 impl<Tag, Id> Relocations<Tag, Id> {
585     pub fn new() -> Self {
586         Relocations(SortedMap::new())
587     }
588
589     // The caller must guarantee that the given relocations are already sorted
590     // by address and contain no duplicates.
591     pub fn from_presorted(r: Vec<(Size, (Tag, Id))>) -> Self {
592         Relocations(SortedMap::from_presorted_elements(r))
593     }
594 }
595
596 impl<Tag> Deref for Relocations<Tag> {
597     type Target = SortedMap<Size, (Tag, AllocId)>;
598
599     fn deref(&self) -> &Self::Target {
600         &self.0
601     }
602 }
603
604 impl<Tag> DerefMut for Relocations<Tag> {
605     fn deref_mut(&mut self) -> &mut Self::Target {
606         &mut self.0
607     }
608 }
609
610 ////////////////////////////////////////////////////////////////////////////////
611 // Undefined byte tracking
612 ////////////////////////////////////////////////////////////////////////////////
613
614 type Block = u64;
615
616 #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
617 pub struct UndefMask {
618     blocks: Vec<Block>,
619     len: Size,
620 }
621
622 impl_stable_hash_for!(struct mir::interpret::UndefMask{blocks, len});
623
624 impl UndefMask {
625     pub const BLOCK_SIZE: u64 = 64;
626
627     pub fn new(size: Size, state: bool) -> Self {
628         let mut m = UndefMask {
629             blocks: vec![],
630             len: Size::ZERO,
631         };
632         m.grow(size, state);
633         m
634     }
635
636     /// Checks whether the range `start..end` (end-exclusive) is entirely defined.
637     ///
638     /// Returns `Ok(())` if it's defined. Otherwise returns the index of the byte
639     /// at which the first undefined access begins.
640     #[inline]
641     pub fn is_range_defined(&self, start: Size, end: Size) -> Result<(), Size> {
642         if end > self.len {
643             return Err(self.len);
644         }
645
646         // FIXME(oli-obk): optimize this for allocations larger than a block.
647         let idx = (start.bytes()..end.bytes())
648             .map(|i| Size::from_bytes(i))
649             .find(|&i| !self.get(i));
650
651         match idx {
652             Some(idx) => Err(idx),
653             None => Ok(())
654         }
655     }
656
657     pub fn set_range(&mut self, start: Size, end: Size, new_state: bool) {
658         let len = self.len;
659         if end > len {
660             self.grow(end - len, new_state);
661         }
662         self.set_range_inbounds(start, end, new_state);
663     }
664
665     pub fn set_range_inbounds(&mut self, start: Size, end: Size, new_state: bool) {
666         let (blocka, bita) = bit_index(start);
667         let (blockb, bitb) = bit_index(end);
668         if blocka == blockb {
669             // first set all bits but the first `bita`
670             // then unset the last `64 - bitb` bits
671             let range = if bitb == 0 {
672                 u64::max_value() << bita
673             } else {
674                 (u64::max_value() << bita) & (u64::max_value() >> (64 - bitb))
675             };
676             if new_state {
677                 self.blocks[blocka] |= range;
678             } else {
679                 self.blocks[blocka] &= !range;
680             }
681             return;
682         }
683         // across block boundaries
684         if new_state {
685             // set bita..64 to 1
686             self.blocks[blocka] |= u64::max_value() << bita;
687             // set 0..bitb to 1
688             if bitb != 0 {
689                 self.blocks[blockb] |= u64::max_value() >> (64 - bitb);
690             }
691             // fill in all the other blocks (much faster than one bit at a time)
692             for block in (blocka + 1) .. blockb {
693                 self.blocks[block] = u64::max_value();
694             }
695         } else {
696             // set bita..64 to 0
697             self.blocks[blocka] &= !(u64::max_value() << bita);
698             // set 0..bitb to 0
699             if bitb != 0 {
700                 self.blocks[blockb] &= !(u64::max_value() >> (64 - bitb));
701             }
702             // fill in all the other blocks (much faster than one bit at a time)
703             for block in (blocka + 1) .. blockb {
704                 self.blocks[block] = 0;
705             }
706         }
707     }
708
709     #[inline]
710     pub fn get(&self, i: Size) -> bool {
711         let (block, bit) = bit_index(i);
712         (self.blocks[block] & (1 << bit)) != 0
713     }
714
715     #[inline]
716     pub fn set(&mut self, i: Size, new_state: bool) {
717         let (block, bit) = bit_index(i);
718         self.set_bit(block, bit, new_state);
719     }
720
721     #[inline]
722     fn set_bit(&mut self, block: usize, bit: usize, new_state: bool) {
723         if new_state {
724             self.blocks[block] |= 1 << bit;
725         } else {
726             self.blocks[block] &= !(1 << bit);
727         }
728     }
729
730     pub fn grow(&mut self, amount: Size, new_state: bool) {
731         if amount.bytes() == 0 {
732             return;
733         }
734         let unused_trailing_bits = self.blocks.len() as u64 * Self::BLOCK_SIZE - self.len.bytes();
735         if amount.bytes() > unused_trailing_bits {
736             let additional_blocks = amount.bytes() / Self::BLOCK_SIZE + 1;
737             assert_eq!(additional_blocks as usize as u64, additional_blocks);
738             self.blocks.extend(
739                 // FIXME(oli-obk): optimize this by repeating `new_state as Block`
740                 iter::repeat(0).take(additional_blocks as usize),
741             );
742         }
743         let start = self.len;
744         self.len += amount;
745         self.set_range_inbounds(start, start + amount, new_state);
746     }
747 }
748
749 #[inline]
750 fn bit_index(bits: Size) -> (usize, usize) {
751     let bits = bits.bytes();
752     let a = bits / UndefMask::BLOCK_SIZE;
753     let b = bits % UndefMask::BLOCK_SIZE;
754     assert_eq!(a as usize as u64, a);
755     assert_eq!(b as usize as u64, b);
756     (a as usize, b as usize)
757 }