memscope-rs 0.2.3

A memory tracking library for Rust applications.
Documentation
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# Analysis Module

## Overview

The analysis module provides advanced memory analysis capabilities including leak detection, safety analysis, lifecycle analysis, and pattern detection. It implements various detectors and analyzers to identify memory issues and provide insights.

## Components

### 1. Detectors

**Files**: `src/analysis/detectors/`

**Purpose**: Specialized detectors for common memory issues.

#### LeakDetector

Detects potential memory leaks:

```rust
pub struct LeakDetector {
    config: LeakDetectorConfig,
}

impl Detector for LeakDetector {
    fn detect(&self, allocations: &[AllocationInfo]) -> DetectionResult {
        // Detect allocations without corresponding deallocations
        let leaked: Vec<_> = allocations.iter()
            .filter(|a| a.timestamp_dealloc.is_none())
            .collect();

        DetectionResult {
            detector_name: "LeakDetector".to_string(),
            issues: leaked.len(),
            details: leaked.iter().map(|a| format!("0x{:x}: {} bytes", a.ptr, a.size)).collect(),
        }
    }
}
```

#### UafDetector

Detects use-after-free issues:

```rust
pub struct UafDetector {
    config: UafDetectorConfig,
}

impl Detector for UafDetector {
    fn detect(&self, allocations: &[AllocationInfo]) -> DetectionResult {
        // Detect accesses after deallocation
        // ... implementation
    }
}
```

#### OverflowDetector

Detects buffer overflow issues:

```rust
pub struct OverflowDetector {
    config: OverflowDetectorConfig,
}

impl Detector for OverflowDetector {
    fn detect(&self, allocations: &[AllocationInfo]) -> DetectionResult {
        // Detect buffer overflows
        // ... implementation
    }
}
```

#### SafetyDetector

Detects safety violations:

```rust
pub struct SafetyDetector {
    config: SafetyDetectorConfig,
}

impl Detector for SafetyDetector {
    fn detect(&self, allocations: &[AllocationInfo]) -> DetectionResult {
        // Detect safety violations
        // ... implementation
    }
}
```

#### LifecycleDetector

Detects lifecycle issues:

```rust
pub struct LifecycleDetector {
    config: LifecycleDetectorConfig,
}

impl Detector for LifecycleDetector {
    fn detect(&self, allocations: &[AllocationInfo]) -> DetectionResult {
        // Detect lifecycle issues
        // ... implementation
    }
}
```

### 2. Specialized Analyzers

#### MemoryPassportTracker

Tracks memory lifecycle with "passports":

```rust
pub struct MemoryPassport {
    pub ptr: usize,
    pub size: usize,
    pub created_at: u64,
    pub status: PassportStatus,
    pub events: Vec<PassportEvent>,
}
```

#### CircularReferenceDetector

Detects circular references in smart pointers:

```rust
pub fn detect_circular_references(allocations: &[AllocationInfo]) -> CircularReferenceAnalysis {
    // Detect cycles in reference graphs
    // ... implementation
}
```

#### VariableRelationshipAnalyzer

Analyzes variable relationships:

```rust
pub fn build_variable_relationship_graph(allocations: &[AllocationInfo]) -> VariableRelationshipGraph {
    // Build relationship graph
    // ... implementation
}
```

### 3. Pattern Analyzers

#### AsyncAnalyzer

Analyzes async patterns:

```rust
pub struct AsyncAnalyzer {
    // Analyzes Future state machines
}
```

#### BorrowAnalyzer

Analyzes borrow patterns:

```rust
pub struct BorrowAnalyzer {
    // Analyzes borrow checker patterns
}
```

#### GenericAnalyzer

Analyzes generic type usage:

```rust
pub struct GenericAnalyzer {
    // Analyzes generic instantiations
}
```

#### ClosureAnalyzer

Analyzes closure captures:

```rust
pub struct ClosureAnalyzer {
    // Analyzes closure lifetime patterns
}
```

### 4. AnalysisManager

**File**: `src/analysis/mod.rs`

**Purpose**: Consolidates all analysis functionality.

**Core Implementation**:

```rust
pub struct AnalysisManager {
    // Consolidates all analysis functionality
}

impl AnalysisManager {
    /// Analyze memory fragmentation
    pub fn analyze_fragmentation(&self, allocations: &[AllocationInfo]) -> FragmentationAnalysis {
        // ... implementation
    }

    /// Analyze system library usage
    pub fn analyze_system_libraries(&self, allocations: &[AllocationInfo]) -> SystemLibraryStats {
        // ... implementation
    }

    /// Analyze concurrency safety
    pub fn analyze_concurrency_safety(&self, allocations: &[AllocationInfo]) -> ConcurrencyAnalysis {
        // ... implementation
    }

    /// Perform comprehensive analysis
    pub fn perform_comprehensive_analysis(
        &self,
        allocations: &[AllocationInfo],
        stats: &MemoryStats,
    ) -> ComprehensiveAnalysisReport {
        // ... implementation
    }
}
```

## Usage Examples

### Using Detectors

```rust
use memscope::analysis::detectors::{LeakDetector, LeakDetectorConfig};

// Create leak detector
let detector = LeakDetector::new(LeakDetectorConfig::default());

// Run detection
let result = detector.detect(&allocations);

println!("Detected {} potential leaks", result.issues);
for detail in &result.details {
    println!("  {}", detail);
}
```

### Comprehensive Analysis

```rust
use memscope::analysis::AnalysisManager;

let manager = AnalysisManager::new();

// Perform comprehensive analysis
let report = manager.perform_comprehensive_analysis(&allocations, &stats);

println!("Fragmentation ratio: {}", report.fragmentation_analysis.fragmentation_ratio);
println!("Unsafe FFI operations: {}", report.unsafe_ffi_stats.total_operations);
```

### Pattern Analysis

```rust
// Analyze async patterns
let async_analyzer = get_global_async_analyzer();
let async_analysis = async_analyzer.analyze_async_patterns();

// Analyze borrow patterns
let borrow_analyzer = get_global_borrow_analyzer();
let borrow_analysis = borrow_analyzer.analyze_borrow_patterns();

// Analyze closure patterns
let closure_analyzer = get_global_closure_analyzer();
let closure_analysis = closure_analyzer.analyze_closure_patterns(&allocations);
```

## Design Principles

### 1. Modularity
Detectors and analyzers are independent:
- **Benefits**: Easy to add new analyses
- **Trade-off**: More complex to coordinate

### 2. Extensibility
Easy to add custom detectors:
- **Benefits**: Flexible for specific use cases
- **Trade-off**: API complexity

### 3. Performance
Optimized for efficient analysis:
- **Benefits**: Fast analysis
- **Trade-off**: May use more memory

## Best Practices

1. **Detector Selection**: Use appropriate detectors for your use case
2. **Configuration**: Customize detector configurations for better results
3. **Error Handling**: Always handle analysis errors
4. **Performance**: Cache analysis results when possible

## Limitations

1. **False Positives**: Detectors may report false positives
2. **Performance**: Complex analyses may be slow
3. **Memory Usage**: Analysis may consume significant memory
4. **Context**: Some analyses require additional context

## Future Improvements

1. **Better Accuracy**: Reduce false positives
2. **More Detectors**: Add more specialized detectors
3. **Performance**: Improve analysis performance
4. **Machine Learning**: Use ML for pattern detection
5. **Real-time Analysis**: Support real-time analysis

## Relation Inference Engine

### Overview

The relation inference engine automatically detects semantic relationships between memory allocations, helping to understand program memory structure and ownership models.

### Supported Relationship Types

| Relationship | Description | Detection Method |
|--------------|-------------|------------------|
| **Owner** | A owns or points to B | Pointer scanning - find pointer to B in A's memory |
| **Slice** | A is a sub-view of B | Address range detection - A's pointer is inside B |
| **Clone** | A is a clone of B | Content similarity + time window + call stack matching |
| **Shared** | A and B share ownership | Arc/Rc control block pattern recognition |

### Usage

```rust
use memscope_rs::analysis::relation_inference::{RelationGraphBuilder, Relation};

// Build relation graph from active allocations
let graph = RelationGraphBuilder::build(&allocations, None);

// Query relationships
for edge in &graph.edges {
    println!("{:?}: {} -> {}", edge.relation, edge.from, edge.to);
}

// Detect circular references
let cycles = graph.detect_cycles();
if !cycles.is_empty() {
    println!("Detected {} circular references", cycles.len());
}

// Get all nodes
let nodes = graph.all_nodes();
```

### Accuracy Metrics

Based on real test data:

```
=== Clone Detection Accuracy ===
Precision: 100.00%
Recall: 100.00%
F1 Score: 100.00%

=== Owner Detection Accuracy ===
✅ Box<Vec> relationship correctly detected
✅ Independent Vec no false positives

=== Performance ===
1000 allocations build time: ~230ms
```

### Configuration Options

```rust
use memscope_rs::analysis::relation_inference::{GraphBuilderConfig, CloneConfig};

let config = GraphBuilderConfig {
    clone_config: CloneConfig {
        min_similarity: 0.8,              // Minimum similarity threshold
        min_similarity_no_stack_hash: 0.95, // Stricter threshold without call stack
        max_time_diff_ns: 10_000_000,     // 10ms time window
        max_clone_edges_per_node: 10,     // Max clone edges per node
        ..Default::default()
    },
};

let graph = RelationGraphBuilder::build(&allocations, Some(config));
```

### Detection Algorithm Details

#### Owner Detection

Scans pointer values in allocation memory. If a pointer to another allocation is found, an Owner relationship is established.

```rust
// Detection flow
1. Read allocation memory content
2. Scan each 8-byte aligned position
3. Parse as pointer value
4. Look up target allocation in RangeMap
5. Create Owner edge
```

#### Slice Detection

Detects if one allocation's pointer falls inside another allocation (not at the start).

```rust
// Detection conditions
1. A.ptr is within B's address range (B.ptr < A.ptr < B.ptr + B.size)
2. A.size <= 256 (Slice metadata is usually small)
3. A's full range is within B
```

#### Clone Detection

Detects clone relationships based on content similarity and time window.

```rust
// Detection conditions
1. Same TypeKind and size
2. Same call_stack_hash (or both None)
3. Allocation time difference within window
4. Content similarity >= threshold
```

#### Shared Detection

Detects Arc/Rc shared ownership.

```rust
// Detection conditions
1. Multiple Owner edges point to the same target
2. Target memory layout matches ArcInner structure
3. strong_count and weak_count are within reasonable range
```

### Notes

1. **Owner Detection**: Requires metadata on heap (e.g., `Box<Vec>`), stack metadata cannot be scanned
2. **Clone Detection**: Relies on call stack hash, allocations with same call stack are grouped for comparison
3. **Shared Detection**: Depends on Owner relationships, requires Owner detection first
4. **Performance**: Uses sliding time window to avoid O(n²) complexity