1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
use crate::Owns;
use core::{
    alloc::{AllocErr, AllocInit, AllocRef, Layout, MemoryBlock, ReallocPlacement},
    ptr::NonNull,
};

/// Marks newly allocated and deallocated memory with a byte pattern.
///
/// When allocating unintitialized memory, the block is set to `0xCD`. Before deallocating,
/// the memory is set `0xDD`.
/// Those values are choosed according to [Magic Debug Values] to match the Visual
/// Studio Debug Heap implementation.
///
/// Once, `const_generics` allows default implementations, the values may be alterd with a parameter.
///
/// [Magic Debug Values]: https://en.wikipedia.org/wiki/Magic_number_%28programming%29#Magic_debug_values
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
pub struct MemoryMarker<A>(pub A);

unsafe impl<A: AllocRef> AllocRef for MemoryMarker<A> {
    fn alloc(&mut self, layout: Layout, init: AllocInit) -> Result<MemoryBlock, AllocErr> {
        let memory = self.0.alloc(layout, init)?;
        if init == AllocInit::Uninitialized {
            unsafe { memory.ptr.as_ptr().write_bytes(0xCD, memory.size) };
        }
        Ok(memory)
    }
    unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
        ptr.as_ptr().write_bytes(0xDD, layout.size());
        self.0.dealloc(ptr, layout)
    }
    unsafe fn grow(
        &mut self,
        ptr: NonNull<u8>,
        layout: Layout,
        new_size: usize,
        placement: ReallocPlacement,
        init: AllocInit,
    ) -> Result<MemoryBlock, AllocErr> {
        let memory = self.0.grow(ptr, layout, new_size, placement, init)?;
        if init == AllocInit::Uninitialized {
            memory
                .ptr
                .as_ptr()
                .add(layout.size())
                .write_bytes(0xCD, memory.size - layout.size());
        }
        Ok(memory)
    }
    unsafe fn shrink(
        &mut self,
        ptr: NonNull<u8>,
        layout: Layout,
        new_size: usize,
        placement: ReallocPlacement,
    ) -> Result<MemoryBlock, AllocErr> {
        ptr.as_ptr()
            .add(new_size)
            .write_bytes(0xDD, layout.size() - new_size);
        self.0.shrink(ptr, layout, new_size, placement)
    }
}

impl<A: Owns> Owns for MemoryMarker<A> {
    fn owns(&self, memory: MemoryBlock) -> bool {
        self.0.owns(memory)
    }
}

#[cfg(test)]
mod tests {
    use super::MemoryMarker;
    use crate::{
        helper::{self, AsSlice},
        Region,
    };
    use std::alloc::{AllocInit, AllocRef, Layout, ReallocPlacement, System};

    #[test]
    fn alloc() {
        let mut alloc = helper::tracker(MemoryMarker(System));
        let memory = alloc
            .alloc(Layout::new::<u64>(), AllocInit::Uninitialized)
            .expect("Could not allocate 8 bytes");
        unsafe {
            assert_eq!(memory.as_slice(), &[0xCD; 8][..]);
            alloc.dealloc(memory.ptr, Layout::new::<u64>());
        }

        let memory = alloc
            .alloc(Layout::new::<u64>(), AllocInit::Zeroed)
            .expect("Could not allocate 8 bytes");
        unsafe {
            assert_eq!(memory.as_slice(), &[0; 8][..]);
            alloc.dealloc(memory.ptr, Layout::new::<u64>());
        }
    }

    #[test]
    fn dealloc() {
        let mut data = [0; 8];
        let mut alloc = helper::tracker(MemoryMarker(Region::new(&mut data)));
        let memory = alloc
            .alloc(Layout::new::<[u8; 8]>(), AllocInit::Uninitialized)
            .expect("Could not allocate 8 bytes");
        unsafe {
            assert_eq!(memory.as_slice(), &[0xCD; 8][..]);
            alloc.dealloc(memory.ptr, Layout::new::<[u8; 8]>());
        }
        drop(alloc);
        assert_eq!(data, [0xDD; 8]);
    }

    #[test]
    fn grow() {
        let mut alloc = helper::tracker(MemoryMarker(System));
        let memory = alloc
            .alloc(Layout::new::<[u64; 4]>(), AllocInit::Zeroed)
            .expect("Could not allocate 32 bytes");
        unsafe {
            let memory = alloc
                .grow(
                    memory.ptr,
                    Layout::new::<[u64; 4]>(),
                    64,
                    ReallocPlacement::MayMove,
                    AllocInit::Uninitialized,
                )
                .expect("Could not grow to 64 bytes");
            assert_eq!(&memory.as_slice()[..32], &[0; 32][..]);
            assert_eq!(&memory.as_slice()[32..], &[0xCD; 32][..]);
            alloc.dealloc(memory.ptr, Layout::new::<[u64; 8]>());
        }
    }

    #[test]
    fn shrink() {
        let mut data = [0; 8];
        let mut alloc = MemoryMarker(Region::new(&mut data));
        let memory = alloc
            .alloc(Layout::new::<[u8; 8]>(), AllocInit::Zeroed)
            .expect("Could not allocate 8 bytes");
        unsafe {
            alloc
                .shrink(
                    memory.ptr,
                    Layout::new::<[u8; 8]>(),
                    4,
                    ReallocPlacement::InPlace,
                )
                .expect("Could not shrink to 4 bytes");
            assert_eq!(data, [0, 0, 0, 0, 0xDD, 0xDD, 0xDD, 0xDD]);
        }
    }
}