Struct MemoryTracker

Source
pub struct MemoryTracker { /* private fields */ }
Expand description

Core memory tracking functionality.

The MemoryTracker maintains records of all memory allocations and deallocations, provides statistics, and supports exporting data in various formats.

Implementations§

Source§

impl MemoryTracker

Source

pub fn new() -> Self

Create a new memory tracker.

Source

pub fn is_fast_mode(&self) -> bool

Check if tracker is in fast mode (for testing)

Source

pub fn enable_fast_mode(&self)

Enable fast mode for testing

Source

pub fn fast_track_allocation( &self, ptr: usize, size: usize, var_name: String, ) -> TrackingResult<()>

Fast track allocation for testing (minimal overhead)

Source

pub fn analyze_memory_layout( &self, type_name: &str, size: usize, ) -> Option<MemoryLayoutInfo>

Analyze memory layout information

Source

pub fn analyze_generic_type( &self, type_name: &str, size: usize, ) -> Option<GenericTypeInfo>

Analyze generic type information

Source

pub fn analyze_dynamic_type( &self, type_name: &str, size: usize, ) -> Option<DynamicTypeInfo>

Analyze dynamic type information (trait objects)

Source

pub fn collect_runtime_state(&self) -> RuntimeStateInfo

Collect runtime state information

Source

pub fn analyze_stack_allocation( &self, type_name: &str, ptr: usize, ) -> Option<StackAllocationInfo>

Analyze stack allocation information

Source

pub fn analyze_temporary_object( &self, type_name: &str, ptr: usize, ) -> Option<TemporaryObjectInfo>

Analyze temporary object information

Source

pub fn analyze_memory_fragmentation(&self) -> EnhancedFragmentationAnalysis

Analyze memory fragmentation

Source

pub fn analyze_generic_instantiation( &self, type_name: &str, size: usize, ) -> Option<GenericInstantiationInfo>

Analyze enhanced generic instantiation

Source

pub fn analyze_type_relationships( &self, type_name: &str, ) -> Option<TypeRelationshipInfo>

Analyze type relationships

Source

pub fn track_type_usage(&self, type_name: &str) -> Option<TypeUsageInfo>

Track type usage

Source

pub fn track_function_calls( &self, scope_name: Option<&str>, ) -> Option<FunctionCallTrackingInfo>

Track function calls

Source

pub fn track_object_lifecycle( &self, ptr: usize, type_name: &str, ) -> Option<ObjectLifecycleInfo>

Track object lifecycle

Source

pub fn track_memory_access_patterns( &self, ptr: usize, size: usize, ) -> Option<MemoryAccessTrackingInfo>

Track memory access patterns

Source

pub fn track_allocation(&self, ptr: usize, size: usize) -> TrackingResult<()>

Track a new memory allocation.

Source

pub fn track_deallocation(&self, ptr: usize) -> TrackingResult<()>

Track a memory deallocation.

Source

pub fn track_deallocation_with_lifetime( &self, ptr: usize, lifetime_ms: u64, ) -> TrackingResult<()>

Track a memory deallocation with precise lifetime information. This method is specifically designed for TrackedVariable to ensure accurate lifetime_ms calculation.

Source

pub fn update_allocation_info( &self, ptr: usize, var_name: String, type_name: String, ) -> TrackingResult<()>

Update allocation info for an existing allocation without creating duplicates.

Source

pub fn create_synthetic_allocation( &self, ptr: usize, size: usize, var_name: String, type_name: String, creation_time: u64, ) -> TrackingResult<()>

Create a synthetic allocation for smart pointers (Rc/Arc) that don’t go through the allocator.

Source

pub fn create_smart_pointer_allocation( &self, ptr: usize, size: usize, var_name: String, type_name: String, creation_time: u64, ref_count: usize, data_ptr: usize, ) -> TrackingResult<()>

Create a specialized synthetic allocation for Rc/Arc with reference counting support.

Source

pub fn track_smart_pointer_clone( &self, clone_ptr: usize, source_ptr: usize, data_ptr: usize, new_ref_count: usize, weak_count: usize, ) -> TrackingResult<()>

Track smart pointer clone relationship

Source

pub fn update_smart_pointer_ref_count( &self, ptr: usize, strong_count: usize, weak_count: usize, ) -> TrackingResult<()>

Update reference count for a smart pointer

Source

pub fn mark_smart_pointer_data_deallocated( &self, data_ptr: usize, ) -> TrackingResult<()>

Mark smart pointer data as implicitly deallocated

Source

pub fn track_smart_pointer_deallocation( &self, ptr: usize, lifetime_ms: u64, final_ref_count: usize, ) -> TrackingResult<()>

Track the deallocation of a smart pointer with enhanced metadata.

Source

pub fn enhance_allocation_info(&self, allocation: &mut AllocationInfo)

Enhance allocation information with detailed analysis

Source

pub fn associate_var( &self, ptr: usize, var_name: String, type_name: String, ) -> TrackingResult<()>

Associate a variable name and type with an allocation.

Source

pub fn get_stats(&self) -> TrackingResult<MemoryStats>

Get current memory usage statistics with advanced analysis.

Source

pub fn get_active_allocations(&self) -> TrackingResult<Vec<AllocationInfo>>

Get all currently active allocations.

Source

pub fn get_allocation_history(&self) -> TrackingResult<Vec<AllocationInfo>>

Get the complete allocation history.

Source

pub fn get_memory_by_type(&self) -> TrackingResult<Vec<TypeMemoryUsage>>

Get memory usage grouped by type with smart inference.

Source

pub fn export_interactive_dashboard<P: AsRef<Path>>( &self, path: P, ) -> TrackingResult<()>

Export interactive HTML dashboard with embedded SVG charts

Source

pub fn export_memory_analysis<P: AsRef<Path>>( &self, path: P, ) -> TrackingResult<()>

Export memory analysis visualization showing variable names, types, and usage patterns. This creates a comprehensive memory analysis with call stack analysis, timeline, and categorization. All output files are automatically placed in the MemoryAnalysis/ directory.

§Arguments
  • path - Output filename for the memory analysis SVG file (recommended: “program_name_memory_analysis.svg”)
Source

pub fn export_lifecycle_timeline<P: AsRef<Path>>( &self, path: P, ) -> TrackingResult<()>

Export interactive lifecycle timeline showing variable lifecycles and relationships. This creates an advanced timeline with variable birth, life, death, and cross-section interactivity. All output files are automatically placed in the MemoryAnalysis/ directory.

§Arguments
  • path - Output filename for the lifecycle timeline SVG file (recommended: “program_name_lifecycle.svg”)
Source

pub fn export_to_json<P: AsRef<Path>>(&self, path: P) -> TrackingResult<()>

Export memory tracking data to 4 separate JSON files.

This method exports data to 4 specialized files:

  • {name}_memory_analysis.json: Memory allocation patterns and statistics
  • {name}_lifetime.json: Variable lifetime and scope analysis
  • {name}_unsafe_ffi.json: Unsafe operations and FFI tracking
  • {name}_variable_relationships.json: Variable dependency graph and relationships
§Export Modes
tracker.export_to_json("output")?;
// OR explicitly
tracker.export_to_json_with_options("output", ExportOptions::default())?;
  • Performance: ~2-5 seconds for typical datasets
  • Data: Only user-tracked variables get full enrichment
  • Use case: Normal development, HTML rendering, production monitoring
§Complete Mode (Slow - Debug Only)
let options = ExportOptions::new().include_system_allocations(true);
tracker.export_to_json_with_options("output", options)?;
  • Performance: ~10-40 seconds (5-10x slower!)
  • Data: ALL allocations including system internals get full enrichment
  • Use case: Deep debugging, memory leak investigation, system analysis
  • ⚠️ Warning: Very slow, generates large files, may impact application performance
Source

pub fn export_to_json_with_options<P: AsRef<Path>>( &self, path: P, options: ExportOptions, ) -> TrackingResult<()>

Export memory tracking data with custom options.

§Examples
tracker.export_to_json_with_options("output", ExportOptions::default())?;
§Complete mode (slow - for debugging)
let options = ExportOptions::new()
    .include_system_allocations(true)
    .verbose_logging(true);
tracker.export_to_json_with_options("debug_output", options)?;
Source§

impl MemoryTracker

Source

pub fn generate_timeline_data( &self, allocation_history: &[AllocationInfo], _active_allocations: &[AllocationInfo], ) -> TimelineData

Generate timeline data with stack traces and hotspots

Source§

impl MemoryTracker

Main export interface - unified entry point for all JSON export operations

Source

pub fn export_to_json_fast<P: AsRef<Path>>(&self, path: P) -> TrackingResult<()>

[CONVENIENCE] Quick export with performance optimization

This method provides a convenient way to export with performance-focused settings. Ideal for production environments where speed is more important than comprehensive analysis. Automatically enables fast export mode for large datasets (>5000 allocations).

§Arguments
  • path - Output base path for multiple optimized files
§Example
// Fast export for production monitoring
tracker.export_to_json_fast("prod_snapshot")?;
§Performance
  • Uses parallel shard processing for large datasets
  • Automatically switches to fast export coordinator when beneficial
  • Reduces export time by 60-80% for complex programs
Source

pub fn export_to_json_comprehensive<P: AsRef<Path>>( &self, path: P, ) -> TrackingResult<()>

[CONVENIENCE] Comprehensive export with all features enabled

This method provides maximum analysis depth with all security and FFI features enabled. Ideal for debugging, security audits, and comprehensive analysis.

§Arguments
  • path - Output base path for comprehensive analysis files
§Example
// Comprehensive export for security audit
tracker.export_to_json_comprehensive("security_audit")?;
Source

pub fn show_export_upgrade_path(&self)

[UTILITY] Display upgrade path information

This method shows users how to migrate from the old API to the new optimized API. Useful for understanding the available options and migration path.

Source

pub fn get_export_capabilities(&self) -> TrackingResult<Value>

[UTILITY] Get current export capabilities and status

Returns information about available export features and current system status.

Source

pub fn export_to_json_with_optimized_options<P: AsRef<Path>>( &self, base_path: P, options: OptimizedExportOptions, ) -> TrackingResult<()>

Unified export to JSON with custom options

This method provides full control over the export process with custom options. It integrates all the new data processing components including BatchProcessor, StreamingJsonWriter, SchemaValidator, and enhanced FFI analysis.

§Arguments
  • base_path - Base path for output
  • Custom export options
§Returns
  • TrackingResult<()> - Success or error result
§Example
let options = OptimizedExportOptions::with_optimization_level(OptimizationLevel::Maximum)
    .parallel_processing(true)
    .streaming_writer(true)
    .schema_validation(true);
tracker.export_to_json_with_options("output/analysis", options)?;
Source

pub fn test_export_backward_compatibility(&self) -> TrackingResult<Value>

Test backward compatibility with legacy export methods

This method verifies that the new optimized export system maintains full backward compatibility with existing export methods.

Source

pub fn get_adaptive_performance_report(&self) -> TrackingResult<Value>

Get adaptive performance report

Returns detailed performance metrics and optimization recommendations from the adaptive performance optimizer.

Source

pub fn reset_adaptive_optimizer(&self) -> TrackingResult<()>

Reset adaptive performance optimizer

Clears all cached data and performance metrics. Useful for testing or when starting fresh performance measurements.

Source

pub fn configure_adaptive_optimization( &self, enabled: bool, cache_size: Option<usize>, initial_batch_size: Option<usize>, ) -> TrackingResult<()>

Configure adaptive optimization settings

Allows runtime configuration of the adaptive performance optimizer.

Source

pub fn get_security_violation_report(&self) -> TrackingResult<Value>

Get comprehensive security violation report

Returns detailed security analysis including violation reports, impact assessments, and remediation suggestions.

Source

pub fn get_security_violations_by_severity( &self, min_severity: ViolationSeverity, ) -> TrackingResult<Vec<Value>>

Get security violations by severity level

Filters security violations by minimum severity level.

Source

pub fn verify_security_report_integrity(&self) -> TrackingResult<Value>

Verify integrity of security violation reports

Checks data integrity hashes for all security violation reports.

Source

pub fn clear_security_violations(&self) -> TrackingResult<()>

Clear all security violation reports

Clears all stored security violation data. Useful for testing or when starting fresh security analysis.

Source

pub fn configure_security_analysis( &self, enable_correlation: bool, include_low_severity: bool, generate_hashes: bool, max_related_allocations: Option<usize>, ) -> TrackingResult<()>

Configure security analysis settings

Allows runtime configuration of security violation analysis.

Source§

impl MemoryTracker

Ultra-fast export implementation (legacy methods for backward compatibility)

Source

pub fn export_optimized_json_files<P: AsRef<Path>>( &self, base_path: P, ) -> TrackingResult<()>

Optimized export to standard 4 JSON files (replaces export_separated_json_simple)

Source

pub fn export_optimized_json_files_with_complex_types<P: AsRef<Path>>( &self, base_path: P, ) -> TrackingResult<()>

Export to 5 JSON files including complex types analysis

Source

pub fn export_optimized_json_files_with_options<P: AsRef<Path>>( &self, base_path: P, options: OptimizedExportOptions, ) -> TrackingResult<()>

Optimized export to standard 4 JSON files with custom options

Source

pub fn export_extensible_json_files<P: AsRef<Path>>( &self, base_path: P, file_types: &[JsonFileType], ) -> TrackingResult<()>

A generic export method reserved for future expansion. can easily add a 5th and 6th JSON file

Source

pub fn export_extensible_json_files_with_options<P: AsRef<Path>>( &self, base_path: P, file_types: &[JsonFileType], options: OptimizedExportOptions, ) -> TrackingResult<()>

A generic export method reserved for future expansion. can easily add a 5th and 6th JSON file

Source§

impl MemoryTracker

Source

pub fn export_to_json_optimized<P: AsRef<Path>>( &self, path: P, ) -> TrackingResult<ComplexTypeExportResult>

Export tracking data with complex type optimization (separate files for better performance)

Trait Implementations§

Source§

impl Default for MemoryTracker

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Drop for MemoryTracker

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more