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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
use crate::capture::types::ImplementationDifficulty;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnknownMemoryRegionAnalysis {
    pub total_unknown_bytes: usize,
    pub unknown_percentage: f64,
    pub unknown_categories: Vec<UnknownMemoryCategory>,
    pub potential_causes: Vec<UnknownMemoryCause>,
    pub reduction_strategies: Vec<UnknownRegionReductionStrategy>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnknownMemoryCategory {
    pub category_type: UnknownRegionType,
    pub description: String,
    pub estimated_size: usize,
    pub confidence_level: f64,
    pub examples: Vec<UnknownMemoryExample>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum UnknownRegionType {
    MemoryMappedRegions,
    ThreadLocalStorage,
    DynamicLibraryRegions,
    SystemReservedRegions,
    JitCodeRegions,
    ExternalLibraryAllocations,
    GuardPages,
    VdsoRegions,
    AnonymousMappings,
    SharedMemorySegments,
    PreTrackingAllocations,
    CorruptedMetadata,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnknownMemoryExample {
    pub address_range: (usize, usize),
    pub size: usize,
    pub suspected_origin: String,
    pub access_pattern: MemoryAccessPattern,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum UnknownMemoryCause {
    ForeignFunctionInterface {
        library_name: String,
        function_name: Option<String>,
    },
    MemoryMapping {
        mapping_type: MappingType,
        file_path: Option<String>,
    },
    SystemAllocations {
        allocation_type: SystemAllocationType,
    },
    ThreadingMemory {
        thread_id: Option<u64>,
        memory_type: ThreadMemoryType,
    },
    DynamicLoading {
        library_path: String,
        load_time: u64,
    },
    InstrumentationGaps {
        gap_type: InstrumentationGapType,
        description: String,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MappingType {
    FileMapping,
    AnonymousMapping,
    SharedMapping,
    DeviceMapping,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SystemAllocationType {
    KernelBuffers,
    DriverMemory,
    SystemCaches,
    HardwareReserved,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ThreadMemoryType {
    ThreadStack,
    ThreadLocalStorage,
    ThreadControlBlock,
    ThreadSynchronization,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum InstrumentationGapType {
    EarlyBootstrap,
    SignalHandlers,
    InterruptHandlers,
    AtomicOperations,
    CompilerOptimizations,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnknownRegionReductionStrategy {
    pub strategy_type: ReductionStrategyType,
    pub description: String,
    pub implementation_steps: Vec<String>,
    pub expected_improvement: f64,
    pub implementation_difficulty: ImplementationDifficulty,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ReductionStrategyType {
    EnhancedInstrumentation,
    BetterSymbolResolution,
    MemoryMappingTracking,
    FfiCallInterception,
    SystemCallMonitoring,
    ThreadAwareTracking,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemRegionInfo {
    pub region_type: String,
    pub description: String,
    pub read_only: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LibraryMappingInfo {
    pub start_address: usize,
    pub end_address: usize,
    pub permissions: String,
    pub file_path: String,
}

impl LibraryMappingInfo {
    pub fn contains_address(&self, addr: usize) -> bool {
        addr >= self.start_address && addr < self.end_address
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MemoryAccessPattern {
    Sequential,
    Random,
    Sparse,
    Unknown,
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Objective: Verify UnknownMemoryRegionAnalysis creation
    /// Invariants: All fields should be properly initialized
    #[test]
    fn test_analysis_creation() {
        let analysis = UnknownMemoryRegionAnalysis {
            total_unknown_bytes: 1024,
            unknown_percentage: 25.5,
            unknown_categories: vec![],
            potential_causes: vec![],
            reduction_strategies: vec![],
        };

        assert_eq!(
            analysis.total_unknown_bytes, 1024,
            "Total bytes should match"
        );
        assert_eq!(analysis.unknown_percentage, 25.5, "Percentage should match");
    }

    /// Objective: Verify UnknownMemoryCategory creation
    /// Invariants: All fields should be accessible
    #[test]
    fn test_category_creation() {
        let category = UnknownMemoryCategory {
            category_type: UnknownRegionType::MemoryMappedRegions,
            description: "Test category".to_string(),
            estimated_size: 4096,
            confidence_level: 0.85,
            examples: vec![],
        };

        assert_eq!(category.estimated_size, 4096, "Size should match");
        assert_eq!(category.confidence_level, 0.85, "Confidence should match");
    }

    /// Objective: Verify UnknownRegionType variants
    /// Invariants: All variants should be distinct
    #[test]
    fn test_region_type_variants() {
        let variants = [
            UnknownRegionType::MemoryMappedRegions,
            UnknownRegionType::ThreadLocalStorage,
            UnknownRegionType::DynamicLibraryRegions,
            UnknownRegionType::SystemReservedRegions,
            UnknownRegionType::JitCodeRegions,
            UnknownRegionType::ExternalLibraryAllocations,
            UnknownRegionType::GuardPages,
            UnknownRegionType::VdsoRegions,
            UnknownRegionType::AnonymousMappings,
            UnknownRegionType::SharedMemorySegments,
            UnknownRegionType::PreTrackingAllocations,
            UnknownRegionType::CorruptedMetadata,
        ];

        for variant in &variants {
            let debug_str = format!("{variant:?}");
            assert!(
                !debug_str.is_empty(),
                "Variant should have debug representation"
            );
        }
    }

    /// Objective: Verify UnknownMemoryExample creation
    /// Invariants: All fields should be properly initialized
    #[test]
    fn test_example_creation() {
        let example = UnknownMemoryExample {
            address_range: (0x1000, 0x2000),
            size: 4096,
            suspected_origin: "mmap".to_string(),
            access_pattern: MemoryAccessPattern::Sequential,
        };

        assert_eq!(
            example.address_range.0, 0x1000,
            "Start address should match"
        );
        assert_eq!(example.size, 4096, "Size should match");
    }

    /// Objective: Verify UnknownMemoryCause variants
    /// Invariants: All variants should be constructible
    #[test]
    fn test_cause_variants() {
        let ffi_cause = UnknownMemoryCause::ForeignFunctionInterface {
            library_name: "libc".to_string(),
            function_name: Some("malloc".to_string()),
        };

        let mmap_cause = UnknownMemoryCause::MemoryMapping {
            mapping_type: MappingType::AnonymousMapping,
            file_path: None,
        };

        let system_cause = UnknownMemoryCause::SystemAllocations {
            allocation_type: SystemAllocationType::KernelBuffers,
        };

        let thread_cause = UnknownMemoryCause::ThreadingMemory {
            thread_id: Some(1),
            memory_type: ThreadMemoryType::ThreadStack,
        };

        let dynamic_cause = UnknownMemoryCause::DynamicLoading {
            library_path: "/lib/test.so".to_string(),
            load_time: 1000,
        };

        let gap_cause = UnknownMemoryCause::InstrumentationGaps {
            gap_type: InstrumentationGapType::EarlyBootstrap,
            description: "Early initialization".to_string(),
        };

        assert!(matches!(
            ffi_cause,
            UnknownMemoryCause::ForeignFunctionInterface { .. }
        ));
        assert!(matches!(
            mmap_cause,
            UnknownMemoryCause::MemoryMapping { .. }
        ));
        assert!(matches!(
            system_cause,
            UnknownMemoryCause::SystemAllocations { .. }
        ));
        assert!(matches!(
            thread_cause,
            UnknownMemoryCause::ThreadingMemory { .. }
        ));
        assert!(matches!(
            dynamic_cause,
            UnknownMemoryCause::DynamicLoading { .. }
        ));
        assert!(matches!(
            gap_cause,
            UnknownMemoryCause::InstrumentationGaps { .. }
        ));
    }

    /// Objective: Verify MappingType variants
    /// Invariants: All variants should be distinct
    #[test]
    fn test_mapping_type_variants() {
        assert!(matches!(MappingType::FileMapping, MappingType::FileMapping));
        assert!(matches!(
            MappingType::AnonymousMapping,
            MappingType::AnonymousMapping
        ));
        assert!(matches!(
            MappingType::SharedMapping,
            MappingType::SharedMapping
        ));
        assert!(matches!(
            MappingType::DeviceMapping,
            MappingType::DeviceMapping
        ));
    }

    /// Objective: Verify SystemAllocationType variants
    /// Invariants: All variants should be distinct
    #[test]
    fn test_system_allocation_type_variants() {
        let variants = [
            SystemAllocationType::KernelBuffers,
            SystemAllocationType::DriverMemory,
            SystemAllocationType::SystemCaches,
            SystemAllocationType::HardwareReserved,
        ];

        for variant in &variants {
            let debug_str = format!("{variant:?}");
            assert!(
                !debug_str.is_empty(),
                "Variant should have debug representation"
            );
        }
    }

    /// Objective: Verify ThreadMemoryType variants
    /// Invariants: All variants should be distinct
    #[test]
    fn test_thread_memory_type_variants() {
        let variants = [
            ThreadMemoryType::ThreadStack,
            ThreadMemoryType::ThreadLocalStorage,
            ThreadMemoryType::ThreadControlBlock,
            ThreadMemoryType::ThreadSynchronization,
        ];

        for variant in &variants {
            let debug_str = format!("{variant:?}");
            assert!(
                !debug_str.is_empty(),
                "Variant should have debug representation"
            );
        }
    }

    /// Objective: Verify InstrumentationGapType variants
    /// Invariants: All variants should be distinct
    #[test]
    fn test_instrumentation_gap_type_variants() {
        let variants = [
            InstrumentationGapType::EarlyBootstrap,
            InstrumentationGapType::SignalHandlers,
            InstrumentationGapType::InterruptHandlers,
            InstrumentationGapType::AtomicOperations,
            InstrumentationGapType::CompilerOptimizations,
        ];

        for variant in &variants {
            let debug_str = format!("{variant:?}");
            assert!(
                !debug_str.is_empty(),
                "Variant should have debug representation"
            );
        }
    }

    /// Objective: Verify UnknownRegionReductionStrategy creation
    /// Invariants: All fields should be accessible
    #[test]
    fn test_reduction_strategy_creation() {
        let strategy = UnknownRegionReductionStrategy {
            strategy_type: ReductionStrategyType::EnhancedInstrumentation,
            description: "Test strategy".to_string(),
            implementation_steps: vec!["Step 1".to_string(), "Step 2".to_string()],
            expected_improvement: 50.0,
            implementation_difficulty: ImplementationDifficulty::Medium,
        };

        assert_eq!(
            strategy.implementation_steps.len(),
            2,
            "Should have two steps"
        );
        assert_eq!(
            strategy.expected_improvement, 50.0,
            "Improvement should match"
        );
    }

    /// Objective: Verify ReductionStrategyType variants
    /// Invariants: All variants should be distinct
    #[test]
    fn test_reduction_strategy_type_variants() {
        let variants = [
            ReductionStrategyType::EnhancedInstrumentation,
            ReductionStrategyType::BetterSymbolResolution,
            ReductionStrategyType::MemoryMappingTracking,
            ReductionStrategyType::FfiCallInterception,
            ReductionStrategyType::SystemCallMonitoring,
            ReductionStrategyType::ThreadAwareTracking,
        ];

        for variant in &variants {
            let debug_str = format!("{variant:?}");
            assert!(
                !debug_str.is_empty(),
                "Variant should have debug representation"
            );
        }
    }

    /// Objective: Verify SystemRegionInfo creation
    /// Invariants: All fields should be accessible
    #[test]
    fn test_system_region_info_creation() {
        let info = SystemRegionInfo {
            region_type: "kernel".to_string(),
            description: "Kernel region".to_string(),
            read_only: true,
        };

        assert_eq!(info.region_type, "kernel", "Region type should match");
        assert!(info.read_only, "Should be read-only");
    }

    /// Objective: Verify LibraryMappingInfo creation and contains_address
    /// Invariants: Address bounds should be correctly checked
    #[test]
    fn test_library_mapping_info() {
        let info = LibraryMappingInfo {
            start_address: 0x1000,
            end_address: 0x2000,
            permissions: "r-x".to_string(),
            file_path: "/lib/test.so".to_string(),
        };

        assert!(info.contains_address(0x1000), "Start should be contained");
        assert!(info.contains_address(0x1500), "Middle should be contained");
        assert!(
            !info.contains_address(0x2000),
            "End should not be contained"
        );
        assert!(
            !info.contains_address(0x500),
            "Before should not be contained"
        );
    }

    /// Objective: Verify MemoryAccessPattern variants
    /// Invariants: All variants should be distinct
    #[test]
    fn test_memory_access_pattern_variants() {
        assert!(matches!(
            MemoryAccessPattern::Sequential,
            MemoryAccessPattern::Sequential
        ));
        assert!(matches!(
            MemoryAccessPattern::Random,
            MemoryAccessPattern::Random
        ));
        assert!(matches!(
            MemoryAccessPattern::Sparse,
            MemoryAccessPattern::Sparse
        ));
        assert!(matches!(
            MemoryAccessPattern::Unknown,
            MemoryAccessPattern::Unknown
        ));
    }

    /// Objective: Verify serialization of types
    /// Invariants: Types should serialize and deserialize correctly
    #[test]
    fn test_serialization() {
        let analysis = UnknownMemoryRegionAnalysis {
            total_unknown_bytes: 1024,
            unknown_percentage: 25.5,
            unknown_categories: vec![],
            potential_causes: vec![],
            reduction_strategies: vec![],
        };

        let json = serde_json::to_string(&analysis);
        assert!(json.is_ok(), "Should serialize to JSON");

        let deserialized: Result<UnknownMemoryRegionAnalysis, _> =
            serde_json::from_str(&json.unwrap());
        assert!(deserialized.is_ok(), "Should deserialize from JSON");
    }

    /// Objective: Verify edge case with zero values
    /// Invariants: Should handle zero values correctly
    #[test]
    fn test_zero_values() {
        let analysis = UnknownMemoryRegionAnalysis {
            total_unknown_bytes: 0,
            unknown_percentage: 0.0,
            unknown_categories: vec![],
            potential_causes: vec![],
            reduction_strategies: vec![],
        };

        assert_eq!(
            analysis.total_unknown_bytes, 0,
            "Zero bytes should be valid"
        );
        assert_eq!(
            analysis.unknown_percentage, 0.0,
            "Zero percentage should be valid"
        );
    }
}