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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
//! Checkers is a simple allocation sanitizer for Rust. It plugs in through the
//! [global allocator] and can sanity check your unsafe Rust during integration
//! testing. Since it plugs in through the global allocator it doesn't require any
//! additional dependencies and works for all platforms - but it is more limited in
//! what it can verify.
//!
//! [global allocator]: https://doc.rust-lang.org/std/alloc/trait.GlobalAlloc.html
//!
//! It can check for the following things:
//! * Double-frees.
//! * Freeing regions which are not allocated.
//! * Freeing only part of regions which are allocated.
//! * Freeing a region with a [mismatching layout].
//! * The underlying allocator produces regions adhering to the requested layout.
//!   Namely size and alignment.
//! * Detailed information on memory usage.
//! * Other user-defined conditions ([see test]).
//!
//! What it can't do:
//! * Test multithreaded code. Since the allocator is global, it is difficult to
//!   scope the state for each test case.
//! * Detect out-of-bounds accesses.
//!
//! [mismatching layout]: https://doc.rust-lang.org/std/alloc/trait.GlobalAlloc.html#safety
//! [see test]: https://github.com/udoprog/checkers/blob/master/tests/leaky_tests.rs
//!
//! # Examples
//!
//! It is recommended that you use checkers for [integration tests], which by
//! default lives in the `./tests` directory. Each file in this directory will be
//! compiled as a separate program, so the use of the global allocator can be more
//! isolated.
//!
//! [integration tests]: https://doc.rust-lang.org/book/ch11-03-test-organization.html#integration-tests
//!
//! We then use checkers by installing `checkers::Allocator` as the global
//! allocator, after this we can make use of [`#[checkers::test]`](attr.test.html) attribute macro or
//! the [`checkers::with`] function in our tests.
//!
//! [`checkers::with`]: crate::with
//!
//! ```rust
//! #[global_allocator]
//! static ALLOCATOR: checkers::Allocator = checkers::Allocator;
//! 
//! #[checkers::test]
//! fn test_allocations() {
//!     let _ = Box::into_raw(Box::new(42));
//! }
//! ```
//!
//! The above would result in the following test output:
//!
//! ```text
//! dangling region: 0x226e5784f30-0x226e5784f40 (size: 16, align: 8).
//! thread 'test_leak_box' panicked at 'allocation checks failed', tests\leaky_tests.rs:4:1
//! ```
//!
//! With `checkers::with`, we can perform more detailed diagnostics:
//!
//! ```rust
//! #[global_allocator]
//! static ALLOCATOR: checkers::Allocator = checkers::Allocator;
//!
//! #[test]
//! fn test_event_inspection() {
//!     let snapshot = checkers::with(|| {
//!         let _ = vec![1, 2, 3, 4];
//!     });
//! 
//!     assert_eq!(2, snapshot.events.len());
//!     assert!(snapshot.events[0].is_allocation_with(|r| r.size >= 16));
//!     assert!(snapshot.events[1].is_deallocation_with(|a| a.size >= 16));
//!     assert_eq!(1, snapshot.events.allocations());
//!     assert_eq!(1, snapshot.events.deallocations());
//!     assert!(snapshot.events.max_memory_used().unwrap() >= 16);
//! }
//! ```

use std::{
    alloc::{GlobalAlloc, Layout, System},
    cell::{Cell, RefCell},
    fmt, thread,
};

mod events;
mod machine;

pub use self::events::Events;
pub use self::machine::{Machine, Region, Violation};
pub use checkers_macros::test;

thread_local! {
    /// Thread-local state required by the allocator.
    ///
    /// Feel free to interact with this directly, but it's primarily used
    /// through the [`test`](crate::test) macro.
    static STATE: RefCell<State> = RefCell::new(State::new());
    static MUTED: Cell<bool> = Cell::new(true);
}

/// Perform an operation, while having access to the thread-local state.
pub fn with_state<F, R>(f: F) -> R
where
    F: FnOnce(&RefCell<State>) -> R,
{
    crate::STATE.with(f)
}

/// Test if the crate is currently muted.
pub fn is_muted() -> bool {
    MUTED.with(Cell::get)
}

/// Enable muting for the duration of the guard.
pub fn mute_guard(muted: bool) -> MuteGuard {
    MuteGuard(MUTED.with(|s| s.replace(muted)))
}

/// A helper guard to make sure the state is de-allocated on drop.
pub struct MuteGuard(bool);

impl Drop for MuteGuard {
    fn drop(&mut self) {
        MUTED.with(|s| s.set(self.0));
    }
}

/// Verify the state of the allocator.
/// 
/// Note: this macro is used by default if the `verify` parameter is not
/// specified in [`#[checkers::test]`](attr.test.html).
///
/// Currently performs the following tests:
/// * Checks that each allocation has an exact corresponding deallocation,
///   and that it happened _after_ the allocation it relates to.
/// * That there are no overlapping deallocations / allocations.
/// * That the thread-local timeline matches.
///
/// # Examples
///
/// ```rust
/// #[global_allocator]
/// static ALLOCATOR: checkers::Allocator = checkers::Allocator;
///
/// fn verify_test_custom_verify(state: &mut checkers::State) {
///    assert_eq!(1, state.events.allocations());
///    checkers::verify!(state);
/// }
///
/// #[checkers::test(verify = "verify_test_custom_verify")]
/// fn test_custom_verify() {
///     let _ = Box::into_raw(vec![1, 2, 3, 4, 5].into_boxed_slice());
/// }
/// ```
#[macro_export]
macro_rules! verify {
    ($state:expr) => {
        let mut validations = Vec::new();
        $state.validate(&mut validations);

        for e in &validations {
            eprintln!("{:?}", e);
        }

        if !validations.is_empty() {
            panic!("allocation checks failed");
        }
    };
}

pub struct Snapshot {
    pub events: Events,
}

/// Run the specified closure and return a snapshot of the memory state
/// afterwards.
///
/// This can be useful to programmatically test for allocation invariants,
/// while the default behavior is to simply panic on invariant errors.
///
/// # Examples
///
/// ```rust
/// #[global_allocator]
/// static ALLOCATOR: checkers::Allocator = checkers::Allocator;
///
/// let snapshot = checkers::with(|| {
///     let _ = vec![1, 2, 3, 4];
/// });
///
/// assert_eq!(2, snapshot.events.len());
/// assert!(snapshot.events[0].is_allocation_with(|a| a.size >= 16));
/// assert!(snapshot.events[1].is_deallocation_with(|a| a.size >= 16));
/// assert_eq!(1, snapshot.events.allocations());
/// assert_eq!(1, snapshot.events.deallocations());
/// assert!(snapshot.events.max_memory_used().unwrap() >= 16);
/// ```
pub fn with<F>(f: F) -> Snapshot
where
    F: FnOnce(),
{
    crate::with_state(|s| {
        s.borrow_mut().events.clear();

        {
            let _g = crate::mute_guard(false);
            f();
        }

        let snapshot = Snapshot {
            events: s.borrow().events.clone(),
        };

        snapshot
    })
}

/// Structure containing all thread-local state required to use the
/// single-threaded allocation checker.
pub struct State {
    pub events: Events,
}

impl State {
    /// Construct new local state.
    pub const fn new() -> Self {
        Self {
            events: Events::new(),
        }
    }

    /// Reserve the specified number of events.
    pub fn reserve(&mut self, cap: usize) {
        self.events.reserve(cap);
    }

    /// Clear the current collection of events.
    pub fn clear(&mut self) {
        self.events.clear();
    }

    /// Validate the current state.
    pub fn validate(&self, errors: &mut Vec<Violation>) {
        self.events.validate(errors);
    }
}

/// A type-erased pointer.
/// The inner representation is specifically _not_ a raw pointer to avoid
/// aliasing the pointers handled by the allocator.
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Pointer(usize);

impl Pointer {
    /// Construct a new default poitner.
    pub const fn new() -> Self {
        Self(0)
    }

    /// Add the given offset to the current pointer.
    pub fn saturating_add(self, n: usize) -> Self {
        Self(self.0.saturating_add(n))
    }

    /// Test if pointer is aligned with the given argument.
    pub fn is_aligned_with(self, n: usize) -> bool {
        self.0 % n == 0
    }
}

impl fmt::Debug for Pointer {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(fmt, "{:?}", &(self.0 as *const ()))
    }
}

impl From<*mut u8> for Pointer {
    fn from(value: *mut u8) -> Self {
        Self(value as usize)
    }
}

impl From<usize> for Pointer {
    fn from(value: usize) -> Self {
        Self(value)
    }
}

/// Metadata for a single allocation or deallocation.
#[derive(Debug, Clone, Copy)]
pub enum Event {
    /// Placeholder for empty events.
    Empty,
    /// An allocation.
    Allocation(Region),
    /// A deallocation.
    Deallocation(Region),
}

impl Event {
    /// Test if this event is an allocation which matches the specified
    /// predicate.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let event = checkers::Event::Allocation(checkers::Region {
    ///     ptr: 100.into(),
    ///     size: 100,
    ///     align: 4,
    /// });
    ///
    /// assert!(event.is_allocation_with(|r| r.size == 100 && r.align == 4));
    /// assert!(!event.is_deallocation_with(|r| r.size == 100 && r.align == 4));
    /// ```
    pub fn is_allocation_with<F>(self, f: F) -> bool
    where
        F: FnOnce(Region) -> bool,
    {
        match self {
            Self::Allocation(region) => f(region),
            _ => false,
        }
    }

    /// Test if this event is a deallocation which matches the specified
    /// predicate.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let event = checkers::Event::Deallocation(checkers::Region {
    ///     ptr: 100.into(),
    ///     size: 100,
    ///     align: 4,
    /// });
    ///
    /// assert!(!event.is_allocation_with(|r| r.size == 100 && r.align == 4));
    /// assert!(event.is_deallocation_with(|r| r.size == 100 && r.align == 4));
    /// ```
    pub fn is_deallocation_with<F>(self, f: F) -> bool
    where
        F: FnOnce(Region) -> bool,
    {
        match self {
            Self::Deallocation(region) => f(region),
            _ => false,
        }
    }
}

/// 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;
/// ```
pub struct Allocator;

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

        if !thread::panicking() && !crate::is_muted() {
            crate::with_state(move |s| {
                s.borrow_mut().events.push(Event::Allocation(Region {
                    ptr: ptr.into(),
                    size: layout.size(),
                    align: layout.align(),
                }));
            });
        }

        ptr
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        if !thread::panicking() && !crate::is_muted() {
            crate::with_state(move |s| {
                s.borrow_mut().events.push(Event::Deallocation(Region {
                    ptr: ptr.into(),
                    size: layout.size(),
                    align: layout.align(),
                }));
            });
        }

        System.dealloc(ptr, layout);
    }
}