memscope-rs - Rust Memory Tracking & Analysis Library
What is this thing?
memscope-rs is a Rust library for tracking memory allocations and generating analysis reports. Think of it as a friendly neighborhood memory detective ๐ต๏ธ that helps you understand what your variables are up to when you're not looking.
It provides simple macros for variable tracking and exports data in JSON and SVG formats. Perfect for those "wait, where did all my memory go?" moments.
Core Features
1. Variable Tracking
- Non-intrusive tracking: Use
track_var!
macro to track variables without breaking your existing code (we promise!) - Smart pointer support: Full support for
Rc<T>
,Arc<T>
,Box<T>
- because Rust loves its smart pointers - Lifecycle analysis: Automatic recording of variable lifecycles from birth to... well, drop
- Reference count monitoring: Real-time tracking of smart pointer reference count changes (watch those Rc clones!)
2. Memory Analysis
- Memory leak detection: Find those sneaky leaks hiding in your code
- Fragmentation analysis: Basic heap fragmentation reporting
- Usage pattern detection: Simple memory usage pattern recognition
- Performance issue identification: Spot memory-related bottlenecks
3. Data Export & Interactive Visualization
- JSON format: Export detailed memory allocation data for programmatic analysis
- SVG visualization: Generate memory usage charts and timelines (pretty pictures!)
- ๐ฏ HTML Interactive Dashboard: Full-featured web-based dashboard with clickable charts, filterable data, and real-time analysis
- Multiple export modes: Fast mode, detailed mode, and "let the computer decide" mode
4. Safety Analysis
- FFI boundary tracking: Monitor memory interactions between Rust and C/C++ code
- Security violation detection: Identify potential memory safety issues
- Use-after-free detection: Catch those "oops, I used it after freeing it" moments
Available Commands and Tools
Example Programs
# Basic usage demonstration
# Ownership patterns demo (prepare to be amazed by Rust's ownership system)
# Complex lifecycle showcase
# Memory stress test (warning: may stress your computer too)
# Performance test
# Unsafe/FFI safety demo (for the brave souls)
Performance Benchmarks
# Run comprehensive performance benchmarks
# Simple benchmark (for when you don't have all day)
# Core performance test
# Performance-only benchmark (no frills, just numbers)
Analysis Tools
# Lifecycle analysis
# Allocation count diagnostics
# Large active allocations analysis
# Test mode validation
Usage Examples
Basic Usage
use ;
Smart Pointer Tracking
use Rc;
use Arc;
// Track reference counted pointers
let rc_data = new;
track_var!;
// Track atomic reference counted pointers (for when you need thread safety)
let arc_data = new;
track_var!;
// Cloning operations are also tracked (watch the ref count go up!)
let rc_clone = clone;
track_var!;
Export Configuration
use ExportOptions;
let options = new
.include_system_allocations // Fast mode (recommended)
.verbose_logging // For when you want ALL the details
.buffer_size; // 128KB buffer (because bigger is better, right?)
if let Err = tracker.export_to_json_with_options
Build & Installation
System Requirements
- Rust: 1.70 or later (we're not asking for much)
- OS: Linux, macOS, Windows (basically everywhere Rust runs)
- Memory: At least 4GB RAM recommended (for analyzing large projects)
From Source
# Clone the repository
# Build the project (grab a coffee, this might take a moment)
# Run tests (cross your fingers)
# Try an example
From Crates.io
# Add to your project
# Or manually add to Cargo.toml
Feature Flags
[]
= { = "0.1.2", = ["backtrace", "derive"] }
Available features:
backtrace
- Enable stack trace collection (adds overhead, but gives you the full story)derive
- Enable derive macro support (experimental, use at your own risk)tracking-allocator
- Custom allocator support (enabled by default)
Development Setup
# Install development dependencies
# Enable debug logging (prepare for information overload)
# Run continuous testing (for the paranoid developer)
# Generate code coverage report (because metrics matter)
Output File Structure & Interactive Dashboard
After running programs, you'll find analysis results in the MemoryAnalysis/
directory:
MemoryAnalysis/
โโโ basic_usage/
โ โโโ basic_usage_snapshot.json # JSON memory data (the raw truth)
โ โโโ basic_usage_graph.svg # SVG memory usage chart (the pretty version)
โ โโโ memory_timeline.svg # Memory timeline graph
โ โโโ dashboard.html # ๐ฏ Interactive dashboard (click all the things!)
โโโ complex_lifecycle/
โ โโโ allocations.json # Allocation details
โ โโโ lifecycle_analysis.json # Lifecycle analysis
โ โโโ performance_metrics.json # Performance metrics
โ โโโ security_violations.json # Security issue reports (hopefully empty)
โโโ benchmark_results/
โโโ benchmark_results.json # Benchmark results
โโโ performance_report.md # Performance report
โโโ comparison_charts.svg # Comparison charts
๐ Interactive HTML Dashboard Features
The generated dashboard.html
provides a rich, interactive experience:
- ๐ Interactive Charts: Click and zoom on memory usage graphs
- ๐ Filterable Data Tables: Search and filter allocations by type, size, or lifetime
- ๐ Real-time Statistics: Live updating memory metrics and trends
- ๐ฏ Variable Drill-down: Click on any variable to see detailed lifecycle information
- ๐ฑ Responsive Design: Works on desktop, tablet, and mobile browsers
- ๐ Cross-references: Navigate between related allocations and smart pointer relationships
To view the dashboard:
# After running your tracked program
# Or simply double-click the HTML file in your file manager
Project Highlights
1. Non-intrusive Design
- Use macros for tracking without changing your code structure
- Variables work normally after tracking (no weird side effects)
- Selective tracking of key variables instead of global tracking (because sometimes less is more)
2. Smart Analysis
- Automatic identification of memory usage patterns and anomalies
- Smart pointer reference count change tracking
- Variable relationship analysis and dependency graph generation
3. Diverse Output Formats
- JSON data for programmatic processing and integration
- SVG charts for intuitive visualization
- HTML dashboard for interactive analysis (with actual buttons to click!)
4. Performance Optimization
- Fast export mode to reduce performance overhead
- Parallel processing support for large datasets
- Configurable buffer sizes for I/O optimization
5. Safety Analysis
- FFI boundary memory safety checks
- Automatic detection of potential security vulnerabilities
- Memory access pattern safety assessment
Comparison with Other Tools
Feature | memscope-rs | Valgrind | Heaptrack | jemalloc |
---|---|---|---|---|
Rust Native | โ | โ | โ | โ ๏ธ |
Variable Names | โ | โ | โ | โ |
Smart Pointer Analysis | โ | โ ๏ธ | โ ๏ธ | โ |
Visual Reports | โ | โ ๏ธ | โ | โ |
Production Ready | โ ๏ธ | โ | โ | โ |
Interactive Timeline | โ | โ | โ ๏ธ | โ |
Real-time Tracking | โ ๏ธ | โ | โ | โ |
Low Overhead | โ ๏ธ | โ ๏ธ | โ | โ |
Mature Ecosystem | โ | โ | โ | โ |
Honest Assessment
memscope-rs (this project)
- โ Strengths: Rust native, variable name tracking, smart pointer analysis, interactive visualization
- โ ๏ธ Current status: Experimental tool, good for development debugging, noticeable performance overhead
- โ Limitations: Not mature enough, not suitable for production, relatively limited functionality
Valgrind
- โ Strengths: Industry standard, battle-tested, comprehensive features, production-grade
- โ ๏ธ Limitations: Not Rust native, significant performance overhead, steep learning curve
- ๐ฏ Best for: Deep memory debugging, complex problem troubleshooting
Heaptrack
- โ Strengths: Mature profiling tool, good visualization, relatively low overhead
- โ ๏ธ Limitations: Mainly for C/C++, limited Rust-specific features
- ๐ฏ Best for: Performance analysis, memory usage optimization
jemalloc
- โ Strengths: Production-grade allocator, excellent performance, built-in analysis features
- โ ๏ธ Limitations: Mainly an allocator, basic analysis functionality
- ๐ฏ Best for: Production environments, performance optimization
When to Use memscope-rs
Good scenarios:
- ๐ Rust project development debugging - Want to understand specific variable memory usage
- ๐ Learning Rust memory management - Visualize ownership and borrowing concepts
- ๐งช Prototype validation - Quickly verify memory usage patterns
- ๐ฏ Smart pointer analysis - Deep dive into Rc/Arc reference count changes
Not recommended scenarios:
- ๐ซ Production monitoring - Use mature tools instead
- ๐ซ High-performance requirements - Tracking overhead might be unacceptable
- ๐ซ Complex memory issues - Valgrind and friends are better
- ๐ซ Large project comprehensive analysis - Functionality and stability not sufficient yet
Performance Characteristics
Based on actual testing (not marketing numbers):
Tracking Overhead
- Small programs: ~5-15% runtime overhead (not too bad!)
- Memory usage: ~10-20% additional memory for tracking data
- Large datasets: Performance degrades significantly (we're working on it)
Export Performance
- Small datasets (< 1000 allocations): < 100ms (blink and you'll miss it)
- Medium datasets (1000-10000 allocations): 100ms - 1s (time for a sip of coffee)
- Large datasets (> 10000 allocations): Several seconds (time for a full coffee break)
Known Limitations
- Thread safety: Basic support, may have issues under heavy concurrency
- Memory leaks: Tracking itself may leak memory in some scenarios (ironic, we know)
- Platform support: Limited testing on different platforms
- Error handling: Some errors are silently ignored (we're working on being more vocal)
Current Development Status
What works:
- โ Basic variable tracking
- โ JSON export with allocation data
- โ Simple SVG charts
- โ Smart pointer support (Rc, Arc, Box)
- โ Basic CLI tools
- โ Examples run successfully
Known issues (we're honest about our problems):
- โ ๏ธ Performance overhead in large applications
- โ ๏ธ 154
unwrap()
calls that could panic (we counted them) - โ ๏ธ Lock contention in multi-threaded scenarios
- โ ๏ธ Inconsistent API design across modules
- โ ๏ธ Memory usage by tracker itself
- โ ๏ธ Thread safety not thoroughly tested
Planned improvements:
- ๐ Replace dangerous
unwrap()
calls with proper error handling - ๐ Optimize lock usage and reduce contention
- ๐ Better error handling and reporting
- ๐ Performance optimization for large datasets
- ๐ More comprehensive testing
- ๐ API consistency improvements
Use Cases
- Development debugging: Track memory usage during development
- Performance optimization: Identify memory bottlenecks and optimization opportunities
- Memory leak troubleshooting: Locate and fix memory leak issues
- Code review: Analyze code memory usage patterns
- Educational demos: Demonstrate Rust memory management mechanisms
Technical Architecture
The project uses a modular design:
- core/: Core tracking functionality and type definitions
- analysis/: Memory analysis algorithms and pattern recognition
- export/: Data export and visualization generation
- cli/: Command-line tools and user interface
- bin/: Executable analysis tools
Testing
# Run basic tests
# Run with specific features
# Run performance tests
# Run examples as integration tests
Troubleshooting
Common Issues
Export fails with large datasets:
// Use smaller buffer or exclude system allocations
let options = new
.include_system_allocations
.buffer_size;
High memory usage:
# Disable backtrace collection
Permission errors on output:
# Ensure write permissions
Contributing
This is experimental software, but we welcome contributions! Please:
- Test thoroughly - Make sure your changes don't break existing functionality
- Document limitations - Be honest about what doesn't work
- Performance test - Measure the impact of your changes
- Keep it simple - Avoid over-engineering (we have enough complexity already)
# Development workflow
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT License (LICENSE-MIT)
at your option.
Disclaimer
This software is provided "as is" without warranty. Use at your own risk. Not suitable for production environments yet, but we're working on it! Performance claims are based on limited testing and may not reflect real-world usage.
Remember: with great power comes great responsibility... and sometimes memory leaks. ๐ฆ
Made with โค๏ธ and ๐ฆ by developers who care about memory (maybe too much)