🦀 memscope-rs - Advanced Rust Memory Analysis & Visualization
memscope-rs is a comprehensive Rust memory analysis toolkit that provides real-time tracking, visualization, and analysis of memory allocations in Rust applications. It features a custom global allocator, intuitive variable tracking, and beautiful SVG visualizations.
🌟 Key Features
🔍 Advanced Memory Tracking
- Custom Global Allocator: Tracks every heap allocation/deallocation automatically
- Variable Association: Link memory allocations to source code variables using
track_var!
macro - Thread-Safe: Full multi-threading support with deadlock prevention
- Type Recognition: Intelligent Rust type detection and categorization
📊 Rich Visualizations
- Enhanced SVG Reports: Beautiful, professional memory usage charts
- Type Categorization: Groups allocations by Collections, Text, Smart Pointers, etc.
- Timeline Views: Visual allocation lifecycle tracking
- Human-Readable Formats: Displays "1.2 KB", "5.4 MB" instead of raw bytes
🛡️ Production Ready
- Deadlock-Free: Advanced lock ordering and
try_lock
strategies - Performance Optimized: Minimal overhead with graceful degradation
- Error Resilient: Comprehensive error handling and recovery
- Memory Safe: Extensive safety testing and validation
📈 Export & Analysis
- JSON Export: Detailed memory snapshots for programmatic analysis
- SVG Visualization: Intuitive charts for human analysis
- Statistics: Peak memory, allocation counts, type breakdowns
- Lifecycle Tracking: Variable creation and destruction patterns
🚀 Quick Start
Installation
Add to your Cargo.toml
:
[]
= "0.1.0"
# Optional: Enable backtrace support
= { = "0.1.0", = ["backtrace"] }
Basic Usage
use ;
📖 Comprehensive Guide
Supported Types
The track_var!
macro works with these Rust types:
// Collections
let numbers = vec!;
track_var!.ok;
// Text
let message = String from;
track_var!.ok;
// Smart Pointers
let boxed_data = Box new;
track_var!.ok;
// Reference Counted
let shared_data = new;
track_var!.ok;
// Thread-Safe Shared
let arc_data = new;
track_var!.ok;
Advanced Usage
Memory Lifecycle Tracking
Concurrent Applications
use Arc;
use thread;
Understanding the Visualizations
SVG Output Features
The enhanced SVG visualization includes:
-
Header Statistics Panel
- Active allocations count
- Current memory usage (human-readable)
- Peak memory usage
- Total allocation count
-
Memory Usage by Type Chart
- Bar chart showing memory consumption per type
- Color-coded by category (Collections=Blue, Text=Green, etc.)
- Shows both size and allocation count
-
Tracked Variables by Category
- Groups your tracked variables by type category
- Shows which variables consume the most memory
- Helps identify memory hotspots
-
Allocation Timeline
- Visual timeline of when variables were allocated
- Shows variable names and sizes
- Helps understand allocation patterns
JSON Output Structure
🛡️ Safety & Security
Security Analysis
We've conducted comprehensive security analysis covering:
- Memory Safety: Extensive testing of unsafe allocator code
- Thread Safety: Deadlock prevention and race condition testing
- Resource Management: Memory leak detection and bounds checking
- Error Handling: Graceful failure modes and recovery
See SECURITY_ANALYSIS.md for detailed analysis.
Performance Characteristics
- Allocation Overhead: < 5% in typical applications
- Memory Overhead: ~50-100 bytes per tracked allocation
- Lock Contention: Minimized with
try_lock
strategies - Export Performance: < 10 seconds for 10,000+ allocations
Production Considerations
# Disable tracking in release builds
init;
# Or use conditional compilation
init;
🧪 Testing
Running Tests
# Basic tests
# Stress tests
# Safety tests
# Performance benchmarks
# Edge cases
# Comprehensive integration tests
Test Coverage
- Unit Tests: Core functionality testing
- Integration Tests: Real-world usage scenarios
- Stress Tests: High-load and concurrent scenarios
- Safety Tests: Memory safety and error handling
- Performance Tests: Overhead and bottleneck analysis
- Edge Cases: Unusual inputs and boundary conditions
📊 Visual Memory Analysis
memscope-rs generates comprehensive SVG visualizations that provide deep insights into your application's memory usage patterns. Here's what each section of the generated report shows:
🎯 Performance Dashboard (Top Section)
Four key performance gauges displaying:
- Memory Efficiency: Allocation/deallocation ratio (35.7% in example)
- Average Allocation Size: Mean size per allocation (1.0K bytes)
- Memory Utilization: Current vs peak memory usage (100.0%)
- Active Allocations: Number of currently tracked allocations (25.0K)
🔥 Memory Allocation Heatmap (Second Section)
A 20x8 grid showing allocation density patterns:
- X-axis: Allocation size (small to large)
- Y-axis: Time progression
- Color intensity: Number of allocations (blue=cold, red=hot)
- Numbers in cells: Exact allocation counts
📊 Memory Usage by Type & Fragmentation Analysis (Third Row)
Left side - Type Usage Chart: Pie chart showing memory distribution by data types Right side - Fragmentation Analysis: Histogram of allocation sizes:
- Green bars: Small allocations (good for performance)
- Orange bars: Medium allocations (moderate impact)
- Red bars: Large allocations (potential fragmentation risk)
🔍 Categorized Allocations & Call Stack Analysis (Fourth Row)
Left side - Categorized Allocations: Memory usage grouped by allocation categories Right side - Call Stack Analysis: Tree visualization showing:
- Colored nodes: Different source locations
- Node size: Proportional to memory usage
- Labels: Source location with allocation count and total bytes
📈 Memory Growth Trends (Fifth Section)
Time-series visualization showing:
- Green trend line: Memory usage progression over time
- Data points: Specific measurement points
- Red dashed line: Peak memory usage indicator
- Trend analysis: Growth patterns and memory behavior
📱 Memory Timeline (Sixth Section)
Detailed timeline showing:
- Variable lifecycles: When variables are allocated and deallocated
- Memory blocks: Visual representation of active allocations
- Time progression: Left to right temporal flow
🎨 Interactive Legend & Summary (Bottom Section)
Left side - Legend: Color coding explanation for all chart elements Right side - Summary: Key statistics including:
- Total active allocations
- Tracked variables percentage
- Average allocation size
- Memory efficiency metrics
- Peak vs current memory comparison
📊 Examples & Use Cases
The examples/
directory contains comprehensive demonstration programs showcasing different memory usage patterns:
🚀 Basic Examples
basic_usage.rs
- Simple tracking example showing fundamental usagelifecycles.rs
- Variable lifecycle tracking with scope management
💪 Advanced Examples
-
heavy_workload.rs
- Complex application simulation with:- Web server session management (1,000 sessions)
- Data pipeline processing (10,000+ records)
- LRU cache system with hit/miss patterns
- Concurrent worker pool (8 threads, 2,000 tasks)
-
memory_stress_test.rs
- Extreme stress testing scenarios including:- Massive Allocation Burst: 50,000+ rapid allocations
- Memory Fragmentation: Complex fragmentation patterns
- Concurrent Storm: 16 threads with 80,000+ allocations
- Large Object Stress: Objects up to 10MB each
- Rapid Cycles: 100,000+ allocation/deallocation cycles
🎯 Running Examples
# Basic usage demonstration
# Variable lifecycle tracking
# Complex workload simulation
# Extreme stress testing (generates rich visualizations)
Each example generates detailed JSON snapshots and beautiful SVG visualizations showing memory usage patterns, performance metrics, and allocation analysis.
Example 1: Web Server Memory Analysis
use ;
Example 2: Data Processing Pipeline
use ;
🔧 Configuration
Features
[]
= { = "0.1.0", = ["backtrace"] }
Available features:
backtrace
: Enable backtrace capture for allocations (requiresbacktrace
crate)tracking-allocator
: Enable custom global allocator (default)
Environment Variables
# Set logging level
RUST_LOG=memscope_rs=debug
# Disable tracking at runtime
TRACE_TOOLS_DISABLED=1
🤝 Contributing
We welcome contributions! Please see our contributing guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Add tests for your changes
- Run the full test suite (
cargo test
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
Development Setup
📄 License
This project is licensed under the Apache License, Version 2.0 - see the LICENSE file for details.
🙏 Acknowledgments
- Rust community for excellent tooling and libraries
- Contributors to the
serde
,svg
, andtracing
crates - Memory analysis research and best practices from the systems programming community
📞 Support
- Documentation: Run
cargo doc --open
to view local documentation - Issues: GitHub Issues
- Discussions: GitHub Discussions
Made with ❤️ and 🦀 by the Rust community