1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
//! LeakSanitizer (LSan) — detects memory leaks at runtime.
//! Clean-room behavioral reconstruction.
//!
//! @llvm_behavior: LeakSanitizer instruments allocation and deallocation
//! sites in the program to track heap allocations. At program exit (or
//! at user-requested checkpoints), it scans memory for reachable
//! pointers and reports any heap blocks that are no longer reachable.
//!
//! Instrumentation strategy:
//! - malloc/calloc/realloc/new → record allocation info
//! - free/delete → mark as freed
//! - Stack/global roots → record as root regions
//! - Exit handler → perform reachability scan
//!
//! The pass inserts calls to the LSan runtime library at:
//! 1. Allocation sites: __lsan_register_allocation(ptr, size, site_id)
//! 2. Deallocation sites: __lsan_unregister_allocation(ptr)
//! 3. Root regions: __lsan_register_root_region(start, end)
//! 4. Check points: __lsan_do_leak_check()
//! 5. Global destructor: __lsan_do_recoverable_leak_check()
//!
//! Leak detection algorithm (at runtime):
//! 1. Stop the world
//! 2. Scan stack, globals, and registered roots for pointer-aligned values
//! 3. Any heap block with no incoming pointer is "leaked"
//! 4. Report leaks with allocation site info
use llvm_native_core::module::Module;
use llvm_native_core::opcode::Opcode;
use llvm_native_core::types::Type;
use llvm_native_core::value::{valref, Value, ValueRef};
use llvm_native_core::SubclassKind;
use std::collections::{HashMap, HashSet};
// ============================================================================
// LeakInfo — Describes a detected leak
// ============================================================================
/// Information about a detected memory leak.
#[derive(Debug, Clone)]
pub struct LeakInfo {
/// Address of the leaked allocation.
pub address: u64,
/// Size of the leaked allocation in bytes.
pub size: u64,
/// Source location where the allocation occurred.
pub allocation_site: SourceLoc,
}
/// Source location for leak reporting.
#[derive(Debug, Clone, Default)]
pub struct SourceLoc {
/// Source filename.
pub filename: String,
/// 1-based line number.
pub line: u32,
/// 1-based column number.
pub column: u32,
/// 0-based byte offset.
pub offset: usize,
}
// ============================================================================
// Allocation Record
// ============================================================================
/// Internal record of an instrumented allocation.
#[derive(Debug, Clone)]
struct AllocRecord {
/// The allocation instruction (call to malloc etc).
call_site: ValueRef,
/// Size operand index in the call.
size_operand: usize,
/// Source location if known.
loc: SourceLoc,
}
// ============================================================================
// Root Region
// ============================================================================
/// A registered root region (memory range to scan for pointers).
#[derive(Debug, Clone)]
struct RootRegion {
/// Start of the region.
start: ValueRef,
/// End of the region.
end: ValueRef,
/// Whether this is a stack region.
is_stack: bool,
}
// ============================================================================
// LeakSanitizer Pass
// ============================================================================
/// LeakSanitizer pass — instruments for leak detection.
#[derive(Debug, Clone)]
pub struct LeakSanitizer {
/// Option value for LSAN_OPTIONS=report_objects=1
pub report_objects: bool,
/// Whether to run leak check at exit.
pub leak_check_at_exit: bool,
/// Maximum number of leaks to report.
pub max_leaks: usize,
/// Whether to use fast (conservative) or precise scanning.
pub use_fast_unwinder: bool,
/// Suppressions file path.
pub suppressions: Vec<String>,
/// Number of allocation sites instrumented.
pub allocs_instrumented: usize,
/// Number of deallocation sites instrumented.
pub deallocs_instrumented: usize,
/// Number of root regions registered.
pub roots_registered: usize,
/// Leak check functions inserted.
pub checks_inserted: usize,
/// Internal allocation records.
allocations: Vec<AllocRecord>,
/// Internal root regions.
root_regions: Vec<RootRegion>,
/// Known allocation function names.
alloc_functions: HashMap<String, bool>,
/// Known deallocation function names.
dealloc_functions: HashMap<String, bool>,
}
impl LeakSanitizer {
/// Create a new LeakSanitizer with default settings.
pub fn new() -> Self {
let mut alloc_fns = HashMap::new();
alloc_fns.insert("malloc".to_string(), true);
alloc_fns.insert("calloc".to_string(), true);
alloc_fns.insert("realloc".to_string(), true);
alloc_fns.insert("memalign".to_string(), true);
alloc_fns.insert("aligned_alloc".to_string(), true);
alloc_fns.insert("posix_memalign".to_string(), true);
alloc_fns.insert("valloc".to_string(), true);
alloc_fns.insert("pvalloc".to_string(), true);
alloc_fns.insert("_Znwm".to_string(), true); // operator new
alloc_fns.insert("_Znam".to_string(), true); // operator new[]
alloc_fns.insert("strdup".to_string(), true);
alloc_fns.insert("strndup".to_string(), true);
alloc_fns.insert("asprintf".to_string(), true);
let mut dealloc_fns = HashMap::new();
dealloc_fns.insert("free".to_string(), true);
dealloc_fns.insert("realloc".to_string(), true); // realloc can free
dealloc_fns.insert("_ZdlPv".to_string(), true); // operator delete
dealloc_fns.insert("_ZdaPv".to_string(), true); // operator delete[]
Self {
report_objects: true,
leak_check_at_exit: true,
max_leaks: 1024,
use_fast_unwinder: true,
suppressions: Vec::new(),
allocs_instrumented: 0,
deallocs_instrumented: 0,
roots_registered: 0,
checks_inserted: 0,
allocations: Vec::new(),
root_regions: Vec::new(),
alloc_functions: alloc_fns,
dealloc_functions: dealloc_fns,
}
}
/// Run LeakSanitizer instrumentation on a module.
///
/// Returns the total number of instrumentation points inserted.
pub fn run_on_module(&mut self, module: &mut Module) -> usize {
self.allocations.clear();
self.root_regions.clear();
self.allocs_instrumented = 0;
self.deallocs_instrumented = 0;
self.roots_registered = 0;
self.checks_inserted = 0;
// Walk all functions and instrument
let functions = module.functions.clone();
for func in &functions {
self.instrument_function(func);
}
// Add global root regions (data, bss)
for global in &module.globals {
let g = global.borrow();
if g.ty.size_bytes() > 0 {
self.register_root_region(global, global);
self.roots_registered += 1;
}
}
// Add leak check at exit if enabled
if self.leak_check_at_exit {
self.instrument_exit_handler(module);
}
self.allocs_instrumented
+ self.deallocs_instrumented
+ self.roots_registered
+ self.checks_inserted
}
// ========================================================================
// Function instrumentation
// ========================================================================
/// Instrument a function's allocation and deallocation calls.
fn instrument_function(&mut self, func: &ValueRef) {
let f = func.borrow();
let blocks: Vec<ValueRef> = f
.operands
.iter()
.filter(|op| op.borrow().is_basic_block())
.cloned()
.collect();
for bb in &blocks {
let block = bb.borrow();
let insts: Vec<ValueRef> = block
.operands
.iter()
.filter(|op| op.borrow().is_instruction())
.cloned()
.collect();
for inst in &insts {
let opcode = inst.borrow().get_opcode();
if opcode == Some(Opcode::Call) {
self.handle_call(inst, func);
}
}
}
}
/// Handle a call instruction: check if it's an alloc or dealloc.
fn handle_call(&mut self, inst: &ValueRef, _func: &ValueRef) {
let i = inst.borrow();
if i.operands.is_empty() {
return;
}
let callee = &i.operands[0];
let callee_name = callee.borrow().name.clone();
if self.is_alloc_function(&callee_name) {
self.instrument_allocation(inst);
} else if self.is_dealloc_function(&callee_name) {
self.instrument_deallocation(inst);
}
}
/// Instrument an allocation call.
fn instrument_allocation(&mut self, alloc: &ValueRef) {
let a = alloc.borrow();
let mut size_operand = 1; // Default: first arg after callee
// Try to identify the size argument
let callee_name = if !a.operands.is_empty() {
a.operands[0].borrow().name.clone()
} else {
String::new()
};
// calloc(num, size) — size is operand 2
if callee_name == "calloc" {
size_operand = 2;
}
let loc = SourceLoc {
filename: "unknown".to_string(),
line: 0,
column: 0,
offset: 0,
};
self.allocations.push(AllocRecord {
call_site: alloc.clone(),
size_operand,
loc,
});
self.allocs_instrumented += 1;
}
/// Instrument a deallocation call.
fn instrument_deallocation(&mut self, dealloc: &ValueRef) {
let _ = dealloc;
self.deallocs_instrumented += 1;
}
/// Register a root region for the garbage collector scan.
pub fn register_root_region(&mut self, start: &ValueRef, end: &ValueRef) {
self.root_regions.push(RootRegion {
start: start.clone(),
end: end.clone(),
is_stack: false,
});
}
/// Instrument a global destructor / atexit handler for leak checking.
fn instrument_exit_handler(&mut self, _module: &Module) {
// In a full implementation, this would insert code equivalent to:
// atexit(__lsan_do_leak_check);
// or add a module destructor.
self.checks_inserted += 1;
}
// ========================================================================
// Leak check insertion
// ========================================================================
/// Add a leak check call at a specific point in a function.
pub fn add_leak_check(&mut self, _func: &ValueRef) {
// Inserts a call to __lsan_do_leak_check() at the end of the function
// or at a specific program point.
self.checks_inserted += 1;
}
// ========================================================================
// Leak reporting (would be called by the runtime)
// ========================================================================
/// Generate a human-readable leak report from a list of leaks.
pub fn generate_leak_report(&self, leaks: &[LeakInfo]) -> String {
if leaks.is_empty() {
return "No leaks detected.\n".to_string();
}
let mut report = String::new();
report.push_str("========================================\n");
report.push_str(&format!(
"LeakSanitizer: detected {} leak(s)\n",
leaks.len()
));
report.push_str("========================================\n");
let total_bytes: u64 = leaks.iter().map(|l| l.size).sum();
report.push_str(&format!(
"Total leaked: {} byte(s) in {} allocation(s)\n",
total_bytes,
leaks.len()
));
for (idx, leak) in leaks.iter().enumerate() {
report.push_str(&format!(
"\nLeak #{}: {} bytes at 0x{:016x}\n",
idx + 1,
leak.size,
leak.address
));
report.push_str(&format!(
" allocated at {}:{}:{}\n",
leak.allocation_site.filename,
leak.allocation_site.line,
leak.allocation_site.column
));
}
report.push_str("\nDirect leak summary:\n");
report.push_str(&format!(" Total: {} byte(s)\n", total_bytes));
report
}
// ========================================================================
// Helpers
// ========================================================================
/// Check if a function name is a known allocator.
pub fn is_alloc_function(&self, name: &str) -> bool {
self.alloc_functions.contains_key(name)
}
/// Check if a function name is a known deallocator.
pub fn is_dealloc_function(&self, name: &str) -> bool {
self.dealloc_functions.contains_key(name)
}
/// Register a custom allocator function name.
pub fn register_alloc_function(&mut self, name: &str) {
self.alloc_functions.insert(name.to_string(), true);
}
/// Register a custom deallocator function name.
pub fn register_dealloc_function(&mut self, name: &str) {
self.dealloc_functions.insert(name.to_string(), true);
}
/// Get the number of allocation sites found.
pub fn num_allocation_sites(&self) -> usize {
self.allocations.len()
}
/// Get the number of root regions registered.
pub fn num_root_regions(&self) -> usize {
self.root_regions.len()
}
}
impl Default for LeakSanitizer {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Helper: Type size_bytes (minimal)
// ============================================================================
/// Extension trait for Type to get approximate byte size.
trait TypeSize {
fn size_bytes(&self) -> usize;
}
impl TypeSize for Type {
fn size_bytes(&self) -> usize {
match &self.kind {
llvm_native_core::types::TypeKind::Integer { bits } => ((bits + 7) / 8) as usize,
llvm_native_core::types::TypeKind::Pointer { .. } => 8,
llvm_native_core::types::TypeKind::Array { len, .. } => *len as usize,
llvm_native_core::types::TypeKind::Float => 4,
llvm_native_core::types::TypeKind::Double => 8,
_ => 8,
}
}
}
// ============================================================================
// Reachability Analysis from Root Set
// ============================================================================
/// Represents a memory snapshot for leak checking.
#[derive(Debug, Clone)]
pub struct MemorySnapshot {
/// All active allocations at snapshot time.
pub allocations: Vec<(u64, u64, String)>, // (addr, size, site_name)
/// Root regions (globals, stacks, registers).
pub roots: Vec<(u64, u64)>,
/// Timestamp of the snapshot.
pub timestamp: u64,
}
/// Performs reachability analysis to find leaked blocks.
#[derive(Debug, Clone)]
pub struct ReachabilityAnalyzer {
/// Whether to use a fast (conservative) or precise scanner.
pub use_fast_scanner: bool,
/// Minimum alignment for pointer detection.
pub pointer_alignment: u64,
/// Whether to scan registers.
pub scan_registers: bool,
}
impl ReachabilityAnalyzer {
pub fn new() -> Self {
Self {
use_fast_scanner: true,
pointer_alignment: 8,
scan_registers: false,
}
}
/// Check if a value looks like a valid heap pointer.
pub fn is_valid_pointer(&self, value: u64, heap_start: u64, heap_end: u64) -> bool {
value >= heap_start && value <= heap_end && value % self.pointer_alignment == 0
}
/// Find all reachable allocations from a root set.
/// Returns the set of allocation addresses that are reachable.
pub fn find_reachable(
&self,
roots: &[(u64, u64)],
allocations: &[(u64, u64, String)],
memory_reader: &dyn Fn(u64) -> Option<u64>,
) -> HashSet<u64> {
let mut reachable = HashSet::new();
let mut worklist: Vec<u64> = Vec::new();
// Seed worklist with root regions
for &(start, end) in roots {
for addr in (start..end).step_by(self.pointer_alignment as usize) {
if let Some(value) = memory_reader(addr) {
worklist.push(value);
}
}
}
// Iteratively follow pointers (transitive closure)
while let Some(ptr) = worklist.pop() {
// Check if ptr points into any allocation
for &(alloc_addr, alloc_size, _) in allocations {
if ptr >= alloc_addr && ptr < alloc_addr + alloc_size {
if reachable.insert(alloc_addr) {
// Scan this block for more pointers
for offset in (0..alloc_size).step_by(self.pointer_alignment as usize) {
if let Some(value) = memory_reader(alloc_addr + offset) {
worklist.push(value);
}
}
}
}
}
}
reachable
}
/// Identify leaked allocations: those not reachable from roots.
pub fn find_leaks(
&self,
snapshot: &MemorySnapshot,
memory_reader: &dyn Fn(u64) -> Option<u64>,
) -> Vec<(u64, u64, String)> {
let reachable = self.find_reachable(&snapshot.roots, &snapshot.allocations, memory_reader);
snapshot
.allocations
.iter()
.filter(|(addr, _, _)| !reachable.contains(addr))
.cloned()
.collect()
}
}
impl Default for ReachabilityAnalyzer {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Stop-The-World Leak Detection
// ============================================================================
/// Manages stop-the-world (STW) for leak checking.
/// In a real implementation this would pause all threads,
/// scan their stacks, and then resume.
#[derive(Debug, Clone)]
pub struct StopTheWorldContext {
/// Whether STW mode is active.
pub is_stopped: bool,
/// Number of threads paused.
pub thread_count: usize,
/// Thread stack regions: (thread_id, stack_start, stack_end).
pub thread_stacks: Vec<(u64, u64, u64)>,
/// Global root regions.
pub global_roots: Vec<(u64, u64)>,
}
impl StopTheWorldContext {
pub fn new() -> Self {
Self {
is_stopped: false,
thread_count: 0,
thread_stacks: Vec::new(),
global_roots: Vec::new(),
}
}
/// Begin STW — register all threads and roots.
pub fn stop_the_world(&mut self) {
self.is_stopped = true;
}
/// End STW — resume all threads.
pub fn resume_the_world(&mut self) {
self.is_stopped = false;
}
/// Register a thread's stack as a root region.
pub fn register_thread(&mut self, thread_id: u64, stack_start: u64, stack_end: u64) {
self.thread_stacks.push((thread_id, stack_start, stack_end));
self.thread_count += 1;
}
/// Get all root regions (thread stacks + globals).
pub fn all_roots(&self) -> Vec<(u64, u64)> {
let mut roots: Vec<(u64, u64)> = self
.thread_stacks
.iter()
.map(|&(_, start, end)| (start, end))
.collect();
roots.extend_from_slice(&self.global_roots);
roots
}
}
impl Default for StopTheWorldContext {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Suppressions File Parsing
// ============================================================================
/// A single suppression rule.
#[derive(Debug, Clone)]
pub struct SuppressionRule {
/// The type of leak this rule suppresses.
pub leak_type: String,
/// Function name pattern to match (glob-style).
pub fun_pattern: Option<String>,
/// Source file pattern to match.
pub src_pattern: Option<String>,
/// Whether this rule is active.
pub active: bool,
}
impl SuppressionRule {
/// Check if a leak report matches this suppression rule.
pub fn matches(&self, leak_type: &str, func_name: &str, src_file: &str) -> bool {
if !self.active {
return false;
}
if self.leak_type != "*" && self.leak_type != leak_type {
return false;
}
if let Some(ref pat) = self.fun_pattern {
if !glob_match(pat, func_name) {
return false;
}
}
if let Some(ref pat) = self.src_pattern {
if !glob_match(pat, src_file) {
return false;
}
}
true
}
}
/// Simple glob matching for suppression patterns.
fn glob_match(pattern: &str, text: &str) -> bool {
if pattern == "*" {
return true;
}
if !pattern.contains('*') {
return pattern == text;
}
let parts: Vec<&str> = pattern.split('*').collect();
let mut pos = 0;
for (i, part) in parts.iter().enumerate() {
if part.is_empty() {
if i == parts.len() - 1 {
return true; // trailing *
}
continue;
}
if let Some(found) = text[pos..].find(part) {
pos += found + part.len();
} else {
return false;
}
}
pos == text.len()
}
/// Parser for LSan suppression files.
#[derive(Debug, Clone)]
pub struct SuppressionParser {
/// Parsed suppression rules.
pub rules: Vec<SuppressionRule>,
}
impl SuppressionParser {
pub fn new() -> Self {
Self { rules: Vec::new() }
}
/// Parse a suppression file.
/// Format:
/// leak:LeakType
/// fun:FunctionNamePattern
/// src:SourceFilePattern
pub fn parse(&mut self, contents: &str) -> usize {
let mut current_rule: Option<SuppressionRule> = None;
for line in contents.lines() {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
if let Some(rule) = current_rule.take() {
self.rules.push(rule);
}
continue;
}
if let Some(rest) = trimmed.strip_prefix("leak:") {
if let Some(rule) = current_rule.take() {
self.rules.push(rule);
}
current_rule = Some(SuppressionRule {
leak_type: rest.trim().to_string(),
fun_pattern: None,
src_pattern: None,
active: true,
});
} else if let Some(ref mut rule) = current_rule {
if let Some(rest) = trimmed.strip_prefix("fun:") {
rule.fun_pattern = Some(rest.trim().to_string());
} else if let Some(rest) = trimmed.strip_prefix("src:") {
rule.src_pattern = Some(rest.trim().to_string());
}
}
}
if let Some(rule) = current_rule {
self.rules.push(rule);
}
self.rules.len()
}
/// Check if a leak is suppressed by any rule.
pub fn is_suppressed(&self, leak_type: &str, func_name: &str, src_file: &str) -> bool {
self.rules
.iter()
.any(|r| r.matches(leak_type, func_name, src_file))
}
/// Number of suppression rules.
pub fn count(&self) -> usize {
self.rules.len()
}
}
impl Default for SuppressionParser {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Allocator Integration for Full Allocation/Deallocation Tracking
// ============================================================================
/// Complete allocator tracker — records every allocation and deallocation
/// with full stack trace and timestamp.
#[derive(Debug, Clone)]
pub struct AllocatorTracker {
/// Active allocations: address → (size, timestamp, stack_trace).
pub active_allocations: HashMap<u64, (u64, u64, Vec<String>)>,
/// Recently freed allocations for use-after-free detection.
pub freed_allocations: Vec<(u64, u64, u64, Vec<String>)>, // addr, size, free_time, stack
/// Total bytes allocated.
pub total_bytes_allocated: u64,
/// Total bytes freed.
pub total_bytes_freed: u64,
/// Current allocation timestamp.
timestamp: u64,
/// Maximum number of freed entries to retain.
max_freed_entries: usize,
}
impl AllocatorTracker {
pub fn new() -> Self {
Self {
active_allocations: HashMap::new(),
freed_allocations: Vec::new(),
total_bytes_allocated: 0,
total_bytes_freed: 0,
timestamp: 0,
max_freed_entries: 1024,
}
}
/// Record an allocation.
pub fn record_alloc(&mut self, addr: u64, size: u64, stack_trace: Vec<String>) {
self.timestamp += 1;
self.active_allocations
.insert(addr, (size, self.timestamp, stack_trace));
self.total_bytes_allocated += size;
}
/// Record a deallocation.
pub fn record_dealloc(&mut self, addr: u64) -> Option<(u64, u64, Vec<String>)> {
if let Some((size, alloc_time, stack_trace)) = self.active_allocations.remove(&addr) {
self.total_bytes_freed += size;
self.freed_allocations
.push((addr, size, self.timestamp, stack_trace));
// Evict oldest if over capacity
if self.freed_allocations.len() > self.max_freed_entries {
self.freed_allocations.remove(0);
}
self.timestamp += 1;
None // Normal deallocation
} else {
// Possible double-free
Some((addr, 0, vec!["unknown allocation".into()]))
}
}
/// Check if an address is currently allocated.
pub fn is_allocated(&self, addr: u64) -> bool {
self.active_allocations.contains_key(&addr)
}
/// Check if an address was recently freed (use-after-free candidate).
pub fn was_recently_freed(&self, addr: u64) -> Option<(u64, Vec<String>)> {
self.freed_allocations
.iter()
.find(|(a, _, _, _)| *a == addr)
.map(|(_, size, _, trace)| (*size, trace.clone()))
}
/// Get allocation info for a leak report.
pub fn get_allocation_info(&self, addr: u64) -> Option<(u64, Vec<String>)> {
self.active_allocations
.get(&addr)
.map(|(size, _, trace)| (*size, trace.clone()))
}
/// Get total bytes currently leaked.
pub fn current_bytes_leaked(&self) -> u64 {
self.total_bytes_allocated - self.total_bytes_freed
}
/// Number of active allocations.
pub fn active_count(&self) -> usize {
self.active_allocations.len()
}
}
impl Default for AllocatorTracker {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Leak Report with Allocation Stack Trace
// ============================================================================
/// A detailed leak report with full allocation context.
#[derive(Debug, Clone)]
pub struct LeakReport {
/// Leaked block address.
pub address: u64,
/// Leaked block size.
pub size: u64,
/// Allocation site description.
pub allocation_site: String,
/// Stack trace at allocation time.
pub allocation_stack: Vec<String>,
/// Whether the leak is directly lost (no pointers to it) or indirectly lost.
pub leak_category: LeakCategory,
/// Whether this leak is suppressed.
pub is_suppressed: bool,
}
/// Category of a memory leak.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LeakCategory {
/// Memory with no pointers to it — definitely leaked.
DirectlyLost,
/// Memory only reachable from other leaked blocks.
IndirectlyLost,
/// Memory reachable (possibly from a global) but never freed.
Reachable,
/// Memory that might be leaked (uncertain).
PossiblyLost,
}
impl LeakCategory {
pub fn as_str(&self) -> &'static str {
match self {
LeakCategory::DirectlyLost => "directly lost",
LeakCategory::IndirectlyLost => "indirectly lost",
LeakCategory::Reachable => "reachable",
LeakCategory::PossiblyLost => "possibly lost",
}
}
}
/// Generates formatted leak reports.
#[derive(Debug, Clone)]
pub struct LeakReportGenerator {
/// All leak reports generated.
pub reports: Vec<LeakReport>,
/// Suppression parser for filtering.
pub suppressions: SuppressionParser,
/// Whether to include reachable blocks in reports.
pub report_reachable: bool,
/// Maximum number of leaks to report.
pub max_reports: usize,
}
impl LeakReportGenerator {
pub fn new() -> Self {
Self {
reports: Vec::new(),
suppressions: SuppressionParser::new(),
report_reachable: false,
max_reports: 100,
}
}
/// Generate a leak report from an allocator snapshot.
pub fn generate_report(
&mut self,
leaks: &[(u64, u64, Vec<String>)],
alloc_tracker: &AllocatorTracker,
) {
for &(addr, size, ref stack) in leaks {
if self.reports.len() >= self.max_reports {
break;
}
let site = stack.first().cloned().unwrap_or_else(|| "unknown".into());
let suppressed = self.suppressions.is_suppressed("Leak", &site, "");
let report = LeakReport {
address: addr,
size,
allocation_site: site,
allocation_stack: stack.clone(),
leak_category: LeakCategory::DirectlyLost,
is_suppressed: suppressed,
};
if !suppressed || self.report_reachable {
self.reports.push(report);
}
}
}
/// Format all reports as a human-readable summary.
pub fn format_summary(&self) -> String {
let visible: Vec<&LeakReport> = self.reports.iter().filter(|r| !r.is_suppressed).collect();
let total_bytes: u64 = visible.iter().map(|r| r.size).sum();
let mut summary = format!(
"=================================================================\n\
==LSan== LEAK REPORT\n\
==LSan== {} leaks found, {} bytes leaked\n",
visible.len(),
total_bytes
);
for report in &visible {
summary.push_str(&format!(
"\nDirect leak of {} byte(s) at 0x{:x}\n",
report.size, report.address
));
summary.push_str(&format!(" allocated from: {}\n", report.allocation_site));
for frame in &report.allocation_stack[1..] {
summary.push_str(&format!(" {}\n", frame));
}
}
summary.push_str("=================================================================\n");
summary
}
/// Number of reports.
pub fn count(&self) -> usize {
self.reports.len()
}
/// Number of suppressed reports.
pub fn suppressed_count(&self) -> usize {
self.reports.iter().filter(|r| r.is_suppressed).count()
}
}
impl Default for LeakReportGenerator {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Full LSan Integration
// ============================================================================
/// Complete LSan with all subsystems.
#[derive(Debug, Clone)]
pub struct LeakSanitizerFull {
/// Base LSan instance.
pub inner: LeakSanitizer,
/// Allocator tracker.
pub alloc_tracker: AllocatorTracker,
/// Reachability analyzer.
pub analyzer: ReachabilityAnalyzer,
/// STW context.
pub stw: StopTheWorldContext,
/// Report generator.
pub report_gen: LeakReportGenerator,
/// Whether full mode is active.
pub full_mode: bool,
}
impl LeakSanitizerFull {
pub fn new() -> Self {
Self {
inner: LeakSanitizer::new(),
alloc_tracker: AllocatorTracker::new(),
analyzer: ReachabilityAnalyzer::new(),
stw: StopTheWorldContext::new(),
report_gen: LeakReportGenerator::new(),
full_mode: false,
}
}
/// Run a complete leak check cycle.
pub fn run_full_leak_check(&mut self) -> usize {
self.stw.stop_the_world();
let roots = self.stw.all_roots();
// Gather snapshot
let allocs: Vec<(u64, u64, String)> = self
.alloc_tracker
.active_allocations
.iter()
.map(|(&addr, (size, _, trace))| {
(addr, *size, trace.first().cloned().unwrap_or_default())
})
.collect();
let snapshot = MemorySnapshot {
allocations: allocs,
roots,
timestamp: 0,
};
// Dummy memory reader (for real implementation, would read actual memory)
let reader = |_addr: u64| -> Option<u64> { None };
let leaks = self.analyzer.find_leaks(&snapshot, &reader);
// Convert to format expected by report generator
let leak_data: Vec<(u64, u64, Vec<String>)> = leaks
.iter()
.map(|(addr, size, site)| (*addr, *size, vec![site.clone()]))
.collect();
self.report_gen
.generate_report(&leak_data, &self.alloc_tracker);
self.stw.resume_the_world();
self.report_gen.count()
}
/// Record an allocation through the full pipeline.
pub fn record_allocation(&mut self, addr: u64, size: u64, stack: Vec<String>) {
self.alloc_tracker.record_alloc(addr, size, stack);
}
/// Record a deallocation through the full pipeline.
pub fn record_deallocation(&mut self, addr: u64) {
self.alloc_tracker.record_dealloc(addr);
}
/// Register a thread stack as a root.
pub fn register_thread_root(&mut self, thread_id: u64, stack_start: u64, stack_end: u64) {
self.stw.register_thread(thread_id, stack_start, stack_end);
}
/// Load suppressions from a file.
pub fn load_suppressions(&mut self, contents: &str) {
self.report_gen.suppressions.parse(contents);
}
/// Get the formatted leak report.
pub fn format_report(&self) -> String {
self.report_gen.format_summary()
}
/// Total bytes currently outstanding.
pub fn outstanding_bytes(&self) -> u64 {
self.alloc_tracker.current_bytes_leaked()
}
}
impl Default for LeakSanitizerFull {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_lsan_new() {
let lsan = LeakSanitizer::new();
assert!(lsan.leak_check_at_exit);
assert_eq!(lsan.max_leaks, 1024);
assert_eq!(lsan.allocs_instrumented, 0);
assert_eq!(lsan.deallocs_instrumented, 0);
}
#[test]
fn test_lsan_default() {
let lsan = LeakSanitizer::default();
assert!(lsan.leak_check_at_exit);
}
#[test]
fn test_is_alloc_function() {
let lsan = LeakSanitizer::new();
assert!(lsan.is_alloc_function("malloc"));
assert!(lsan.is_alloc_function("calloc"));
assert!(lsan.is_alloc_function("realloc"));
}
#[test]
fn test_is_dealloc_function() {
let lsan = LeakSanitizer::new();
assert!(lsan.is_dealloc_function("free"));
assert!(lsan.is_dealloc_function("realloc"));
}
#[test]
fn test_not_alloc_function() {
let lsan = LeakSanitizer::new();
assert!(!lsan.is_alloc_function("printf"));
assert!(!lsan.is_alloc_function("unknown"));
}
#[test]
fn test_register_custom_alloc() {
let mut lsan = LeakSanitizer::new();
lsan.register_alloc_function("my_alloc");
assert!(lsan.is_alloc_function("my_alloc"));
}
#[test]
fn test_register_custom_dealloc() {
let mut lsan = LeakSanitizer::new();
lsan.register_dealloc_function("my_free");
assert!(lsan.is_dealloc_function("my_free"));
}
#[test]
fn test_run_on_empty_module() {
let mut lsan = LeakSanitizer::new();
let mut module = llvm_native_core::module::Module::new("test");
let count = lsan.run_on_module(&mut module);
// No functions → only roots registered (no globals) and maybe exit check
assert!(count >= 0);
}
#[test]
fn test_register_root_region() {
let mut lsan = LeakSanitizer::new();
let v1 = valref(Value::new(Type::i32()));
let v2 = valref(Value::new(Type::i32()));
lsan.register_root_region(&v1, &v2);
assert_eq!(lsan.num_root_regions(), 1);
}
#[test]
fn test_generate_leak_report_empty() {
let lsan = LeakSanitizer::new();
let report = lsan.generate_leak_report(&[]);
assert!(report.contains("No leaks detected"));
}
#[test]
fn test_generate_leak_report_with_leaks() {
let lsan = LeakSanitizer::new();
let leaks = vec![
LeakInfo {
address: 0x1000,
size: 64,
allocation_site: SourceLoc {
filename: "test.c".to_string(),
line: 42,
column: 10,
offset: 0,
},
},
LeakInfo {
address: 0x2000,
size: 128,
allocation_site: SourceLoc {
filename: "test.c".to_string(),
line: 100,
column: 5,
offset: 0,
},
},
];
let report = lsan.generate_leak_report(&leaks);
assert!(report.contains("detected 2 leak"));
assert!(report.contains("192 byte"));
assert!(report.contains("test.c:42:10"));
assert!(report.contains("test.c:100:5"));
}
#[test]
fn test_add_leak_check() {
let mut lsan = LeakSanitizer::new();
let func = valref(Value::new(Type::void()).with_subclass(SubclassKind::Function));
assert_eq!(lsan.checks_inserted, 0);
lsan.add_leak_check(&func);
assert_eq!(lsan.checks_inserted, 1);
}
#[test]
fn test_num_allocation_sites() {
let lsan = LeakSanitizer::new();
assert_eq!(lsan.num_allocation_sites(), 0);
}
#[test]
fn test_leak_info_clone() {
let leak = LeakInfo {
address: 0xdeadbeef,
size: 256,
allocation_site: SourceLoc {
filename: "main.c".to_string(),
line: 10,
column: 1,
offset: 0,
},
};
let leak2 = leak.clone();
assert_eq!(leak2.address, 0xdeadbeef);
assert_eq!(leak2.size, 256);
assert_eq!(leak2.allocation_site.filename, "main.c");
}
#[test]
fn test_cpp_alloc_functions() {
let lsan = LeakSanitizer::new();
assert!(lsan.is_alloc_function("_Znwm")); // operator new
assert!(lsan.is_alloc_function("_Znam")); // operator new[]
}
#[test]
fn test_cpp_dealloc_functions() {
let lsan = LeakSanitizer::new();
assert!(lsan.is_dealloc_function("_ZdlPv")); // operator delete
assert!(lsan.is_dealloc_function("_ZdaPv")); // operator delete[]
}
}