1use crate::core::types::AllocationInfo;
9use serde::{Deserialize, Serialize};
10use std::collections::HashMap;
11
12#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
14pub enum AdvancedTypeCategory {
15 InteriorMutability,
17 Synchronization,
19 Channel,
21 Atomic,
23 ThreadLocal,
25 MemoryManagement,
27 Async,
29}
30
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
33pub struct TypeBehaviorPattern {
34 pub has_interior_mutability: bool,
36 pub is_thread_safe: bool,
38 pub can_block: bool,
40 pub manages_memory_layout: bool,
42 pub deadlock_potential: bool,
44 pub has_runtime_borrow_check: bool,
46 pub has_runtime_overhead: bool,
48}
49
50#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
52pub struct AdvancedTypeInfo {
53 pub category: AdvancedTypeCategory,
55 pub behavior: TypeBehaviorPattern,
57 pub state_info: TypeStateInfo,
59 pub potential_issues: Vec<TypeIssue>,
61 pub performance_info: PerformanceInfo,
63}
64
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67pub struct TypeStateInfo {
68 pub is_borrowed: Option<bool>,
70 pub borrow_count: Option<usize>,
72 pub is_locked: Option<bool>,
74 pub lock_owner_thread: Option<String>,
76 pub wait_queue_length: Option<usize>,
78 pub channel_info: Option<ChannelStateInfo>,
80}
81
82#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
84pub struct ChannelStateInfo {
85 pub capacity: Option<usize>,
87 pub current_size: usize,
89 pub sender_count: usize,
91 pub receiver_count: usize,
93 pub is_closed: bool,
95}
96
97#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
99pub struct TypeIssue {
100 pub severity: IssueSeverity,
102 pub description: String,
104 pub suggestion: Option<String>,
106 pub location: Option<String>,
108}
109
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
112pub enum IssueSeverity {
113 Info,
115 Warning,
117 Error,
119 Critical,
121}
122
123#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
125pub struct PerformanceInfo {
126 pub overhead_factor: f64,
128 pub memory_overhead: usize,
130 pub is_lock_free: bool,
132 pub latency_category: LatencyCategory,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
138pub enum LatencyCategory {
139 Immediate,
141 Fast,
143 Moderate,
145 Slow,
147 VerySlow,
149}
150
151pub trait AdvancedTypeAnalyzer {
153 fn analyze_advanced_type(&self) -> AdvancedTypeInfo;
155
156 fn get_current_state(&self) -> TypeStateInfo;
158
159 fn check_issues(&self) -> Vec<TypeIssue>;
161
162 fn get_performance_info(&self) -> PerformanceInfo;
164}
165
166pub struct GenericAdvancedTypeAnalyzer;
168
169impl GenericAdvancedTypeAnalyzer {
170 pub fn analyze_by_type_name(type_name: &str, allocation: &AllocationInfo) -> AdvancedTypeInfo {
172 let category = Self::categorize_type(type_name);
173 let behavior = Self::analyze_behavior_pattern(type_name, &category);
174 let state_info = Self::extract_state_info(type_name, allocation);
175 let potential_issues = Self::check_potential_issues(type_name, &category, &behavior);
176 let performance_info = Self::analyze_performance(type_name, &category);
177
178 AdvancedTypeInfo {
179 category,
180 behavior,
181 state_info,
182 potential_issues,
183 performance_info,
184 }
185 }
186
187 fn categorize_type(type_name: &str) -> AdvancedTypeCategory {
189 if type_name.contains("Cell") || type_name.contains("UnsafeCell") {
190 AdvancedTypeCategory::InteriorMutability
191 } else if type_name.contains("Mutex")
192 || type_name.contains("RwLock")
193 || type_name.contains("Condvar")
194 || type_name.contains("Barrier")
195 {
196 AdvancedTypeCategory::Synchronization
197 } else if type_name.contains("Sender")
198 || type_name.contains("Receiver")
199 || type_name.contains("mpsc")
200 || type_name.contains("channel")
201 {
202 AdvancedTypeCategory::Channel
203 } else if type_name.contains("Atomic") {
204 AdvancedTypeCategory::Atomic
205 } else if type_name.contains("ThreadLocal") || type_name.contains("LocalKey") {
206 AdvancedTypeCategory::ThreadLocal
207 } else if type_name.contains("ManuallyDrop")
208 || type_name.contains("MaybeUninit")
209 || type_name.contains("Pin")
210 {
211 AdvancedTypeCategory::MemoryManagement
212 } else if type_name.contains("Future")
213 || type_name.contains("Waker")
214 || type_name.contains("Context")
215 || type_name.contains("async")
216 {
217 AdvancedTypeCategory::Async
218 } else {
219 AdvancedTypeCategory::MemoryManagement
221 }
222 }
223
224 fn analyze_behavior_pattern(
226 type_name: &str,
227 category: &AdvancedTypeCategory,
228 ) -> TypeBehaviorPattern {
229 match category {
230 AdvancedTypeCategory::InteriorMutability => TypeBehaviorPattern {
231 has_interior_mutability: true,
232 is_thread_safe: !type_name.contains("Cell"), can_block: false,
234 manages_memory_layout: false,
235 deadlock_potential: false,
236 has_runtime_borrow_check: type_name.contains("RefCell"),
237 has_runtime_overhead: type_name.contains("RefCell"),
238 },
239 AdvancedTypeCategory::Synchronization => TypeBehaviorPattern {
240 has_interior_mutability: true,
241 is_thread_safe: true,
242 can_block: true,
243 manages_memory_layout: false,
244 deadlock_potential: true,
245 has_runtime_borrow_check: false,
246 has_runtime_overhead: true,
247 },
248 AdvancedTypeCategory::Channel => TypeBehaviorPattern {
249 has_interior_mutability: true,
250 is_thread_safe: true,
251 can_block: true,
252 manages_memory_layout: true,
253 deadlock_potential: false,
254 has_runtime_borrow_check: false,
255 has_runtime_overhead: true,
256 },
257 AdvancedTypeCategory::Atomic => TypeBehaviorPattern {
258 has_interior_mutability: true,
259 is_thread_safe: true,
260 can_block: false,
261 manages_memory_layout: false,
262 deadlock_potential: false,
263 has_runtime_borrow_check: false,
264 has_runtime_overhead: false,
265 },
266 AdvancedTypeCategory::ThreadLocal => TypeBehaviorPattern {
267 has_interior_mutability: true,
268 is_thread_safe: false, can_block: false,
270 manages_memory_layout: true,
271 deadlock_potential: false,
272 has_runtime_borrow_check: false,
273 has_runtime_overhead: true,
274 },
275 AdvancedTypeCategory::MemoryManagement => TypeBehaviorPattern {
276 has_interior_mutability: false,
277 is_thread_safe: true, can_block: false,
279 manages_memory_layout: true,
280 deadlock_potential: false,
281 has_runtime_borrow_check: false,
282 has_runtime_overhead: false,
283 },
284 AdvancedTypeCategory::Async => TypeBehaviorPattern {
285 has_interior_mutability: true,
286 is_thread_safe: true,
287 can_block: true, manages_memory_layout: true,
289 deadlock_potential: false,
290 has_runtime_borrow_check: false,
291 has_runtime_overhead: true,
292 },
293 }
294 }
295
296 fn extract_state_info(_type_name: &str, _allocation: &AllocationInfo) -> TypeStateInfo {
298 TypeStateInfo {
301 is_borrowed: None,
302 borrow_count: None,
303 is_locked: None,
304 lock_owner_thread: None,
305 wait_queue_length: None,
306 channel_info: None,
307 }
308 }
309
310 fn check_potential_issues(
312 type_name: &str,
313 category: &AdvancedTypeCategory,
314 behavior: &TypeBehaviorPattern,
315 ) -> Vec<TypeIssue> {
316 let mut issues = Vec::new();
317
318 match category {
320 AdvancedTypeCategory::InteriorMutability => {
321 if type_name.contains("RefCell") {
322 issues.push(TypeIssue {
323 severity: IssueSeverity::Warning,
324 description: "RefCell has runtime borrow checking overhead".to_string(),
325 suggestion: Some("Consider using Cell for Copy types or redesign to avoid interior mutability".to_string()),
326 location: None,
327 });
328 }
329 }
330 AdvancedTypeCategory::Synchronization => {
331 if behavior.deadlock_potential {
332 issues.push(TypeIssue {
333 severity: IssueSeverity::Warning,
334 description: "Synchronization primitive has deadlock potential".to_string(),
335 suggestion: Some(
336 "Ensure consistent lock ordering and consider using try_lock()"
337 .to_string(),
338 ),
339 location: None,
340 });
341 }
342 }
343 AdvancedTypeCategory::Channel => {
344 issues.push(TypeIssue {
345 severity: IssueSeverity::Info,
346 description: "Channel operations can block indefinitely".to_string(),
347 suggestion: Some("Consider using try_send/try_recv or timeouts".to_string()),
348 location: None,
349 });
350 }
351 _ => {}
352 }
353
354 issues
355 }
356
357 fn analyze_performance(type_name: &str, category: &AdvancedTypeCategory) -> PerformanceInfo {
359 match category {
360 AdvancedTypeCategory::InteriorMutability => {
361 if type_name.contains("Cell") {
362 PerformanceInfo {
363 overhead_factor: 1.0, memory_overhead: 0,
365 is_lock_free: true,
366 latency_category: LatencyCategory::Immediate,
367 }
368 } else {
369 PerformanceInfo {
370 overhead_factor: 2.0, memory_overhead: std::mem::size_of::<usize>(), is_lock_free: true,
373 latency_category: LatencyCategory::Fast,
374 }
375 }
376 }
377 AdvancedTypeCategory::Synchronization => PerformanceInfo {
378 overhead_factor: 10.0, memory_overhead: std::mem::size_of::<usize>() * 2, is_lock_free: false,
381 latency_category: LatencyCategory::Moderate,
382 },
383 AdvancedTypeCategory::Channel => PerformanceInfo {
384 overhead_factor: 5.0, memory_overhead: 64, is_lock_free: false,
387 latency_category: LatencyCategory::Moderate,
388 },
389 AdvancedTypeCategory::Atomic => PerformanceInfo {
390 overhead_factor: 1.5, memory_overhead: 0,
392 is_lock_free: true,
393 latency_category: LatencyCategory::Immediate,
394 },
395 AdvancedTypeCategory::ThreadLocal => PerformanceInfo {
396 overhead_factor: 3.0, memory_overhead: std::mem::size_of::<usize>(), is_lock_free: true,
399 latency_category: LatencyCategory::Fast,
400 },
401 AdvancedTypeCategory::MemoryManagement => PerformanceInfo {
402 overhead_factor: 1.0, memory_overhead: 0,
404 is_lock_free: true,
405 latency_category: LatencyCategory::Immediate,
406 },
407 AdvancedTypeCategory::Async => PerformanceInfo {
408 overhead_factor: 4.0, memory_overhead: 32, is_lock_free: true,
411 latency_category: LatencyCategory::Fast,
412 },
413 }
414 }
415}
416
417#[derive(Debug, Clone, Serialize, Deserialize)]
419pub struct AdvancedTypeAnalysisReport {
420 pub by_category: HashMap<String, Vec<AdvancedTypeInfo>>,
422 pub all_issues: Vec<TypeIssue>,
424 pub performance_summary: PerformanceSummary,
426 pub statistics: AdvancedTypeStatistics,
428}
429
430#[derive(Debug, Clone, Serialize, Deserialize)]
432pub struct PerformanceSummary {
433 pub total_overhead_factor: f64,
435 pub total_memory_overhead: usize,
437 pub lock_free_percentage: f64,
439 pub dominant_latency_category: LatencyCategory,
441}
442
443#[derive(Debug, Clone, Serialize, Deserialize)]
445pub struct AdvancedTypeStatistics {
446 pub by_category: HashMap<String, usize>,
448 pub by_issue_severity: HashMap<String, usize>,
450 pub by_latency_category: HashMap<String, usize>,
452 pub total_advanced_types: usize,
454}
455
456pub fn analyze_advanced_types(allocations: &[AllocationInfo]) -> AdvancedTypeAnalysisReport {
458 let mut by_category: HashMap<String, Vec<AdvancedTypeInfo>> = HashMap::new();
459 let mut all_issues = Vec::new();
460 let mut total_overhead_factor = 0.0;
461 let mut total_memory_overhead = 0;
462 let mut lock_free_count = 0;
463 let mut total_count = 0;
464 let mut latency_counts: HashMap<LatencyCategory, usize> = HashMap::new();
465
466 for allocation in allocations {
467 if let Some(type_name) = &allocation.type_name {
468 if is_advanced_type(type_name) {
470 let analysis =
471 GenericAdvancedTypeAnalyzer::analyze_by_type_name(type_name, allocation);
472
473 let category_key = format!("{:?}", analysis.category);
475 let issues = analysis.potential_issues.clone();
476 let overhead_factor = analysis.performance_info.overhead_factor;
477 let memory_overhead = analysis.performance_info.memory_overhead;
478 let is_lock_free = analysis.performance_info.is_lock_free;
479 let latency_category = analysis.performance_info.latency_category.clone();
480
481 by_category
483 .entry(category_key)
484 .or_insert_with(Vec::new)
485 .push(analysis);
486
487 all_issues.extend(issues);
489
490 total_overhead_factor += overhead_factor;
492 total_memory_overhead += memory_overhead;
493 if is_lock_free {
494 lock_free_count += 1;
495 }
496 *latency_counts.entry(latency_category).or_insert(0) += 1;
497 total_count += 1;
498 }
499 }
500 }
501
502 let performance_summary = if total_count > 0 {
504 PerformanceSummary {
505 total_overhead_factor: total_overhead_factor / total_count as f64,
506 total_memory_overhead,
507 lock_free_percentage: (lock_free_count as f64 / total_count as f64) * 100.0,
508 dominant_latency_category: latency_counts
509 .iter()
510 .max_by_key(|(_, count)| *count)
511 .map(|(category, _)| category.clone())
512 .unwrap_or(LatencyCategory::Fast),
513 }
514 } else {
515 PerformanceSummary {
516 total_overhead_factor: 1.0,
517 total_memory_overhead: 0,
518 lock_free_percentage: 100.0,
519 dominant_latency_category: LatencyCategory::Immediate,
520 }
521 };
522
523 let statistics =
525 generate_advanced_type_statistics(&by_category, &all_issues, &latency_counts, total_count);
526
527 AdvancedTypeAnalysisReport {
528 by_category,
529 all_issues,
530 performance_summary,
531 statistics,
532 }
533}
534
535pub fn is_advanced_type(type_name: &str) -> bool {
537 type_name.contains("Cell")
538 || type_name.contains("Mutex")
539 || type_name.contains("RwLock")
540 || type_name.contains("Atomic")
541 || type_name.contains("Sender")
542 || type_name.contains("Receiver")
543 || type_name.contains("ThreadLocal")
544 || type_name.contains("ManuallyDrop")
545 || type_name.contains("MaybeUninit")
546 || type_name.contains("Pin")
547 || type_name.contains("Future")
548 || type_name.contains("Waker")
549 || type_name.contains("Condvar")
550 || type_name.contains("Barrier")
551 || type_name.contains("Arc<")
552 || type_name.contains("Rc<")
553 || type_name.contains("Weak<")
554 || type_name.contains("Box<dyn")
555 || type_name.contains("Cow<")
556 || type_name.contains("HashMap<")
557 || type_name.contains("BTreeMap<")
558 || type_name.contains("PhantomData<")
559}
560
561pub fn get_type_category(type_name: &str) -> Option<AdvancedTypeCategory> {
563 if type_name.contains("Cell<")
564 || type_name.contains("RefCell<")
565 || type_name.contains("UnsafeCell<")
566 {
567 Some(AdvancedTypeCategory::InteriorMutability)
568 } else if type_name.contains("Mutex<")
569 || type_name.contains("RwLock<")
570 || type_name.contains("Condvar")
571 {
572 Some(AdvancedTypeCategory::Synchronization)
573 } else if type_name.contains("mpsc::")
574 || type_name.contains("Sender<")
575 || type_name.contains("Receiver<")
576 {
577 Some(AdvancedTypeCategory::Channel)
578 } else if type_name.contains("Atomic") {
579 Some(AdvancedTypeCategory::Atomic)
580 } else if type_name.contains("ThreadLocal<") || type_name.contains("LocalKey<") {
581 Some(AdvancedTypeCategory::ThreadLocal)
582 } else if type_name.contains("ManuallyDrop<")
583 || type_name.contains("MaybeUninit<")
584 || type_name.contains("Pin<")
585 {
586 Some(AdvancedTypeCategory::MemoryManagement)
587 } else if type_name.contains("Future")
588 || type_name.contains("Stream")
589 || type_name.contains("Waker")
590 || type_name.contains("Context")
591 {
592 Some(AdvancedTypeCategory::Async)
593 } else {
594 None
595 }
596}
597
598pub fn create_behavior_pattern(type_name: &str) -> TypeBehaviorPattern {
600 let category = get_type_category(type_name);
601
602 match category {
603 Some(AdvancedTypeCategory::InteriorMutability) => TypeBehaviorPattern {
604 has_interior_mutability: true,
605 is_thread_safe: !type_name.contains("Cell<"), can_block: false,
607 manages_memory_layout: false,
608 deadlock_potential: false,
609 has_runtime_borrow_check: type_name.contains("RefCell<"),
610 has_runtime_overhead: type_name.contains("RefCell<"),
611 },
612 Some(AdvancedTypeCategory::Synchronization) => TypeBehaviorPattern {
613 has_interior_mutability: true,
614 is_thread_safe: true,
615 can_block: true,
616 manages_memory_layout: false,
617 deadlock_potential: true,
618 has_runtime_borrow_check: false,
619 has_runtime_overhead: true,
620 },
621 Some(AdvancedTypeCategory::Channel) => TypeBehaviorPattern {
622 has_interior_mutability: false,
623 is_thread_safe: true,
624 can_block: true,
625 manages_memory_layout: true,
626 deadlock_potential: false,
627 has_runtime_borrow_check: false,
628 has_runtime_overhead: true,
629 },
630 Some(AdvancedTypeCategory::Atomic) => TypeBehaviorPattern {
631 has_interior_mutability: true,
632 is_thread_safe: true,
633 can_block: false,
634 manages_memory_layout: false,
635 deadlock_potential: false,
636 has_runtime_borrow_check: false,
637 has_runtime_overhead: false,
638 },
639 Some(AdvancedTypeCategory::ThreadLocal) => TypeBehaviorPattern {
640 has_interior_mutability: true,
641 is_thread_safe: false,
642 can_block: false,
643 manages_memory_layout: true,
644 deadlock_potential: false,
645 has_runtime_borrow_check: false,
646 has_runtime_overhead: true,
647 },
648 Some(AdvancedTypeCategory::MemoryManagement) => TypeBehaviorPattern {
649 has_interior_mutability: type_name.contains("Pin<"),
650 is_thread_safe: false,
651 can_block: false,
652 manages_memory_layout: true,
653 deadlock_potential: false,
654 has_runtime_borrow_check: false,
655 has_runtime_overhead: false,
656 },
657 Some(AdvancedTypeCategory::Async) => TypeBehaviorPattern {
658 has_interior_mutability: false,
659 is_thread_safe: false,
660 can_block: false,
661 manages_memory_layout: true,
662 deadlock_potential: false,
663 has_runtime_borrow_check: false,
664 has_runtime_overhead: true,
665 },
666 None => TypeBehaviorPattern {
667 has_interior_mutability: false,
668 is_thread_safe: false,
669 can_block: false,
670 manages_memory_layout: false,
671 deadlock_potential: false,
672 has_runtime_borrow_check: false,
673 has_runtime_overhead: false,
674 },
675 }
676}
677
678pub fn analyze_type(allocation: &AllocationInfo) -> Option<AdvancedTypeInfo> {
680 let type_name = allocation.type_name.as_ref()?;
681
682 if !is_advanced_type(type_name) {
683 return None;
684 }
685
686 let category = get_type_category(type_name)?;
687 let behavior = create_behavior_pattern(type_name);
688
689 let mut issues = Vec::new();
690 let _recommendations: Vec<String> = Vec::new();
691
692 if behavior.deadlock_potential {
694 issues.push(TypeIssue {
695 severity: IssueSeverity::Warning,
696 description: "Type has deadlock potential - ensure proper lock ordering".to_string(),
697 location: Some(format!("ptr: 0x{:x}", allocation.ptr)),
698 suggestion: Some(
699 "Consider using timeout-based locking or lock hierarchies".to_string(),
700 ),
701 });
702 }
703
704 if behavior.has_runtime_overhead && allocation.size > 1024 {
705 issues.push(TypeIssue {
706 severity: IssueSeverity::Warning,
707 description: "Large allocation with runtime overhead".to_string(),
708 location: Some(format!(
709 "ptr: 0x{:x}, size: {}",
710 allocation.ptr, allocation.size
711 )),
712 suggestion: Some(
713 "Consider using more efficient alternatives for large data".to_string(),
714 ),
715 });
716 }
717
718 Some(AdvancedTypeInfo {
719 category,
720 behavior: behavior.clone(),
721 state_info: TypeStateInfo {
722 is_borrowed: None,
723 borrow_count: Some(allocation.borrow_count),
724 is_locked: None,
725 lock_owner_thread: None,
726 wait_queue_length: None,
727 channel_info: None,
728 },
729 potential_issues: issues,
730 performance_info: PerformanceInfo {
731 overhead_factor: if behavior.has_runtime_overhead {
732 2.0
733 } else {
734 1.0
735 },
736 memory_overhead: calculate_overhead(type_name),
737 is_lock_free: !behavior.can_block,
738 latency_category: if behavior.can_block {
739 LatencyCategory::Moderate
740 } else {
741 LatencyCategory::Fast
742 },
743 },
744 })
745}
746
747fn calculate_overhead(type_name: &str) -> usize {
749 if type_name.contains("RefCell<") {
750 std::mem::size_of::<isize>() } else if type_name.contains("Mutex<") {
752 64 } else if type_name.contains("RwLock<") {
754 96 } else if type_name.contains("Arc<") || type_name.contains("Rc<") {
756 std::mem::size_of::<usize>() * 2 } else {
758 0
759 }
760}
761
762#[allow(dead_code)]
764fn calculate_alignment(type_name: &str) -> usize {
765 if type_name.contains("Atomic") {
766 8 } else if type_name.contains("Mutex<") || type_name.contains("RwLock<") {
768 std::mem::align_of::<std::sync::Mutex<()>>()
769 } else {
770 std::mem::align_of::<usize>()
771 }
772}
773
774fn generate_advanced_type_statistics(
776 by_category: &HashMap<String, Vec<AdvancedTypeInfo>>,
777 all_issues: &[TypeIssue],
778 latency_counts: &HashMap<LatencyCategory, usize>,
779 total_count: usize,
780) -> AdvancedTypeStatistics {
781 let mut by_category_stats = HashMap::new();
782 for (category, types) in by_category {
783 by_category_stats.insert(category.clone(), types.len());
784 }
785
786 let mut by_issue_severity = HashMap::new();
787 for issue in all_issues {
788 let severity_key = format!("{:?}", issue.severity);
789 *by_issue_severity.entry(severity_key).or_insert(0) += 1;
790 }
791
792 let mut by_latency_category = HashMap::new();
793 for (category, count) in latency_counts {
794 by_latency_category.insert(format!("{:?}", category), *count);
795 }
796
797 AdvancedTypeStatistics {
798 by_category: by_category_stats,
799 by_issue_severity,
800 by_latency_category,
801 total_advanced_types: total_count,
802 }
803}
804
805pub fn detect_interior_mutability_patterns(
809 allocations: &[AllocationInfo],
810) -> InteriorMutabilityReport {
811 let mut cell_instances = Vec::new();
812 let mut refcell_instances = Vec::new();
813 let mut unsafe_cell_instances = Vec::new();
814 let mut runtime_borrow_violations = Vec::new();
815
816 for allocation in allocations {
817 if let Some(type_name) = &allocation.type_name {
818 if type_name.contains("Cell<") {
819 cell_instances.push(CellInstance {
820 ptr: allocation.ptr,
821 type_name: type_name.clone(),
822 size: allocation.size,
823 thread_safe: true, zero_cost: true, });
826 } else if type_name.contains("RefCell<") {
827 let instance = RefCellInstance {
828 ptr: allocation.ptr,
829 type_name: type_name.clone(),
830 size: allocation.size,
831 current_borrow_count: allocation.borrow_count,
832 has_active_mut_borrow: allocation.borrow_count > 0,
833 runtime_check_overhead: true,
834 };
835
836 if allocation.borrow_count > 1 {
838 runtime_borrow_violations.push(BorrowViolation {
839 ptr: allocation.ptr,
840 violation_type: BorrowViolationType::MultipleBorrows,
841 borrow_count: allocation.borrow_count,
842 timestamp: allocation.timestamp_alloc,
843 });
844 }
845
846 refcell_instances.push(instance);
847 } else if type_name.contains("UnsafeCell<") {
848 unsafe_cell_instances.push(UnsafeCellInstance {
849 ptr: allocation.ptr,
850 type_name: type_name.clone(),
851 size: allocation.size,
852 requires_unsafe_access: true,
853 });
854 }
855 }
856 }
857
858 let total_types = cell_instances.len() + refcell_instances.len() + unsafe_cell_instances.len();
859
860 InteriorMutabilityReport {
861 cell_instances,
862 refcell_instances,
863 unsafe_cell_instances,
864 runtime_borrow_violations,
865 total_interior_mutability_types: total_types,
866 analysis_timestamp: current_timestamp(),
867 }
868}
869
870pub fn monitor_concurrency_primitives(
872 allocations: &[AllocationInfo],
873) -> ConcurrencyPrimitiveReport {
874 let mut mutex_instances = Vec::new();
875 let mut rwlock_instances = Vec::new();
876 let mut condvar_instances = Vec::new();
877 let lock_contentions = Vec::new();
878
879 for allocation in allocations {
880 if let Some(type_name) = &allocation.type_name {
881 if type_name.contains("Mutex<") {
882 mutex_instances.push(MutexInstance {
883 ptr: allocation.ptr,
884 type_name: type_name.clone(),
885 size: allocation.size,
886 is_locked: false, lock_owner_thread: None,
888 waiting_threads: 0,
889 total_lock_acquisitions: 0,
890 total_wait_time_ns: 0,
891 });
892 } else if type_name.contains("RwLock<") {
893 rwlock_instances.push(RwLockInstance {
894 ptr: allocation.ptr,
895 type_name: type_name.clone(),
896 size: allocation.size,
897 read_count: 0,
898 has_write_lock: false,
899 waiting_readers: 0,
900 waiting_writers: 0,
901 total_read_acquisitions: 0,
902 total_write_acquisitions: 0,
903 });
904 } else if type_name.contains("Condvar") {
905 condvar_instances.push(CondvarInstance {
906 ptr: allocation.ptr,
907 type_name: type_name.clone(),
908 size: allocation.size,
909 waiting_threads: 0,
910 total_notifications: 0,
911 });
912 }
913 }
914 }
915
916 let deadlock_score =
917 calculate_deadlock_potential_by_count(mutex_instances.len(), rwlock_instances.len());
918
919 ConcurrencyPrimitiveReport {
920 mutex_instances,
921 rwlock_instances,
922 condvar_instances,
923 lock_contentions,
924 deadlock_potential_score: deadlock_score,
925 analysis_timestamp: current_timestamp(),
926 }
927}
928
929fn current_timestamp() -> u64 {
933 std::time::SystemTime::now()
934 .duration_since(std::time::UNIX_EPOCH)
935 .unwrap_or_default()
936 .as_nanos() as u64
937}
938
939fn calculate_deadlock_potential_by_count(mutex_count: usize, rwlock_count: usize) -> f64 {
941 let total_locks = mutex_count + rwlock_count;
942 if total_locks <= 1 {
943 return 0.0;
944 }
945
946 (total_locks as f64).log2() / 10.0
949}
950
951#[derive(Debug, Clone, Serialize, Deserialize)]
955pub struct InteriorMutabilityReport {
956 pub cell_instances: Vec<CellInstance>,
958 pub refcell_instances: Vec<RefCellInstance>,
960 pub unsafe_cell_instances: Vec<UnsafeCellInstance>,
962 pub runtime_borrow_violations: Vec<BorrowViolation>,
964 pub total_interior_mutability_types: usize,
966 pub analysis_timestamp: u64,
968}
969
970#[derive(Debug, Clone, Serialize, Deserialize)]
972pub struct CellInstance {
973 pub ptr: usize,
975 pub type_name: String,
977 pub size: usize,
979 pub thread_safe: bool,
981 pub zero_cost: bool,
983}
984
985#[derive(Debug, Clone, Serialize, Deserialize)]
987pub struct RefCellInstance {
988 pub ptr: usize,
990 pub type_name: String,
992 pub size: usize,
994 pub current_borrow_count: usize,
996 pub has_active_mut_borrow: bool,
998 pub runtime_check_overhead: bool,
1000}
1001
1002#[derive(Debug, Clone, Serialize, Deserialize)]
1004pub struct UnsafeCellInstance {
1005 pub ptr: usize,
1007 pub type_name: String,
1009 pub size: usize,
1011 pub requires_unsafe_access: bool,
1013}
1014
1015#[derive(Debug, Clone, Serialize, Deserialize)]
1017pub struct BorrowViolation {
1018 pub ptr: usize,
1020 pub violation_type: BorrowViolationType,
1022 pub borrow_count: usize,
1024 pub timestamp: u64,
1026}
1027
1028#[derive(Debug, Clone, Serialize, Deserialize)]
1030pub enum BorrowViolationType {
1031 MultipleBorrows,
1033 MutableBorrowConflict,
1035 BorrowAfterMove,
1037}
1038
1039#[derive(Debug, Clone, Serialize, Deserialize)]
1041pub struct ConcurrencyPrimitiveReport {
1042 pub mutex_instances: Vec<MutexInstance>,
1044 pub rwlock_instances: Vec<RwLockInstance>,
1046 pub condvar_instances: Vec<CondvarInstance>,
1048 pub lock_contentions: Vec<LockContention>,
1050 pub deadlock_potential_score: f64,
1052 pub analysis_timestamp: u64,
1054}
1055
1056#[derive(Debug, Clone, Serialize, Deserialize)]
1058pub struct MutexInstance {
1059 pub ptr: usize,
1061 pub type_name: String,
1063 pub size: usize,
1065 pub is_locked: bool,
1067 pub lock_owner_thread: Option<String>,
1069 pub waiting_threads: usize,
1071 pub total_lock_acquisitions: u64,
1073 pub total_wait_time_ns: u64,
1075}
1076
1077#[derive(Debug, Clone, Serialize, Deserialize)]
1079pub struct RwLockInstance {
1080 pub ptr: usize,
1082 pub type_name: String,
1084 pub size: usize,
1086 pub read_count: usize,
1088 pub has_write_lock: bool,
1090 pub waiting_readers: usize,
1092 pub waiting_writers: usize,
1094 pub total_read_acquisitions: u64,
1096 pub total_write_acquisitions: u64,
1098}
1099
1100#[derive(Debug, Clone, Serialize, Deserialize)]
1102pub struct CondvarInstance {
1103 pub ptr: usize,
1105 pub type_name: String,
1107 pub size: usize,
1109 pub waiting_threads: usize,
1111 pub total_notifications: u64,
1113}
1114
1115#[derive(Debug, Clone, Serialize, Deserialize)]
1117pub struct LockContention {
1118 pub lock_ptr: usize,
1120 pub contention_type: ContentionType,
1122 pub waiting_time_ns: u64,
1124 pub thread_id: String,
1126 pub timestamp: u64,
1128}
1129
1130#[derive(Debug, Clone, Serialize, Deserialize)]
1132pub enum ContentionType {
1133 MutexContention,
1135 RwLockReadContention,
1137 RwLockWriteContention,
1139}