BorrowScope Runtime
A comprehensive runtime tracking library for visualizing Rust's ownership and borrowing system. BorrowScope Runtime captures ownership transfers, borrows, smart pointer operations, and unsafe code patterns as they happen, generating structured event data for analysis and visualization.
Why BorrowScope Runtime?
Rust's ownership system operates at compile time, making it invisible during execution. BorrowScope Runtime bridges this gap by instrumenting your code to capture every ownership operation at runtime. Whether you're learning Rust, debugging complex ownership issues, or analyzing memory patterns, this library makes the invisible mechanics of Rust's memory model visible.
Features
- Comprehensive Coverage: 41+ tracking functions covering all Rust ownership patterns
- Zero-Cost Abstraction: Complete compile-time elimination when
trackfeature is disabled - Thread Safety: All operations are thread-safe with efficient synchronization
- RAII Guards: Automatic drop tracking with guard types
- Event Sourcing: Store events and build ownership graphs on demand
- Rich Analysis: Lifetime analysis, timeline construction, and graph statistics
- JSON Export: Export tracking data for visualization tools
- Performance: ~75-80ns per tracking call, ~80 bytes per event
Quick Start
Add to your Cargo.toml:
[]
= { = "0.1", = ["track"] }
Basic usage:
use *;
Comprehensive API
Basic Ownership Tracking
Track fundamental ownership operations:
// Variable creation and destruction
let x = track_new; // Track variable creation
let y = track_move; // Track ownership transfer
track_drop; // Track variable drop
// Borrowing operations
let data = track_new;
let r = track_borrow; // Track immutable borrow
let r_mut = track_borrow_mut; // Track mutable borrow
RAII Guards (Automatic Drop Tracking)
Eliminate manual drop tracking with RAII guards:
// Guards support transparent access via Deref/DerefMut
let guard = track_new_guard;
println!; // Access inner value
Smart Pointer Tracking
Track reference-counted smart pointers with precise count monitoring:
use Rc;
use Arc;
// Rc<T> tracking
let rc1 = track_rc_new;
let rc2 = track_rc_clone;
// Automatically tracks strong_count and weak_count
// Arc<T> tracking (thread-safe)
let arc1 = track_arc_new;
let arc2 = track_arc_clone;
Interior Mutability Tracking
Monitor RefCell and Cell operations with runtime borrow checking:
use ;
// RefCell tracking
let cell = track_refcell_new;
let borrow = refcell_borrow!;
let borrow_mut = refcell_borrow_mut!;
refcell_drop!;
// Cell tracking
let cell = track_cell_new;
let value = track_cell_get;
track_cell_set;
Unsafe Code Tracking
Comprehensive tracking for unsafe operations:
// Raw pointer operations
let x = 42;
let ptr = track_raw_ptr;
let ptr_mut = track_raw_ptr_mut;
unsafe
// Unsafe block tracking
unsafe
// FFI and transmute tracking
track_ffi_call;
track_transmute;
track_unsafe_fn_call;
track_union_field_access;
Static and Const Tracking
Monitor global variable access patterns:
// Static variable tracking
static mut COUNTER: i32 = 0;
track_static_init;
track_static_access;
// Const evaluation tracking
const PI: f64 = 3.14159;
track_const_eval;
Async Tracking
Track async blocks and await expressions:
// Async block tracking
track_async_block_enter;
// ... async block body ...
track_async_block_exit;
// Await expression tracking
track_await_start;
// ... await completes ...
track_await_end;
Control Flow Tracking
Track loops, branches, and control flow:
// Loop tracking
track_loop_enter;
track_loop_iteration;
track_loop_iteration;
track_loop_exit;
// Match tracking
track_match_enter;
track_match_arm;
track_match_exit;
// Branch tracking
track_branch;
// Return tracking
track_return;
// Try operator tracking
track_try;
Method Call Tracking
Track common method calls:
// Clone tracking
track_clone;
// Lock tracking (Mutex/RwLock)
track_lock;
track_lock;
// Unwrap tracking
track_unwrap;
track_unwrap;
Advanced API Features
Custom ID Correlation
All tracking functions have _with_id variants for custom correlation:
let custom_id = "user_defined_123";
let x = track_new_with_id;
let r = track_borrow_with_id;
Event Querying and Filtering
Rich querying capabilities for event analysis:
// Get all events or filtered subsets
let all_events = get_events;
let new_events = get_new_events;
let borrow_events = get_borrow_events;
let move_events = get_move_events;
let drop_events = get_drop_events;
// Filter events by variable or criteria
let var_events = get_events_for_var;
let filtered = get_events_filtered;
// Get event statistics
let counts = get_event_counts;
let summary = get_summary;
print_summary;
Batch Operations
Efficient batch processing for performance:
let var_names = vec!;
track_drop_batch;
Ownership Graph Analysis
Build and analyze ownership relationships:
let graph = get_graph;
// Graph statistics
let stats = graph.stats;
println!;
// Find specific variables and relationships
let var = graph.find_variable;
let borrows = graph.find_borrows;
// Analyze ownership patterns
for relationship in &graph.edges
Lifetime Analysis
Advanced lifetime relationship analysis:
// Build timeline from events
let timeline = from_events;
// Analyze lifetime relationships
let relations = timeline.analyze_lifetimes;
for relation in relations
// Detect elision rules
let elision_rules = timeline.detect_elision_rules;
Export and Visualization
Export tracking data for external analysis:
// Export to JSON file
export_json.unwrap;
// Manual export with custom data
let events = get_events;
let graph = get_graph;
let export_data = new;
export_data.to_file.unwrap;
Event Types
BorrowScope Runtime tracks 40+ event types covering all ownership patterns:
| Category | Events |
|---|---|
| Basic Ownership | New, Borrow, Move, Drop |
| Smart Pointers | RcNew, RcClone, ArcNew, ArcClone |
| Interior Mutability | RefCellNew, RefCellBorrow, RefCellDrop, CellNew, CellGet, CellSet |
| Static/Const | StaticInit, StaticAccess, ConstEval |
| Unsafe Operations | RawPtrCreated, RawPtrDeref, UnsafeBlockEnter, UnsafeBlockExit, UnsafeFnCall |
| FFI/Transmute | FfiCall, Transmute, UnionFieldAccess |
| Async | AsyncBlockEnter, AsyncBlockExit, AwaitStart, AwaitEnd |
| Loops | LoopEnter, LoopIteration, LoopExit |
| Control Flow | MatchEnter, MatchArm, MatchExit, Branch, Return, Try |
| Method Calls | Clone, Lock, Unwrap |
| Access | IndexAccess, FieldAccess, Call, Deref |
All events include timestamps and are serializable to JSON for analysis.
Architecture
BorrowScope Runtime uses an event sourcing architecture:
- Event Recording: Track operations as timestamped events
- Thread-Safe Storage: Store events in a global, thread-safe tracker
- On-Demand Analysis: Build ownership graphs and timelines from event streams
- Export Pipeline: Serialize data to JSON for visualization tools
Key components:
- Tracker: Global event recorder with atomic timestamp generation
- Event System: Comprehensive event types with JSON serialization
- Graph Builder: Constructs ownership graphs from event streams
- RAII Guards: Automatic resource tracking with scope-based cleanup
- Lifetime Analyzer: Timeline construction and relationship analysis
Performance
Optimized for minimal runtime overhead:
- Single tracking call: ~75-80ns
- 1000 operations: ~150μs
- JSON export (1000 events): ~1ms
- Memory per event: ~80 bytes
- Zero cost when disabled: Complete compile-time elimination
Thread safety achieved through:
parking_lot::Mutexfor efficient locking (40-60% faster than std)AtomicU64for lock-free timestamp generation- Event sourcing to avoid complex concurrent graph updates
Feature Flags
track- Enables runtime tracking. Without this feature, all tracking functions compile to no-ops with zero overhead.
# Development/debugging (with tracking)
[]
= { = "0.1", = ["track"] }
# Production (zero overhead)
[]
= "0.1"
Testing
Comprehensive test suite with 555+ tests:
# Run all tests
# Run specific test categories
# Run benchmarks
Error Handling
Robust error handling with comprehensive error types:
use ;
match export_json
Documentation
Generate and view complete API documentation:
License
Licensed under the Apache License, Version 2.0. See the main BorrowScope repository for full license information.