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
use crate::rt;
use crate::rt::{object, Location};

use tracing::trace;

/// Tracks an allocation
#[derive(Debug)]
pub(crate) struct Allocation {
    state: object::Ref<State>,
}

#[derive(Debug)]
pub(super) struct State {
    is_dropped: bool,
    allocated: Location,
}

/// Track a raw allocation
pub(crate) fn alloc(ptr: *mut u8, location: Location) {
    rt::execution(|execution| {
        let state = execution.objects.insert(State {
            is_dropped: false,
            allocated: location,
        });

        let allocation = Allocation { state };

        trace!(?allocation.state, ?ptr, %location, "alloc");

        let prev = execution.raw_allocations.insert(ptr as usize, allocation);
        assert!(prev.is_none(), "pointer already tracked");
    });
}

/// Track a raw deallocation
pub(crate) fn dealloc(ptr: *mut u8, location: Location) {
    let allocation =
        rt::execution(
            |execution| match execution.raw_allocations.remove(&(ptr as usize)) {
                Some(allocation) => {
                    trace!(state = ?allocation.state, ?ptr, %location, "dealloc");

                    allocation
                }
                None => panic!("pointer not tracked"),
            },
        );

    // Drop outside of the `rt::execution` block
    drop(allocation);
}

impl Allocation {
    pub(crate) fn new(location: Location) -> Allocation {
        rt::execution(|execution| {
            let state = execution.objects.insert(State {
                is_dropped: false,
                allocated: location,
            });

            trace!(?state, %location, "Allocation::new");

            Allocation { state }
        })
    }
}

impl Drop for Allocation {
    #[track_caller]
    fn drop(&mut self) {
        let location = location!();
        rt::execution(|execution| {
            let state = self.state.get_mut(&mut execution.objects);

            trace!(state = ?self.state, drop.location = %location, "Allocation::drop");

            state.is_dropped = true;
        });
    }
}

impl State {
    pub(super) fn check_for_leaks(&self, index: usize) {
        if !self.is_dropped {
            if self.allocated.is_captured() {
                panic!(
                    "Allocation leaked.\n  Allocated: {}\n      Index: {}",
                    self.allocated, index
                );
            } else {
                panic!("Allocation leaked.\n  Index: {}", index);
            }
        }
    }
}