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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
use crate::{AllocZeroed, Event, Realloc, Region};
use std::alloc::{GlobalAlloc, Layout, System};

/// Allocator that needs to be installed.
///
/// Delegates allocations to [`std::alloc::System`] (this might be configurable
/// in the future).
///
/// [`std::alloc::System`]: std::alloc::System
///
/// You install it by doing:
///
/// ```rust,no_run
/// #[global_allocator]
/// static ALLOCATOR: checkers::Allocator = checkers::Allocator::system();
/// ```
pub struct Allocator<T = System> {
    delegate: T,
}

impl<T> Allocator<T> {
    /// Construct an allocator with a custom delegate global allocator.
    ///
    /// # Examples
    ///
    /// ```rust
    /// #[global_allocator]
    /// static ALLOCATOR: checkers::Allocator = checkers::Allocator::new(std::alloc::System);
    /// ```
    pub const fn new(delegate: T) -> Allocator<T> {
        Allocator { delegate }
    }
}

impl Allocator<System> {
    /// Construct an allocator with the system delegate global allocator.
    ///
    /// # Examples
    ///
    /// ```rust
    /// #[global_allocator]
    /// static ALLOCATOR: checkers::Allocator = checkers::Allocator::system();
    /// ```
    pub const fn system() -> Allocator<System> {
        Self::new(System)
    }
}

unsafe impl<T> GlobalAlloc for Allocator<T>
where
    T: GlobalAlloc,
{
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        let ptr = self.delegate.alloc(layout);

        // Note: On null return early, caller is likely to panic or handle OOM
        // scenario gracefully.
        // TODO: Consider emitting diagnostics.
        if crate::is_muted() || ptr.is_null() {
            if ptr.is_null() {
                crate::with_state(move |s| {
                    s.borrow_mut().events.push(Event::AllocFailed);
                });
            }

            return ptr;
        }

        crate::with_state(move |s| {
            s.borrow_mut().events.push(Event::Alloc(Region {
                ptr: ptr.into(),
                size: layout.size(),
                align: layout.align(),
            }));
        });

        ptr
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        self.delegate.dealloc(ptr, layout);

        if crate::is_muted() {
            return;
        }

        crate::with_state(move |s| {
            s.borrow_mut().events.push(Event::Free(Region {
                ptr: ptr.into(),
                size: layout.size(),
                align: layout.align(),
            }));
        });
    }

    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
        let ptr = self.delegate.alloc_zeroed(layout);

        // Note: On null return early, caller is likely to panic or handle OOM
        // scenario gracefully.
        if crate::is_muted() || ptr.is_null() {
            if ptr.is_null() {
                crate::with_state(move |s| {
                    s.borrow_mut().events.push(Event::AllocZeroedFailed);
                });
            }

            return ptr;
        }

        crate::with_state(move |s| {
            #[cfg(feature = "zeroed")]
            let is_zeroed = Some(crate::utils::is_zeroed_ptr(ptr, layout.size()));
            #[cfg(not(feature = "zeroed"))]
            let is_zeroed = None;

            s.borrow_mut().events.push(Event::AllocZeroed(AllocZeroed {
                is_zeroed,
                alloc: Region {
                    ptr: ptr.into(),
                    size: layout.size(),
                    align: layout.align(),
                },
            }));
        });

        ptr
    }

    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
        // Note: On null return early, caller is likely to panic or handle OOM
        // scenario gracefully.
        if crate::is_muted() || ptr.is_null() {
            if ptr.is_null() {
                crate::with_state(|s| {
                    s.borrow_mut().events.push(Event::ReallocNull);
                });
            }

            return self.delegate.realloc(ptr, layout, new_size);
        }

        // Safety Note: This needs to happen before call to `realloc`, since it
        // might deallocate it.
        #[cfg(feature = "realloc")]
        let min_size = usize::min(layout.size(), new_size);
        #[cfg(feature = "realloc")]
        let old_hash = crate::utils::hash_ptr(ptr, min_size);

        // Safety Note: Convert to pointer early to avoid relying on potentially
        // dangling pointer later.
        let old_ptr = ptr.into();
        let new_ptr = self.delegate.realloc(ptr, layout, new_size);

        // Note: return early, caller is likely to panic or handle OOM scenario.
        // gracefully. Prior memory is unaltered.
        // TODO: Consider emitting diagnostics.
        if new_ptr.is_null() {
            crate::with_state(|s| {
                s.borrow_mut().events.push(Event::ReallocFailed);
            });

            return new_ptr;
        }

        crate::with_state(move |s| {
            #[cfg(feature = "realloc")]
            let is_relocated = Some(old_hash == crate::utils::hash_ptr(new_ptr, min_size));
            #[cfg(not(feature = "realloc"))]
            let is_relocated = None;

            let free = Region {
                ptr: old_ptr,
                size: layout.size(),
                align: layout.align(),
            };

            let alloc = Region {
                ptr: new_ptr.into(),
                size: new_size,
                align: layout.align(),
            };

            s.borrow_mut().events.push(Event::Realloc(Realloc {
                is_relocated,
                free,
                alloc,
            }));
        });

        new_ptr
    }
}