oxicuda-driver 0.1.1

OxiCUDA Driver - Dynamic CUDA driver API wrapper via libloading (zero SDK dependency)
Documentation
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
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
//! Kernel debugging utilities for OxiCUDA.
//!
//! This module provides tools for debugging GPU kernels without traditional
//! debuggers. It includes memory checking, NaN/Inf detection, printf
//! emulation, assertion support, and PTX instrumentation for automated
//! bounds/NaN checking.
//!
//! # Architecture
//!
//! The debugging system is layered:
//!
//! 1. **`KernelDebugger`** — Top-level manager that creates debug sessions and
//!    manages breakpoints / watchpoints.
//! 2. **`DebugSession`** — Collects [`DebugEvent`]s for a single kernel launch.
//! 3. **`MemoryChecker`** — Validates memory accesses against known allocations.
//! 4. **`NanInfChecker`** — Scans host-side buffers for NaN / Inf values.
//! 5. **`PrintfBuffer`** — Parses a raw byte buffer that emulates GPU `printf`.
//! 6. **`KernelAssertions`** — Convenience assertion helpers that produce
//!    [`DebugEvent`]s instead of panicking.
//! 7. **`DebugPtxInstrumenter`** — Instruments PTX source for automated
//!    bounds/NaN checking and printf support.
//!
//! # Example
//!
//! ```rust
//! use oxicuda_driver::debug::*;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let config = KernelDebugConfig::default();
//! let mut debugger = KernelDebugger::new(config);
//! let session = debugger.attach("my_kernel")?;
//! assert_eq!(session.kernel_name(), "my_kernel");
//! # Ok(())
//! # }
//! ```

use std::fmt;

use crate::error::{CudaError, CudaResult};

// ---------------------------------------------------------------------------
// DebugLevel
// ---------------------------------------------------------------------------

/// Verbosity level for kernel debugging output.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum DebugLevel {
    /// No debug output.
    Off,
    /// Only errors.
    Error,
    /// Errors and warnings.
    Warn,
    /// Errors, warnings, and informational messages.
    #[default]
    Info,
    /// Verbose debugging output.
    Debug,
    /// Maximum verbosity — every detail is logged.
    Trace,
}

impl fmt::Display for DebugLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Off => write!(f, "OFF"),
            Self::Error => write!(f, "ERROR"),
            Self::Warn => write!(f, "WARN"),
            Self::Info => write!(f, "INFO"),
            Self::Debug => write!(f, "DEBUG"),
            Self::Trace => write!(f, "TRACE"),
        }
    }
}

// ---------------------------------------------------------------------------
// KernelDebugConfig
// ---------------------------------------------------------------------------

/// Configuration for a kernel debug session.
#[derive(Debug, Clone)]
pub struct KernelDebugConfig {
    /// The verbosity level for debug output.
    pub debug_level: DebugLevel,
    /// Whether to instrument bounds checking on memory accesses.
    pub enable_bounds_check: bool,
    /// Whether to detect NaN values in floating-point registers.
    pub enable_nan_check: bool,
    /// Whether to detect Inf values in floating-point registers.
    pub enable_inf_check: bool,
    /// Whether to detect potential race conditions.
    pub enable_race_detection: bool,
    /// Size of the GPU-side printf buffer in bytes.
    pub print_buffer_size: usize,
    /// Maximum number of printf calls per thread before truncation.
    pub max_print_per_thread: usize,
}

impl Default for KernelDebugConfig {
    fn default() -> Self {
        Self {
            debug_level: DebugLevel::Info,
            enable_bounds_check: true,
            enable_nan_check: true,
            enable_inf_check: true,
            enable_race_detection: false,
            print_buffer_size: 1024 * 1024, // 1 MiB
            max_print_per_thread: 32,
        }
    }
}

// ---------------------------------------------------------------------------
// DebugEventType
// ---------------------------------------------------------------------------

/// The kind of debug event captured during kernel execution.
#[derive(Debug, Clone, PartialEq)]
pub enum DebugEventType {
    /// A memory access was out of the allocated bounds.
    OutOfBounds {
        /// The faulting address.
        address: u64,
        /// The size of the attempted access in bytes.
        size: usize,
    },
    /// A NaN was detected in a floating-point register.
    NanDetected {
        /// Register or variable name.
        register: String,
        /// The NaN bit-pattern reinterpreted as f64.
        value: f64,
    },
    /// An infinity was detected in a floating-point register.
    InfDetected {
        /// Register or variable name.
        register: String,
    },
    /// A potential race condition on a shared memory address.
    RaceCondition {
        /// The conflicting address.
        address: u64,
    },
    /// A kernel-side assertion.
    Assertion {
        /// The assertion condition expression.
        condition: String,
        /// Source file name.
        file: String,
        /// Source line number.
        line: u32,
    },
    /// A kernel-side printf invocation.
    Printf {
        /// The format string.
        format: String,
    },
    /// A breakpoint was hit.
    Breakpoint {
        /// The breakpoint identifier.
        id: u32,
    },
}

impl DebugEventType {
    /// Returns a short category tag suitable for filtering.
    fn tag(&self) -> &'static str {
        match self {
            Self::OutOfBounds { .. } => "OOB",
            Self::NanDetected { .. } => "NaN",
            Self::InfDetected { .. } => "Inf",
            Self::RaceCondition { .. } => "RACE",
            Self::Assertion { .. } => "ASSERT",
            Self::Printf { .. } => "PRINTF",
            Self::Breakpoint { .. } => "BP",
        }
    }

    /// Returns `true` when this variant has the same discriminant as `other`,
    /// ignoring inner field values. Used by [`DebugSession::filter_events`].
    fn same_kind(&self, other: &Self) -> bool {
        std::mem::discriminant(self) == std::mem::discriminant(other)
    }
}

// ---------------------------------------------------------------------------
// DebugEvent
// ---------------------------------------------------------------------------

/// A single debug event captured during kernel execution.
#[derive(Debug, Clone)]
pub struct DebugEvent {
    /// What kind of event occurred.
    pub event_type: DebugEventType,
    /// The CUDA thread index `(x, y, z)` that triggered the event.
    pub thread_id: (u32, u32, u32),
    /// The CUDA block index `(x, y, z)` that triggered the event.
    pub block_id: (u32, u32, u32),
    /// Timestamp in nanoseconds (monotonic, relative to session start).
    pub timestamp_ns: u64,
    /// Free-form human-readable message.
    pub message: String,
}

impl fmt::Display for DebugEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "[{tag}] block({bx},{by},{bz}) thread({tx},{ty},{tz}) @{ts}ns: {msg}",
            tag = self.event_type.tag(),
            bx = self.block_id.0,
            by = self.block_id.1,
            bz = self.block_id.2,
            tx = self.thread_id.0,
            ty = self.thread_id.1,
            tz = self.thread_id.2,
            ts = self.timestamp_ns,
            msg = self.message,
        )
    }
}

// ---------------------------------------------------------------------------
// WatchType
// ---------------------------------------------------------------------------

/// The kind of memory access a watchpoint monitors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WatchType {
    /// Trigger on reads.
    Read,
    /// Trigger on writes.
    Write,
    /// Trigger on both reads and writes.
    ReadWrite,
}

// ---------------------------------------------------------------------------
// Breakpoint / Watchpoint helpers
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
#[allow(dead_code)]
struct Breakpoint {
    id: u32,
    line: u32,
}

#[derive(Debug, Clone)]
#[allow(dead_code)]
struct Watchpoint {
    id: u32,
    address: u64,
    size: usize,
    watch_type: WatchType,
}

// ---------------------------------------------------------------------------
// KernelDebugger
// ---------------------------------------------------------------------------

/// Top-level kernel debugging manager.
///
/// Create one per debugging session group. It holds global breakpoints and
/// watchpoints and spawns [`DebugSession`] instances per kernel launch.
#[derive(Debug)]
pub struct KernelDebugger {
    config: KernelDebugConfig,
    breakpoints: Vec<Breakpoint>,
    watchpoints: Vec<Watchpoint>,
    next_bp_id: u32,
    next_wp_id: u32,
}

impl KernelDebugger {
    /// Create a new kernel debugger with the given configuration.
    pub fn new(config: KernelDebugConfig) -> Self {
        Self {
            config,
            breakpoints: Vec::new(),
            watchpoints: Vec::new(),
            next_bp_id: 1,
            next_wp_id: 1,
        }
    }

    /// Attach the debugger to a kernel launch, returning a new debug session.
    ///
    /// On macOS this always succeeds with a synthetic (empty) session because
    /// no actual GPU driver is available.
    ///
    /// # Errors
    ///
    /// Returns [`CudaError::InvalidValue`] if `kernel_name` is empty.
    pub fn attach(&mut self, kernel_name: &str) -> CudaResult<DebugSession> {
        if kernel_name.is_empty() {
            return Err(CudaError::InvalidValue);
        }
        Ok(DebugSession {
            kernel_name: kernel_name.to_owned(),
            events: Vec::new(),
            config: self.config.clone(),
        })
    }

    /// Set a breakpoint at a PTX source line. Returns the breakpoint ID.
    pub fn set_breakpoint(&mut self, line: u32) -> u32 {
        let id = self.next_bp_id;
        self.next_bp_id = self.next_bp_id.saturating_add(1);
        self.breakpoints.push(Breakpoint { id, line });
        id
    }

    /// Remove a breakpoint by ID. Returns `true` if it was found and removed.
    pub fn remove_breakpoint(&mut self, bp_id: u32) -> bool {
        let before = self.breakpoints.len();
        self.breakpoints.retain(|bp| bp.id != bp_id);
        self.breakpoints.len() < before
    }

    /// Set a memory watchpoint. Returns the watchpoint ID.
    pub fn watchpoint(&mut self, address: u64, size: usize, watch_type: WatchType) -> u32 {
        let id = self.next_wp_id;
        self.next_wp_id = self.next_wp_id.saturating_add(1);
        self.watchpoints.push(Watchpoint {
            id,
            address,
            size,
            watch_type,
        });
        id
    }

    /// Returns a reference to the current debug configuration.
    pub fn config(&self) -> &KernelDebugConfig {
        &self.config
    }
}

// ---------------------------------------------------------------------------
// DebugSummary
// ---------------------------------------------------------------------------

/// Aggregate statistics for a debug session.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DebugSummary {
    /// Total number of debug events.
    pub total_events: usize,
    /// Number of error-level events (OOB, assertions, races).
    pub errors: usize,
    /// Number of warning-level events (NaN, Inf).
    pub warnings: usize,
    /// Number of NaN detection events.
    pub nan_count: usize,
    /// Number of Inf detection events.
    pub inf_count: usize,
    /// Number of out-of-bounds events.
    pub oob_count: usize,
    /// Number of race condition events.
    pub race_count: usize,
}

// ---------------------------------------------------------------------------
// DebugSession
// ---------------------------------------------------------------------------

/// An active debug session for a single kernel launch.
///
/// Collects [`DebugEvent`]s and provides analysis / reporting helpers.
#[derive(Debug)]
pub struct DebugSession {
    kernel_name: String,
    events: Vec<DebugEvent>,
    #[allow(dead_code)]
    config: KernelDebugConfig,
}

impl DebugSession {
    /// The kernel name this session is attached to.
    pub fn kernel_name(&self) -> &str {
        &self.kernel_name
    }

    /// All events collected so far.
    pub fn events(&self) -> &[DebugEvent] {
        &self.events
    }

    /// Record a new debug event.
    pub fn add_event(&mut self, event: DebugEvent) {
        self.events.push(event);
    }

    /// Return references to events whose type matches the discriminant of
    /// `event_type` (field values inside variants are ignored for matching).
    pub fn filter_events(&self, event_type: &DebugEventType) -> Vec<&DebugEvent> {
        self.events
            .iter()
            .filter(|e| e.event_type.same_kind(event_type))
            .collect()
    }

    /// Compute aggregate statistics over all collected events.
    pub fn summary(&self) -> DebugSummary {
        let mut s = DebugSummary {
            total_events: self.events.len(),
            ..DebugSummary::default()
        };
        for ev in &self.events {
            match &ev.event_type {
                DebugEventType::OutOfBounds { .. } => {
                    s.oob_count += 1;
                    s.errors += 1;
                }
                DebugEventType::NanDetected { .. } => {
                    s.nan_count += 1;
                    s.warnings += 1;
                }
                DebugEventType::InfDetected { .. } => {
                    s.inf_count += 1;
                    s.warnings += 1;
                }
                DebugEventType::RaceCondition { .. } => {
                    s.race_count += 1;
                    s.errors += 1;
                }
                DebugEventType::Assertion { .. } => {
                    s.errors += 1;
                }
                DebugEventType::Printf { .. } | DebugEventType::Breakpoint { .. } => {}
            }
        }
        s
    }

    /// Produce a human-readable debug report.
    pub fn format_report(&self) -> String {
        let summary = self.summary();
        let mut out = String::with_capacity(512);
        out.push_str(&format!("=== Debug Report: {} ===\n", self.kernel_name));
        out.push_str(&format!(
            "Total events: {}  (errors: {}, warnings: {})\n",
            summary.total_events, summary.errors, summary.warnings
        ));
        if summary.oob_count > 0 {
            out.push_str(&format!("  Out-of-bounds: {}\n", summary.oob_count));
        }
        if summary.nan_count > 0 {
            out.push_str(&format!("  NaN detected:  {}\n", summary.nan_count));
        }
        if summary.inf_count > 0 {
            out.push_str(&format!("  Inf detected:  {}\n", summary.inf_count));
        }
        if summary.race_count > 0 {
            out.push_str(&format!("  Race cond.:    {}\n", summary.race_count));
        }
        out.push_str("--- Events ---\n");
        for ev in &self.events {
            out.push_str(&format!("  {ev}\n"));
        }
        out.push_str("=== End Report ===\n");
        out
    }
}

// ---------------------------------------------------------------------------
// MemoryRegion / MemoryChecker
// ---------------------------------------------------------------------------

/// A contiguous GPU memory allocation known to the memory checker.
#[derive(Debug, Clone)]
pub struct MemoryRegion {
    /// Base device address of the allocation.
    pub base_address: u64,
    /// Size in bytes.
    pub size: usize,
    /// Human-readable name for diagnostics.
    pub name: String,
    /// Whether the allocation is read-only.
    pub is_readonly: bool,
}

/// Validates memory accesses against a set of known [`MemoryRegion`]s.
#[derive(Debug)]
pub struct MemoryChecker {
    allocations: Vec<MemoryRegion>,
}

impl MemoryChecker {
    /// Create a memory checker from a list of known allocations.
    pub fn new(allocations: Vec<MemoryRegion>) -> Self {
        Self { allocations }
    }

    /// Check whether a memory access is valid.
    ///
    /// Returns `Some(DebugEvent)` if the access is out of bounds or violates
    /// read-only protections; `None` if the access is valid.
    pub fn check_access(&self, address: u64, size: usize, is_write: bool) -> Option<DebugEvent> {
        // Find the allocation that contains this address.
        let region = self.allocations.iter().find(|r| {
            address >= r.base_address
                && address
                    .checked_add(size as u64)
                    .is_some_and(|end| end <= r.base_address + r.size as u64)
        });

        match region {
            Some(r) if is_write && r.is_readonly => Some(DebugEvent {
                event_type: DebugEventType::OutOfBounds { address, size },
                thread_id: (0, 0, 0),
                block_id: (0, 0, 0),
                timestamp_ns: 0,
                message: format!("Write to read-only region '{}' at {:#x}", r.name, address),
            }),
            Some(_) => None,
            None => Some(DebugEvent {
                event_type: DebugEventType::OutOfBounds { address, size },
                thread_id: (0, 0, 0),
                block_id: (0, 0, 0),
                timestamp_ns: 0,
                message: format!(
                    "Access at {:#x} (size {}) does not fall within any known allocation",
                    address, size
                ),
            }),
        }
    }
}

// ---------------------------------------------------------------------------
// NanInfChecker / NanInfLocation
// ---------------------------------------------------------------------------

/// Location of a NaN or Inf value found in a buffer.
#[derive(Debug, Clone, PartialEq)]
pub struct NanInfLocation {
    /// Index into the buffer.
    pub index: usize,
    /// The problematic value (as f64 for uniform reporting).
    pub value: f64,
    /// `true` if NaN, `false` if Inf.
    pub is_nan: bool,
}

/// Scans host-side buffers for NaN and Inf values.
#[derive(Debug, Clone, Copy)]
pub struct NanInfChecker;

impl NanInfChecker {
    /// Check an `f32` buffer for NaN and Inf values.
    pub fn check_f32(data: &[f32]) -> Vec<NanInfLocation> {
        data.iter()
            .enumerate()
            .filter_map(|(i, &v)| {
                if v.is_nan() {
                    Some(NanInfLocation {
                        index: i,
                        value: f64::from(v),
                        is_nan: true,
                    })
                } else if v.is_infinite() {
                    Some(NanInfLocation {
                        index: i,
                        value: f64::from(v),
                        is_nan: false,
                    })
                } else {
                    None
                }
            })
            .collect()
    }

    /// Check an `f64` buffer for NaN and Inf values.
    pub fn check_f64(data: &[f64]) -> Vec<NanInfLocation> {
        data.iter()
            .enumerate()
            .filter_map(|(i, &v)| {
                if v.is_nan() {
                    Some(NanInfLocation {
                        index: i,
                        value: v,
                        is_nan: true,
                    })
                } else if v.is_infinite() {
                    Some(NanInfLocation {
                        index: i,
                        value: v,
                        is_nan: false,
                    })
                } else {
                    None
                }
            })
            .collect()
    }
}

// ---------------------------------------------------------------------------
// PrintfBuffer / PrintfEntry / PrintfArg
// ---------------------------------------------------------------------------

/// A single argument captured from a GPU printf call.
#[derive(Debug, Clone, PartialEq)]
pub enum PrintfArg {
    /// Integer argument.
    Int(i64),
    /// Floating-point argument.
    Float(f64),
    /// String argument.
    String(String),
}

/// A parsed GPU-side printf entry.
#[derive(Debug, Clone)]
pub struct PrintfEntry {
    /// Thread index that issued the printf.
    pub thread_id: (u32, u32, u32),
    /// Block index that issued the printf.
    pub block_id: (u32, u32, u32),
    /// The format string.
    pub format_string: String,
    /// Parsed arguments.
    pub args: Vec<PrintfArg>,
}

/// GPU-side printf emulation buffer.
///
/// The buffer layout is a simple framed protocol:
///
/// ```text
/// [entry_count: u32_le]
/// repeated entry_count times:
///   [thread_x: u32_le] [thread_y: u32_le] [thread_z: u32_le]
///   [block_x:  u32_le] [block_y:  u32_le] [block_z:  u32_le]
///   [fmt_len:  u32_le] [fmt_bytes: u8 * fmt_len]
///   [arg_count: u32_le]
///   repeated arg_count times:
///     [tag: u8]  0=Int(i64_le), 1=Float(f64_le), 2=String(u32_le len + bytes)
/// ```
#[derive(Debug)]
pub struct PrintfBuffer {
    buffer_size: usize,
}

impl PrintfBuffer {
    /// Create a printf buffer descriptor with the given maximum size.
    pub fn new(buffer_size: usize) -> Self {
        Self { buffer_size }
    }

    /// Returns the configured buffer size.
    pub fn buffer_size(&self) -> usize {
        self.buffer_size
    }

    /// Parse a raw byte buffer into structured printf entries.
    ///
    /// Returns an empty vec if the buffer is too small or malformed.
    pub fn parse_entries(&self, raw: &[u8]) -> Vec<PrintfEntry> {
        let mut entries = Vec::new();
        let mut cursor = 0usize;

        let entry_count = match Self::read_u32(raw, &mut cursor) {
            Some(n) => n as usize,
            None => return entries,
        };

        for _ in 0..entry_count {
            let Some(entry) = self.parse_single_entry(raw, &mut cursor) else {
                break;
            };
            entries.push(entry);
        }

        entries
    }

    fn parse_single_entry(&self, raw: &[u8], cursor: &mut usize) -> Option<PrintfEntry> {
        let tx = Self::read_u32(raw, cursor)?;
        let ty = Self::read_u32(raw, cursor)?;
        let tz = Self::read_u32(raw, cursor)?;
        let bx = Self::read_u32(raw, cursor)?;
        let by = Self::read_u32(raw, cursor)?;
        let bz = Self::read_u32(raw, cursor)?;

        let fmt_len = Self::read_u32(raw, cursor)? as usize;
        let fmt_bytes = Self::read_bytes(raw, cursor, fmt_len)?;
        let format_string = String::from_utf8_lossy(fmt_bytes).into_owned();

        let arg_count = Self::read_u32(raw, cursor)? as usize;
        let mut args = Vec::with_capacity(arg_count);
        for _ in 0..arg_count {
            let tag = Self::read_u8(raw, cursor)?;
            let arg = match tag {
                0 => {
                    let val = Self::read_i64(raw, cursor)?;
                    PrintfArg::Int(val)
                }
                1 => {
                    let val = Self::read_f64(raw, cursor)?;
                    PrintfArg::Float(val)
                }
                2 => {
                    let slen = Self::read_u32(raw, cursor)? as usize;
                    let sbytes = Self::read_bytes(raw, cursor, slen)?;
                    PrintfArg::String(String::from_utf8_lossy(sbytes).into_owned())
                }
                _ => return None,
            };
            args.push(arg);
        }

        Some(PrintfEntry {
            thread_id: (tx, ty, tz),
            block_id: (bx, by, bz),
            format_string,
            args,
        })
    }

    // --- Low-level readers ---

    fn read_u8(raw: &[u8], cursor: &mut usize) -> Option<u8> {
        if *cursor >= raw.len() {
            return None;
        }
        let val = raw[*cursor];
        *cursor += 1;
        Some(val)
    }

    fn read_u32(raw: &[u8], cursor: &mut usize) -> Option<u32> {
        if *cursor + 4 > raw.len() {
            return None;
        }
        let bytes: [u8; 4] = raw[*cursor..*cursor + 4].try_into().ok()?;
        *cursor += 4;
        Some(u32::from_le_bytes(bytes))
    }

    fn read_i64(raw: &[u8], cursor: &mut usize) -> Option<i64> {
        if *cursor + 8 > raw.len() {
            return None;
        }
        let bytes: [u8; 8] = raw[*cursor..*cursor + 8].try_into().ok()?;
        *cursor += 8;
        Some(i64::from_le_bytes(bytes))
    }

    fn read_f64(raw: &[u8], cursor: &mut usize) -> Option<f64> {
        if *cursor + 8 > raw.len() {
            return None;
        }
        let bytes: [u8; 8] = raw[*cursor..*cursor + 8].try_into().ok()?;
        *cursor += 8;
        Some(f64::from_le_bytes(bytes))
    }

    fn read_bytes<'a>(raw: &'a [u8], cursor: &mut usize, len: usize) -> Option<&'a [u8]> {
        if *cursor + len > raw.len() {
            return None;
        }
        let slice = &raw[*cursor..*cursor + len];
        *cursor += len;
        Some(slice)
    }
}

// ---------------------------------------------------------------------------
// KernelAssertions
// ---------------------------------------------------------------------------

/// Convenience assertion helpers that produce [`DebugEvent`]s instead of
/// panicking, suitable for GPU kernel emulation / validation.
#[derive(Debug, Clone, Copy)]
pub struct KernelAssertions;

impl KernelAssertions {
    /// Assert that `index < len`. Returns an event if the assertion fails.
    pub fn assert_bounds(index: usize, len: usize, name: &str) -> Option<DebugEvent> {
        if index < len {
            return None;
        }
        Some(DebugEvent {
            event_type: DebugEventType::Assertion {
                condition: format!("{name}[{index}] < {len}"),
                file: String::new(),
                line: 0,
            },
            thread_id: (0, 0, 0),
            block_id: (0, 0, 0),
            timestamp_ns: 0,
            message: format!("Bounds check failed: {name}[{index}] out of range (len={len})"),
        })
    }

    /// Assert that `value` is not NaN. Returns an event if it is.
    pub fn assert_not_nan(value: f64, name: &str) -> Option<DebugEvent> {
        if !value.is_nan() {
            return None;
        }
        Some(DebugEvent {
            event_type: DebugEventType::NanDetected {
                register: name.to_owned(),
                value,
            },
            thread_id: (0, 0, 0),
            block_id: (0, 0, 0),
            timestamp_ns: 0,
            message: format!("NaN detected in '{name}'"),
        })
    }

    /// Assert that `value` is finite (not NaN and not Inf). Returns an event
    /// if it is not.
    pub fn assert_finite(value: f64, name: &str) -> Option<DebugEvent> {
        if value.is_finite() {
            return None;
        }
        if value.is_nan() {
            return Some(DebugEvent {
                event_type: DebugEventType::NanDetected {
                    register: name.to_owned(),
                    value,
                },
                thread_id: (0, 0, 0),
                block_id: (0, 0, 0),
                timestamp_ns: 0,
                message: format!("Non-finite (NaN) value in '{name}'"),
            });
        }
        Some(DebugEvent {
            event_type: DebugEventType::InfDetected {
                register: name.to_owned(),
            },
            thread_id: (0, 0, 0),
            block_id: (0, 0, 0),
            timestamp_ns: 0,
            message: format!("Non-finite (Inf) value in '{name}'"),
        })
    }

    /// Assert that `value` is strictly positive. Returns an event if it is
    /// not (including NaN, zero, and negative values).
    pub fn assert_positive(value: f64, name: &str) -> Option<DebugEvent> {
        if value > 0.0 {
            return None;
        }
        if value.is_nan() {
            return Some(DebugEvent {
                event_type: DebugEventType::NanDetected {
                    register: name.to_owned(),
                    value,
                },
                thread_id: (0, 0, 0),
                block_id: (0, 0, 0),
                timestamp_ns: 0,
                message: format!("Expected positive value for '{name}', got NaN"),
            });
        }
        Some(DebugEvent {
            event_type: DebugEventType::Assertion {
                condition: format!("{name} > 0"),
                file: String::new(),
                line: 0,
            },
            thread_id: (0, 0, 0),
            block_id: (0, 0, 0),
            timestamp_ns: 0,
            message: format!("Expected positive value for '{name}', got {value}"),
        })
    }
}

// ---------------------------------------------------------------------------
// DebugPtxInstrumenter
// ---------------------------------------------------------------------------

/// Instruments PTX source code with debugging checks.
///
/// This instrumenter inserts additional PTX instructions for bounds checking,
/// NaN detection, and printf buffer support. The instrumented code writes
/// diagnostic data to a designated debug buffer that the host can read back
/// after kernel execution.
#[derive(Debug)]
pub struct DebugPtxInstrumenter {
    enable_bounds_check: bool,
    enable_nan_check: bool,
    enable_printf: bool,
}

impl DebugPtxInstrumenter {
    /// Create an instrumenter from a debug configuration.
    pub fn new(config: &KernelDebugConfig) -> Self {
        Self {
            enable_bounds_check: config.enable_bounds_check,
            enable_nan_check: config.enable_nan_check,
            enable_printf: config.print_buffer_size > 0,
        }
    }

    /// Insert bounds-checking instrumentation into PTX source.
    ///
    /// Adds `setp` + `trap` sequences after every `ld.global` / `st.global`
    /// instruction to validate the address against the allocation size
    /// parameter.
    pub fn instrument_bounds_checks(&self, ptx: &str) -> String {
        if !self.enable_bounds_check {
            return ptx.to_owned();
        }

        let mut output = String::with_capacity(ptx.len() + ptx.len() / 4);
        // Add debug parameter declaration at the top of each kernel entry.
        let mut added_param = false;

        for line in ptx.lines() {
            let trimmed = line.trim();
            // Insert debug buffer param after .entry
            if trimmed.starts_with(".entry") && !added_param {
                output.push_str(line);
                output.push('\n');
                output.push_str("    // [oxicuda-debug] bounds-check instrumentation\n");
                output.push_str("    .param .u64 __oxicuda_debug_buf;\n");
                added_param = true;
                continue;
            }

            // Instrument global loads/stores
            if (trimmed.starts_with("ld.global") || trimmed.starts_with("st.global"))
                && !trimmed.starts_with("// [oxicuda-debug]")
            {
                output.push_str(line);
                output.push('\n');
                output.push_str("    // [oxicuda-debug] bounds check for above access\n");
                output.push_str("    setp.ge.u64 %p_oob, %rd_addr, %rd_alloc_end;\n");
                output.push_str("    @%p_oob trap;\n");
            } else {
                output.push_str(line);
                output.push('\n');
            }
        }

        output
    }

    /// Insert NaN-detection instrumentation into PTX source.
    ///
    /// After every floating-point arithmetic instruction (`add.f32`,
    /// `mul.f64`, etc.) a `testp.nan` check is inserted.
    pub fn instrument_nan_checks(&self, ptx: &str) -> String {
        if !self.enable_nan_check {
            return ptx.to_owned();
        }

        let fp_ops = [
            "add.f32", "add.f64", "sub.f32", "sub.f64", "mul.f32", "mul.f64", "div.f32", "div.f64",
            "fma.f32", "fma.f64",
        ];

        let mut output = String::with_capacity(ptx.len() + ptx.len() / 4);

        for line in ptx.lines() {
            output.push_str(line);
            output.push('\n');

            let trimmed = line.trim();
            if fp_ops.iter().any(|op| trimmed.starts_with(op)) {
                // Extract the destination register (first token after the op).
                if let Some(dest) = trimmed.split_whitespace().nth(1) {
                    let dest_clean = dest.trim_end_matches(',');
                    let width = if trimmed.contains(".f64") {
                        "f64"
                    } else {
                        "f32"
                    };
                    output.push_str(&format!(
                        "    // [oxicuda-debug] NaN check for {dest_clean}\n"
                    ));
                    output.push_str(&format!("    testp.nan.{width} %p_nan, {dest_clean};\n"));
                    output.push_str("    @%p_nan trap;\n");
                }
            }
        }

        output
    }

    /// Insert printf buffer support into PTX source.
    ///
    /// Adds a `.param .u64 __oxicuda_printf_buf` to each entry and inserts
    /// stub store sequences where `// PRINTF` markers appear.
    pub fn instrument_printf(&self, ptx: &str) -> String {
        if !self.enable_printf {
            return ptx.to_owned();
        }

        let mut output = String::with_capacity(ptx.len() + ptx.len() / 4);
        let mut added_param = false;

        for line in ptx.lines() {
            let trimmed = line.trim();
            if trimmed.starts_with(".entry") && !added_param {
                output.push_str(line);
                output.push('\n');
                output.push_str("    // [oxicuda-debug] printf buffer parameter\n");
                output.push_str("    .param .u64 __oxicuda_printf_buf;\n");
                added_param = true;
                continue;
            }

            if trimmed.starts_with("// PRINTF") {
                output.push_str("    // [oxicuda-debug] printf store sequence\n");
                output.push_str("    ld.param.u64 %rd_pbuf, [__oxicuda_printf_buf];\n");
                output.push_str("    atom.global.add.u32 %r_poff, [%rd_pbuf], 1;\n");
            } else {
                output.push_str(line);
                output.push('\n');
            }
        }

        output
    }

    /// Remove all OxiCUDA debug instrumentation from PTX source.
    pub fn strip_debug(&self, ptx: &str) -> String {
        let mut output = String::with_capacity(ptx.len());
        let mut skip_next = false;

        for line in ptx.lines() {
            if skip_next {
                skip_next = false;
                continue;
            }

            let trimmed = line.trim();

            // Skip debug comment lines and the instruction immediately after.
            if trimmed.starts_with("// [oxicuda-debug]") {
                // Also skip the next instrumentation line.
                skip_next = true;
                continue;
            }

            // Skip debug parameter declarations.
            if trimmed.contains("__oxicuda_debug_buf") || trimmed.contains("__oxicuda_printf_buf") {
                continue;
            }

            output.push_str(line);
            output.push('\n');
        }

        output
    }
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // -- Config defaults --

    #[test]
    fn config_default_values() {
        let cfg = KernelDebugConfig::default();
        assert_eq!(cfg.debug_level, DebugLevel::Info);
        assert!(cfg.enable_bounds_check);
        assert!(cfg.enable_nan_check);
        assert!(cfg.enable_inf_check);
        assert!(!cfg.enable_race_detection);
        assert_eq!(cfg.print_buffer_size, 1024 * 1024);
        assert_eq!(cfg.max_print_per_thread, 32);
    }

    // -- KernelDebugger creation --

    #[test]
    fn debugger_creation_with_config() {
        let cfg = KernelDebugConfig {
            debug_level: DebugLevel::Trace,
            enable_bounds_check: false,
            ..KernelDebugConfig::default()
        };
        let debugger = KernelDebugger::new(cfg);
        assert_eq!(debugger.config().debug_level, DebugLevel::Trace);
        assert!(!debugger.config().enable_bounds_check);
    }

    // -- Session lifecycle --

    #[test]
    fn debug_session_lifecycle() {
        let cfg = KernelDebugConfig::default();
        let mut debugger = KernelDebugger::new(cfg);
        let session = debugger.attach("test_kernel");
        assert!(session.is_ok());
        let session = session.expect("session");
        assert_eq!(session.kernel_name(), "test_kernel");
        assert!(session.events().is_empty());

        // Attaching with empty name is an error.
        let err = debugger.attach("");
        assert!(err.is_err());
    }

    // -- Breakpoints --

    #[test]
    fn breakpoint_set_and_remove() {
        let mut debugger = KernelDebugger::new(KernelDebugConfig::default());
        let bp1 = debugger.set_breakpoint(42);
        let bp2 = debugger.set_breakpoint(100);
        assert_ne!(bp1, bp2);

        assert!(debugger.remove_breakpoint(bp1));
        // Removing again should return false.
        assert!(!debugger.remove_breakpoint(bp1));
        // bp2 should still be present.
        assert!(debugger.remove_breakpoint(bp2));
    }

    // -- Memory checker: valid access --

    #[test]
    fn memory_checker_valid_access() {
        let checker = MemoryChecker::new(vec![MemoryRegion {
            base_address: 0x1000,
            size: 256,
            name: "buf_a".into(),
            is_readonly: false,
        }]);
        // Read within bounds.
        assert!(checker.check_access(0x1000, 16, false).is_none());
        // Write within bounds.
        assert!(checker.check_access(0x1080, 32, true).is_none());
    }

    // -- Memory checker: OOB detection --

    #[test]
    fn memory_checker_out_of_bounds() {
        let checker = MemoryChecker::new(vec![MemoryRegion {
            base_address: 0x1000,
            size: 256,
            name: "buf_a".into(),
            is_readonly: false,
        }]);
        // Access past the end.
        let ev = checker.check_access(0x1100, 16, false);
        assert!(ev.is_some());
        let ev = ev.expect("oob event");
        assert!(matches!(ev.event_type, DebugEventType::OutOfBounds { .. }));

        // Completely outside.
        let ev2 = checker.check_access(0x5000, 4, true);
        assert!(ev2.is_some());
    }

    // -- NaN detection in f32 --

    #[test]
    fn nan_detection_f32() {
        let data = [1.0_f32, f32::NAN, 3.0, f32::NAN];
        let locs = NanInfChecker::check_f32(&data);
        assert_eq!(locs.len(), 2);
        assert_eq!(locs[0].index, 1);
        assert!(locs[0].is_nan);
        assert_eq!(locs[1].index, 3);
    }

    // -- Inf detection in f64 --

    #[test]
    fn inf_detection_f64() {
        let data = [1.0_f64, f64::INFINITY, f64::NEG_INFINITY, 4.0];
        let locs = NanInfChecker::check_f64(&data);
        assert_eq!(locs.len(), 2);
        assert!(!locs[0].is_nan);
        assert_eq!(locs[0].index, 1);
        assert!(!locs[1].is_nan);
        assert_eq!(locs[1].index, 2);
    }

    // -- Printf buffer parsing --

    #[test]
    fn printf_buffer_parsing() {
        let buf = PrintfBuffer::new(4096);

        // Build a raw buffer with one entry containing one Int arg.
        let mut raw = Vec::new();
        // entry_count = 1
        raw.extend_from_slice(&1_u32.to_le_bytes());
        // thread_id (1,0,0)
        raw.extend_from_slice(&1_u32.to_le_bytes());
        raw.extend_from_slice(&0_u32.to_le_bytes());
        raw.extend_from_slice(&0_u32.to_le_bytes());
        // block_id (0,0,0)
        raw.extend_from_slice(&0_u32.to_le_bytes());
        raw.extend_from_slice(&0_u32.to_le_bytes());
        raw.extend_from_slice(&0_u32.to_le_bytes());
        // format string "val=%d"
        let fmt = b"val=%d";
        raw.extend_from_slice(&(fmt.len() as u32).to_le_bytes());
        raw.extend_from_slice(fmt);
        // arg_count = 1
        raw.extend_from_slice(&1_u32.to_le_bytes());
        // tag=0 (Int), value=42
        raw.push(0);
        raw.extend_from_slice(&42_i64.to_le_bytes());

        let entries = buf.parse_entries(&raw);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].thread_id, (1, 0, 0));
        assert_eq!(entries[0].format_string, "val=%d");
        assert_eq!(entries[0].args.len(), 1);
        assert_eq!(entries[0].args[0], PrintfArg::Int(42));
    }

    // -- Assertions --

    #[test]
    fn assertion_checks() {
        // bounds: in range => None
        assert!(KernelAssertions::assert_bounds(5, 10, "arr").is_none());
        // bounds: out of range => Some
        let ev = KernelAssertions::assert_bounds(10, 10, "arr");
        assert!(ev.is_some());

        // NaN
        assert!(KernelAssertions::assert_not_nan(1.0, "x").is_none());
        assert!(KernelAssertions::assert_not_nan(f64::NAN, "x").is_some());

        // finite
        assert!(KernelAssertions::assert_finite(1.0, "x").is_none());
        assert!(KernelAssertions::assert_finite(f64::INFINITY, "x").is_some());
        assert!(KernelAssertions::assert_finite(f64::NAN, "x").is_some());

        // positive
        assert!(KernelAssertions::assert_positive(1.0, "x").is_none());
        assert!(KernelAssertions::assert_positive(0.0, "x").is_some());
        assert!(KernelAssertions::assert_positive(-1.0, "x").is_some());
        assert!(KernelAssertions::assert_positive(f64::NAN, "x").is_some());
    }

    // -- Event filtering --

    #[test]
    fn debug_event_filtering() {
        let cfg = KernelDebugConfig::default();
        let mut debugger = KernelDebugger::new(cfg);
        let mut session = debugger.attach("filter_test").expect("session");

        session.add_event(DebugEvent {
            event_type: DebugEventType::NanDetected {
                register: "f0".into(),
                value: f64::NAN,
            },
            thread_id: (0, 0, 0),
            block_id: (0, 0, 0),
            timestamp_ns: 100,
            message: "nan".into(),
        });
        session.add_event(DebugEvent {
            event_type: DebugEventType::OutOfBounds {
                address: 0xDEAD,
                size: 4,
            },
            thread_id: (1, 0, 0),
            block_id: (0, 0, 0),
            timestamp_ns: 200,
            message: "oob".into(),
        });
        session.add_event(DebugEvent {
            event_type: DebugEventType::NanDetected {
                register: "f1".into(),
                value: f64::NAN,
            },
            thread_id: (2, 0, 0),
            block_id: (0, 0, 0),
            timestamp_ns: 300,
            message: "nan2".into(),
        });

        let nans = session.filter_events(&DebugEventType::NanDetected {
            register: String::new(),
            value: 0.0,
        });
        assert_eq!(nans.len(), 2);

        let oobs = session.filter_events(&DebugEventType::OutOfBounds {
            address: 0,
            size: 0,
        });
        assert_eq!(oobs.len(), 1);
    }

    // -- Summary statistics --

    #[test]
    fn summary_statistics() {
        let cfg = KernelDebugConfig::default();
        let mut debugger = KernelDebugger::new(cfg);
        let mut session = debugger.attach("summary_test").expect("session");

        session.add_event(DebugEvent {
            event_type: DebugEventType::NanDetected {
                register: "f0".into(),
                value: f64::NAN,
            },
            thread_id: (0, 0, 0),
            block_id: (0, 0, 0),
            timestamp_ns: 0,
            message: String::new(),
        });
        session.add_event(DebugEvent {
            event_type: DebugEventType::InfDetected {
                register: "f1".into(),
            },
            thread_id: (0, 0, 0),
            block_id: (0, 0, 0),
            timestamp_ns: 0,
            message: String::new(),
        });
        session.add_event(DebugEvent {
            event_type: DebugEventType::OutOfBounds {
                address: 0x100,
                size: 4,
            },
            thread_id: (0, 0, 0),
            block_id: (0, 0, 0),
            timestamp_ns: 0,
            message: String::new(),
        });
        session.add_event(DebugEvent {
            event_type: DebugEventType::RaceCondition { address: 0x200 },
            thread_id: (0, 0, 0),
            block_id: (0, 0, 0),
            timestamp_ns: 0,
            message: String::new(),
        });

        let s = session.summary();
        assert_eq!(s.total_events, 4);
        assert_eq!(s.errors, 2); // OOB + race
        assert_eq!(s.warnings, 2); // NaN + Inf
        assert_eq!(s.nan_count, 1);
        assert_eq!(s.inf_count, 1);
        assert_eq!(s.oob_count, 1);
        assert_eq!(s.race_count, 1);
    }

    // -- Format report --

    #[test]
    fn format_report_output() {
        let cfg = KernelDebugConfig::default();
        let mut debugger = KernelDebugger::new(cfg);
        let mut session = debugger.attach("report_test").expect("session");

        session.add_event(DebugEvent {
            event_type: DebugEventType::NanDetected {
                register: "f0".into(),
                value: f64::NAN,
            },
            thread_id: (0, 0, 0),
            block_id: (0, 0, 0),
            timestamp_ns: 42,
            message: "NaN found".into(),
        });

        let report = session.format_report();
        assert!(report.contains("report_test"));
        assert!(report.contains("Total events: 1"));
        assert!(report.contains("NaN detected:  1"));
        assert!(report.contains("NaN found"));
        assert!(report.contains("=== End Report ==="));
    }

    // -- PTX instrumentation: bounds checks --

    #[test]
    fn ptx_instrumentation_bounds_checks() {
        let cfg = KernelDebugConfig::default();
        let inst = DebugPtxInstrumenter::new(&cfg);

        let ptx = ".entry my_kernel {\n    ld.global.f32 %f0, [%rd0];\n    ret;\n}\n";
        let result = inst.instrument_bounds_checks(ptx);

        assert!(result.contains("__oxicuda_debug_buf"));
        assert!(result.contains("setp.ge.u64"));
        assert!(result.contains("@%p_oob trap"));
    }

    // -- PTX strip debug --

    #[test]
    fn ptx_strip_debug_roundtrip() {
        let cfg = KernelDebugConfig::default();
        let inst = DebugPtxInstrumenter::new(&cfg);

        let original = ".entry kern {\n    add.f32 %f0, %f1, %f2;\n    ret;\n}\n";
        let instrumented = inst.instrument_nan_checks(original);
        assert!(instrumented.contains("[oxicuda-debug]"));

        let stripped = inst.strip_debug(&instrumented);
        // After stripping, no debug markers should remain.
        assert!(!stripped.contains("[oxicuda-debug]"));
        // Original instructions should still be present.
        assert!(stripped.contains("add.f32"));
        assert!(stripped.contains("ret;"));
    }
}