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
use std::collections::hash_map::DefaultHasher;
use std::fmt;
use std::hash::{Hash, Hasher};

pub use backtrace;
use backtrace::{Backtrace, BacktraceFmt, BytesOrWideString, PrintFmt};

use crate::{BacktraceMode, Size, SizeF64};

#[derive(Clone)]
pub struct HashedBacktrace {
    inner: Option<Backtrace>,
    hash: u64,
}

pub struct TraceInfo {
    pub backtrace: HashedBacktrace,
    pub allocated: u64,
    pub freed: u64,
    pub allocations: u64,
    pub mode: BacktraceMode,
}

struct HashedBacktraceShort<'a>(&'a HashedBacktrace);

impl<'a> fmt::Display for HashedBacktraceShort<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.display_short(f)
    }
}

impl HashedBacktrace {
    pub fn capture(mode: BacktraceMode) -> Self {
        if matches!(mode, BacktraceMode::None) {
            return Self {
                inner: None,
                hash: 0,
            };
        }
        let backtrace = Backtrace::new_unresolved();
        let mut hasher = DefaultHasher::new();
        backtrace
            .frames()
            .iter()
            .for_each(|x| hasher.write_u64(x.ip() as u64));
        let hash = hasher.finish();
        Self {
            inner: Some(backtrace),
            hash,
        }
    }

    pub fn inner(&self) -> &Backtrace {
        self.inner.as_ref().unwrap()
    }

    pub fn inner_mut(&mut self) -> &mut Backtrace {
        self.inner.as_mut().unwrap()
    }

    pub fn hash(&self) -> u64 {
        self.hash
    }

    fn display_short(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let full = f.alternate();
        let frames = self.inner().frames();

        let cwd = std::env::current_dir();
        let mut print_path = move |fmt: &mut fmt::Formatter<'_>, path: BytesOrWideString<'_>| {
            let path = path.into_path_buf();
            if !full {
                if let Ok(cwd) = &cwd {
                    if let Ok(suffix) = path.strip_prefix(cwd) {
                        return fmt::Display::fmt(&suffix.display(), fmt);
                    }
                }
            }
            fmt::Display::fmt(&path.display(), fmt)
        };

        let mut f = BacktraceFmt::new(f, PrintFmt::Short, &mut print_path);
        f.add_context()?;
        for frame in frames {
            let symbols = frame.symbols();
            for symbol in symbols {
                if let Some(name) = symbol.name().map(|x| x.to_string()) {
                    let name = name.strip_prefix('<').unwrap_or(&name);
                    if name.starts_with("alloc_track::")
                        || name == "__rg_alloc"
                        || name.starts_with("alloc::")
                        || name.starts_with("std::panicking::")
                        || name == "__rust_try"
                        || name == "_start"
                        || name == "__libc_start_main_impl"
                        || name == "__libc_start_call_main"
                        || name.starts_with("std::rt::")
                    {
                        continue;
                    }
                }

                f.frame().backtrace_symbol(frame, symbol)?;
            }
            if symbols.is_empty() {
                f.frame().print_raw(frame.ip(), None, None, None)?;
            }
        }
        f.finish()?;
        Ok(())
    }
}

impl PartialEq for HashedBacktrace {
    fn eq(&self, other: &Self) -> bool {
        self.hash == other.hash
    }
}

impl Eq for HashedBacktrace {}

impl Hash for HashedBacktrace {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.hash.hash(state);
    }
}

#[derive(Debug, Clone, Default)]
pub struct BacktraceMetric {
    pub allocated: u64,
    pub freed: u64,
    pub allocations: u64,
    pub mode: BacktraceMode,
}

impl BacktraceMetric {
    pub fn in_use(&self) -> u64 {
        self.allocated.saturating_sub(self.freed)
    }

    pub fn avg_allocation(&self) -> f64 {
        if self.allocations == 0 {
            0.0
        } else {
            self.allocated as f64 / self.allocations as f64
        }
    }
}

impl fmt::Display for BacktraceMetric {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "allocated: {}", Size(self.allocated))?;
        writeln!(f, "allocations: {}", Size(self.allocations))?;
        writeln!(f, "avg_allocation: {}", SizeF64(self.avg_allocation()))?;
        writeln!(f, "freed: {}", Size(self.freed))?;
        writeln!(f, "total_used: {}", Size(self.in_use()))?;
        Ok(())
    }
}

pub struct BacktraceReport(pub Vec<(HashedBacktrace, BacktraceMetric)>);

impl fmt::Display for BacktraceReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (backtrace, metric) in &self.0 {
            match metric.mode {
                BacktraceMode::None => unreachable!(),
                BacktraceMode::Short => {
                    writeln!(f, "{}\n{metric}\n\n", HashedBacktraceShort(backtrace))?
                }
                BacktraceMode::Full => writeln!(f, "{:?}\n{metric}\n\n", backtrace.inner())?,
            }
        }
        Ok(())
    }
}