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
//! Analyzer - Unified analysis entry point.
use crate::analyzer::report::{
AnalysisReport, CycleReport, LeakReport, MemoryStatsReport, MetricsReport,
};
use crate::view::MemoryView;
use tracing::{debug, info};
use super::{DetectionAnalysis, ExportEngine, GraphAnalysis, MetricsAnalysis, TimelineAnalysis};
/// Unified analysis entry point.
///
/// Provides access to all analysis modules through a single interface.
/// Uses lazy initialization for expensive operations.
pub struct Analyzer {
view: MemoryView,
graph: Option<GraphAnalysis>,
detect: Option<DetectionAnalysis>,
metrics: Option<MetricsAnalysis>,
timeline: Option<TimelineAnalysis>,
}
impl Analyzer {
/// Create analyzer from GlobalTracker.
pub fn from_tracker(
tracker: &crate::capture::backends::global_tracking::GlobalTracker,
) -> Self {
info!("Creating Analyzer from GlobalTracker");
Self::from_view(MemoryView::from_tracker(tracker))
}
/// Create analyzer from view.
pub fn from_view(view: MemoryView) -> Self {
let alloc_count = view.len();
info!("Creating Analyzer with {} allocations", alloc_count);
Self {
view,
graph: None,
detect: None,
metrics: None,
timeline: None,
}
}
/// Get graph analysis (lazy).
pub fn graph(&mut self) -> &mut GraphAnalysis {
if self.graph.is_none() {
debug!("Initializing GraphAnalysis (lazy)");
self.graph = Some(GraphAnalysis::from_view(&self.view));
}
self.graph
.as_mut()
.expect("GraphAnalysis should be initialized after lazy initialization")
}
/// Get detection analysis (lazy).
pub fn detect(&mut self) -> &DetectionAnalysis {
if self.detect.is_none() {
debug!("Initializing DetectionAnalysis (lazy)");
self.detect = Some(DetectionAnalysis::from_view(&self.view));
}
self.detect
.as_ref()
.expect("DetectionAnalysis should be initialized after lazy initialization")
}
/// Get metrics analysis (lazy).
pub fn metrics(&mut self) -> &MetricsAnalysis {
if self.metrics.is_none() {
debug!("Initializing MetricsAnalysis (lazy)");
self.metrics = Some(MetricsAnalysis::from_view(&self.view));
}
self.metrics
.as_ref()
.expect("MetricsAnalysis should be initialized after lazy initialization")
}
/// Get timeline analysis (lazy).
pub fn timeline(&mut self) -> &TimelineAnalysis {
if self.timeline.is_none() {
debug!("Initializing TimelineAnalysis (lazy)");
self.timeline = Some(TimelineAnalysis::from_view(&self.view));
}
self.timeline
.as_ref()
.expect("TimelineAnalysis should be initialized after lazy initialization")
}
/// Get export engine.
pub fn export(&self) -> ExportEngine<'_> {
ExportEngine::new(&self.view)
}
/// Get underlying view.
pub fn view(&self) -> &MemoryView {
&self.view
}
/// Run full analysis on the memory data.
///
/// This method performs a comprehensive analysis of all tracked memory
/// allocations and returns a complete report.
///
/// # Analysis Pipeline
///
/// The analysis is performed in the following order:
///
/// 1. **Statistics Collection** (O(1))
/// - Total allocation count
/// - Total bytes allocated
/// - Peak memory usage
/// - Thread count
///
/// 2. **Leak Detection** (O(n))
/// - Identifies allocations that were never deallocated
/// - Reports leaked bytes and allocation details
///
/// 3. **Cycle Detection** (O(V + E))
/// - Uses DFS-based algorithm to detect reference cycles
/// - Groups allocations by type for potential cycle identification
///
/// 4. **Metrics Summary** (O(n))
/// - Aggregates allocation statistics by type
/// - Reports top allocations by size
///
/// # Performance Characteristics
///
/// - **Time Complexity**: O(n + V + E) where n is the number of allocations,
/// V is the number of unique pointers, and E is the number of edges
/// - **Space Complexity**: O(n) for storing analysis results
/// - **Memory Overhead**: Minimal, results are computed on-demand
///
/// # Example
///
/// ```ignore
/// let mut analyzer = analyzer(&tracker)?;
/// let report = analyzer.analyze();
///
/// println!("Allocations: {}", report.stats.allocation_count);
/// println!("Leaks: {}", report.leaks.leak_count);
/// println!("Cycles: {}", report.cycles.cycle_count);
/// ```
///
/// # Returns
///
/// An `AnalysisReport` containing:
/// - `stats`: Basic memory statistics
/// - `leaks`: Memory leak detection results
/// - `cycles`: Reference cycle detection results
/// - `metrics`: Aggregated metrics summary
pub fn analyze(&mut self) -> AnalysisReport {
info!("Starting full analysis");
let stats = MemoryStatsReport {
allocation_count: self.view.len(),
total_bytes: self.view.total_memory(),
peak_bytes: self.view.snapshot().stats.peak_memory,
thread_count: self.view.snapshot().thread_stats.len(),
};
debug!(
"Stats: {} allocations, {} bytes, {} threads",
stats.allocation_count, stats.total_bytes, stats.thread_count
);
let leaks = self.detect().leaks();
if leaks.leak_count > 0 {
info!(
"Leak detection found {} leaks ({} bytes)",
leaks.leak_count, leaks.total_leaked_bytes
);
}
let cycles = self.graph().cycles();
if cycles.cycle_count > 0 {
info!("Cycle detection found {} cycles", cycles.cycle_count);
}
let metrics = self.metrics().summary();
info!("Analysis complete");
AnalysisReport {
stats,
leaks,
cycles,
metrics,
}
}
/// Quick leak check.
pub fn quick_leak_check(&mut self) -> LeakReport {
self.detect().leaks()
}
/// Quick cycle check.
pub fn quick_cycle_check(&mut self) -> CycleReport {
self.graph().cycles()
}
/// Quick metrics.
pub fn quick_metrics(&mut self) -> MetricsReport {
self.metrics().summary()
}
}
impl Clone for Analyzer {
fn clone(&self) -> Self {
Self {
view: self.view.clone(),
graph: None,
detect: None,
metrics: None,
timeline: None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::event_store::MemoryEvent;
#[test]
fn test_analyzer_from_events() {
let events = vec![
MemoryEvent::allocate(0x1000, 64, 1),
MemoryEvent::allocate(0x2000, 128, 2),
];
let view = MemoryView::from_events(events);
let mut analyzer = Analyzer::from_view(view);
// Only test detection (no heap scanning required)
let leaks = analyzer.quick_leak_check();
assert_eq!(leaks.leak_count, 2);
// Test metrics (no heap scanning required)
let metrics = analyzer.quick_metrics();
assert_eq!(metrics.allocation_count, 2);
}
#[test]
fn test_quick_leak_check() {
let events = vec![MemoryEvent::allocate(0x1000, 64, 1)];
let view = MemoryView::from_events(events);
let mut analyzer = Analyzer::from_view(view);
let leaks = analyzer.quick_leak_check();
assert_eq!(leaks.leak_count, 1);
}
}