memf-linux 0.2.1

Linux kernel memory forensic walkers (processes, connections, modules)
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
//! Suspicious `perf_event` detection for Linux memory forensics.
//!
//! Walks each process's `perf_event_context` (via `task_struct.perf_event_ctxp[0]`)
//! and enumerates all attached `perf_event` structs. Hardware cache events and raw
//! PMU accesses are flagged as suspicious (Spectre/cache-timing attack patterns).

use memf_core::object_reader::ObjectReader;
use memf_format::PhysicalMemoryProvider;

use crate::Result;

/// Information about a single perf_event attached to a process.
#[derive(Debug, Clone, serde::Serialize)]
pub struct PerfEventInfo {
    /// PID of the owning process.
    pub pid: u32,
    /// Command name of the owning process.
    pub comm: String,
    /// PERF_TYPE_* constant.
    pub event_type: u32,
    /// Human-readable name for `event_type`.
    pub event_type_name: String,
    /// Event configuration (e.g. `PERF_COUNT_HW_CACHE_MISSES`).
    pub config: u64,
    /// Sample period set on the event.
    pub sample_period: u64,
    /// True when this event matches cache-side-channel or PMU-based attack patterns.
    pub is_suspicious: bool,
}

/// Map a `PERF_TYPE_*` constant to a human-readable name.
pub fn perf_type_name(t: u32) -> &'static str {
    match t {
        0 => "HARDWARE",
        1 => "SOFTWARE",
        2 => "TRACEPOINT",
        3 => "HW_CACHE",
        4 => "RAW",
        5 => "BREAKPOINT",
        _ => "UNKNOWN",
    }
}

/// Classify whether a perf_event represents a suspicious access pattern.
///
/// - `PERF_TYPE_HW_CACHE` (3) with config low byte <= 2 (L1D or LL cache) is
///   a known pattern used in cache-timing / Spectre attacks.
/// - `PERF_TYPE_RAW` (4) gives direct PMU counter access from userspace and is
///   always considered suspicious.
pub use crate::heuristics::classify_perf_event;

/// Walk all perf_events across all processes and return structured info.
///
/// Returns `Ok(Vec::new())` when `init_task` symbol or required ISF offsets
/// are absent (graceful degradation).
pub fn walk_perf_events<P: PhysicalMemoryProvider>(
    reader: &ObjectReader<P>,
) -> Result<Vec<PerfEventInfo>> {
    // Graceful degradation: require init_task symbol.
    let init_task_addr = match reader.symbols().symbol_address("init_task") {
        Some(addr) => addr,
        None => return Ok(Vec::new()),
    };

    // Require task_struct.tasks offset for process-list traversal.
    let tasks_offset = match reader.symbols().field_offset("task_struct", "tasks") {
        Some(off) => off,
        None => return Ok(Vec::new()),
    };

    // Require perf_event_ctxp offset for perf context pointer array.
    let ctxp_offset = match reader
        .symbols()
        .field_offset("task_struct", "perf_event_ctxp")
    {
        Some(off) => off,
        None => return Ok(Vec::new()),
    };

    let mut results = Vec::new();

    // Collect all task_struct addresses by walking the tasks list_head.
    let mut task_addrs: Vec<u64> = Vec::new();
    {
        let first_next: u64 = match reader.read_field(init_task_addr, "task_struct", "tasks") {
            Ok(v) => v,
            Err(_) => return Ok(Vec::new()),
        };
        let mut cursor = first_next;
        let mut guard = 0usize;
        loop {
            if cursor == 0 || guard > 65536 {
                break;
            }
            let task_addr = cursor.saturating_sub(tasks_offset);
            if task_addr == init_task_addr {
                break;
            }
            task_addrs.push(task_addr);
            cursor = match reader.read_field(cursor, "list_head", "next") {
                Ok(v) => v,
                Err(_) => break,
            };
            guard += 1;
        }
    }

    // Include init_task itself.
    let all_tasks = std::iter::once(init_task_addr).chain(task_addrs);

    for task_addr in all_tasks {
        let pid: u32 = reader
            .read_field::<u32>(task_addr, "task_struct", "pid")
            .unwrap_or(0);
        let comm_bytes: [u8; 16] = reader
            .read_field(task_addr, "task_struct", "comm")
            .unwrap_or([0u8; 16]);
        let comm = std::str::from_utf8(&comm_bytes)
            .unwrap_or("")
            .trim_end_matches('\0')
            .to_string();

        // Read perf_event_ctxp[0]: pointer stored at task_addr + ctxp_offset.
        let ctx_ptr_addr = task_addr + ctxp_offset;
        let ctx_ptr: u64 = match reader.read_bytes(ctx_ptr_addr, 8) {
            Ok(bytes) => u64::from_le_bytes(bytes.try_into().unwrap_or([0u8; 8])),
            Err(_) => continue,
        };
        if ctx_ptr == 0 {
            continue;
        }

        // Walk pinned_groups and flexible_groups list_heads of perf_event_context.
        for group_field in &["pinned_groups", "flexible_groups"] {
            let head_addr = match reader
                .symbols()
                .field_offset("perf_event_context", group_field)
            {
                Some(off) => ctx_ptr + off,
                None => continue,
            };

            let first_event_list: u64 = match reader.read_bytes(head_addr, 8) {
                Ok(b) => u64::from_le_bytes(b.try_into().unwrap_or([0u8; 8])),
                Err(_) => continue,
            };

            let event_group_node_offset =
                match reader.symbols().field_offset("perf_event", "group_entry") {
                    Some(off) => off,
                    None => continue,
                };

            let mut cursor = first_event_list;
            let mut guard = 0usize;
            loop {
                if cursor == 0 || cursor == head_addr || guard > 4096 {
                    break;
                }
                let event_addr = cursor.saturating_sub(event_group_node_offset);

                // perf_event.attr is embedded at ~0x20; type at attr+0, config at attr+8.
                let attr_offset: u64 = reader
                    .symbols()
                    .field_offset("perf_event", "attr")
                    .map_or(0x20, |o| o);

                let event_type: u32 = if let Ok(b) = reader.read_bytes(event_addr + attr_offset, 4)
                {
                    u32::from_le_bytes(b.try_into().unwrap_or([0u8; 4]))
                } else {
                    cursor = match reader.read_bytes(cursor, 8) {
                        Ok(b) => u64::from_le_bytes(b.try_into().unwrap_or([0u8; 8])),
                        Err(_) => break,
                    };
                    guard += 1;
                    continue;
                };

                let config: u64 = reader
                    .read_bytes(event_addr + attr_offset + 8, 8)
                    .ok()
                    .and_then(|b| b.try_into().ok())
                    .map_or(0, u64::from_le_bytes);

                let sample_period: u64 = reader
                    .read_bytes(event_addr + attr_offset + 16, 8)
                    .ok()
                    .and_then(|b| b.try_into().ok())
                    .map_or(0, u64::from_le_bytes);

                let is_suspicious = classify_perf_event(event_type, config);
                results.push(PerfEventInfo {
                    pid,
                    comm: comm.clone(),
                    event_type,
                    event_type_name: perf_type_name(event_type).to_string(),
                    config,
                    sample_period,
                    is_suspicious,
                });

                cursor = match reader.read_bytes(cursor, 8) {
                    Ok(b) => u64::from_le_bytes(b.try_into().unwrap_or([0u8; 8])),
                    Err(_) => break,
                };
                guard += 1;
            }
        }
    }

    Ok(results)
}

#[cfg(test)]
mod tests {
    use super::*;
    use memf_core::object_reader::ObjectReader;
    use memf_core::test_builders::{PageTableBuilder, SyntheticPhysMem};
    use memf_core::vas::{TranslationMode, VirtualAddressSpace};
    use memf_symbols::isf::IsfResolver;
    use memf_symbols::test_builders::IsfBuilder;

    fn make_no_symbol_reader() -> ObjectReader<SyntheticPhysMem> {
        let isf = IsfBuilder::new().build_json();
        let resolver = IsfResolver::from_value(&isf).unwrap();
        let (cr3, mem) = PageTableBuilder::new().build();
        let vas = VirtualAddressSpace::new(mem, cr3, TranslationMode::X86_64FourLevel);
        ObjectReader::new(vas, Box::new(resolver))
    }

    #[test]
    fn perf_type_name_hardware() {
        assert_eq!(perf_type_name(0), "HARDWARE");
    }

    #[test]
    fn perf_type_name_unknown() {
        assert_eq!(perf_type_name(99), "UNKNOWN");
    }

    #[test]
    fn classify_ll_cache_event_suspicious() {
        // PERF_TYPE_HW_CACHE (3), config low byte = 2 (PERF_COUNT_HW_CACHE_LL)
        assert!(
            classify_perf_event(3, 2),
            "LL cache event must be suspicious"
        );
    }

    #[test]
    fn classify_l1d_cache_event_suspicious() {
        // PERF_TYPE_HW_CACHE (3), config low byte = 0 (PERF_COUNT_HW_CACHE_L1D)
        assert!(
            classify_perf_event(3, 0),
            "L1D cache event must be suspicious"
        );
    }

    #[test]
    fn classify_software_event_not_suspicious() {
        assert!(
            !classify_perf_event(1, 0),
            "SOFTWARE event must not be suspicious"
        );
    }

    #[test]
    fn classify_raw_pmu_event_suspicious() {
        assert!(
            classify_perf_event(4, 0xDEAD),
            "RAW PMU event must be suspicious"
        );
    }

    #[test]
    fn classify_hardware_event_not_suspicious() {
        assert!(
            !classify_perf_event(0, 1),
            "plain HARDWARE event must not be suspicious"
        );
    }

    #[test]
    fn walk_perf_events_no_symbol_returns_empty() {
        let reader = make_no_symbol_reader();
        let result = walk_perf_events(&reader).unwrap();
        assert!(
            result.is_empty(),
            "no init_task symbol → empty vec expected"
        );
    }

    // --- perf_type_name exhaustive coverage ---

    #[test]
    fn perf_type_name_software() {
        assert_eq!(perf_type_name(1), "SOFTWARE");
    }

    #[test]
    fn perf_type_name_tracepoint() {
        assert_eq!(perf_type_name(2), "TRACEPOINT");
    }

    #[test]
    fn perf_type_name_hw_cache() {
        assert_eq!(perf_type_name(3), "HW_CACHE");
    }

    #[test]
    fn perf_type_name_raw() {
        assert_eq!(perf_type_name(4), "RAW");
    }

    #[test]
    fn perf_type_name_breakpoint() {
        assert_eq!(perf_type_name(5), "BREAKPOINT");
    }

    // --- classify_perf_event boundary and branch coverage ---

    #[test]
    fn classify_hw_cache_config_byte_1_suspicious() {
        // PERF_TYPE_HW_CACHE (3), config low byte = 1 (PERF_COUNT_HW_CACHE_L1I)
        assert!(
            classify_perf_event(3, 1),
            "HW_CACHE with config=1 must be suspicious"
        );
    }

    #[test]
    fn classify_hw_cache_config_byte_3_not_suspicious() {
        // low byte = 3 is > 2, so NOT suspicious
        assert!(
            !classify_perf_event(3, 3),
            "HW_CACHE with config byte = 3 must not be suspicious"
        );
    }

    #[test]
    fn classify_hw_cache_config_high_byte_not_suspicious() {
        // config = 0x0300 → low byte = 0, which IS <= 2 (suspicious)
        // But config = 0xFF03 → low byte = 3, not suspicious
        assert!(
            !classify_perf_event(3, 0xFF03),
            "HW_CACHE with low byte > 2 must not be suspicious"
        );
    }

    #[test]
    fn classify_tracepoint_not_suspicious() {
        assert!(
            !classify_perf_event(2, 0),
            "TRACEPOINT event must not be suspicious"
        );
    }

    #[test]
    fn classify_breakpoint_not_suspicious() {
        assert!(
            !classify_perf_event(5, 0),
            "BREAKPOINT event must not be suspicious"
        );
    }

    #[test]
    fn classify_unknown_type_not_suspicious() {
        assert!(
            !classify_perf_event(99, 0),
            "unknown event type must not be suspicious"
        );
    }

    // --- walk_perf_events: has init_task but no tasks field ---

    #[test]
    fn walk_perf_events_missing_tasks_offset_returns_empty() {
        let isf = IsfBuilder::new()
            .add_symbol("init_task", 0xFFFF_8888_0000_0000)
            .build_json();
        let resolver = IsfResolver::from_value(&isf).unwrap();
        let (cr3, mem) = PageTableBuilder::new().build();
        let vas = VirtualAddressSpace::new(mem, cr3, TranslationMode::X86_64FourLevel);
        let reader = ObjectReader::new(vas, Box::new(resolver));

        let result = walk_perf_events(&reader).unwrap();
        assert!(
            result.is_empty(),
            "missing task_struct.tasks offset → empty vec expected"
        );
    }

    // --- walk_perf_events: has init_task + tasks but no perf_event_ctxp ---

    #[test]
    fn walk_perf_events_missing_ctxp_offset_returns_empty() {
        let isf = IsfBuilder::new()
            .add_symbol("init_task", 0xFFFF_8888_0000_0000)
            .add_struct("task_struct", 512)
            .add_field("task_struct", "tasks", 8, "pointer")
            .build_json();
        let resolver = IsfResolver::from_value(&isf).unwrap();
        let (cr3, mem) = PageTableBuilder::new().build();
        let vas = VirtualAddressSpace::new(mem, cr3, TranslationMode::X86_64FourLevel);
        let reader = ObjectReader::new(vas, Box::new(resolver));

        let result = walk_perf_events(&reader).unwrap();
        assert!(
            result.is_empty(),
            "missing perf_event_ctxp offset → empty vec expected"
        );
    }

    // --- walk_perf_events: all symbols present, self-pointing tasks list → empty ---
    // Exercises the task-list traversal body and the perf-context branch.
    #[test]
    fn walk_perf_events_symbol_present_self_pointing_list_returns_empty() {
        use memf_core::test_builders::{flags as ptf, SyntheticPhysMem};

        // tasks field is at offset 0x10; perf_event_ctxp is at offset 0x20.
        // init_task.tasks.next must point back to init_task_addr + tasks_offset
        // so that the loop's "task_addr == init_task_addr" guard fires immediately.
        let tasks_offset: u64 = 0x10;
        let ctxp_offset: u64 = 0x20;

        let sym_vaddr: u64 = 0xFFFF_8800_0020_0000;
        let sym_paddr: u64 = 0x0040_0000; // unique paddr, < 16 MB

        let isf = IsfBuilder::new()
            .add_symbol("init_task", sym_vaddr)
            .add_struct("task_struct", 0x400)
            .add_field("task_struct", "tasks", tasks_offset, "pointer")
            .add_field("task_struct", "perf_event_ctxp", ctxp_offset, "pointer")
            .add_field("task_struct", "pid", 0x30, "unsigned int")
            .add_field("task_struct", "comm", 0x38, "char")
            .build_json();
        let resolver = IsfResolver::from_value(&isf).unwrap();

        // Build a page for init_task:
        // [tasks_offset+0..+8] = init_task_vaddr + tasks_offset  (self-pointing → empty list)
        // [ctxp_offset+0..+8]  = 0  (null ctx_ptr → loop skips perf context)
        let mut page = [0u8; 4096];
        let self_ptr = sym_vaddr + tasks_offset;
        page[tasks_offset as usize..tasks_offset as usize + 8]
            .copy_from_slice(&self_ptr.to_le_bytes());
        // ctxp already zero

        let (cr3, mem) = PageTableBuilder::new()
            .map_4k(sym_vaddr, sym_paddr, ptf::WRITABLE)
            .write_phys(sym_paddr, &page)
            .build();

        let vas = VirtualAddressSpace::new(mem, cr3, TranslationMode::X86_64FourLevel);
        let reader: ObjectReader<SyntheticPhysMem> = ObjectReader::new(vas, Box::new(resolver));

        let result = walk_perf_events(&reader).unwrap();
        assert!(
            result.is_empty(),
            "self-pointing tasks list with null ctx_ptr → no perf events"
        );
    }

    // --- walk_perf_events: non-null ctx_ptr, missing pinned_groups field → continues ---
    // Exercises the `continue` branch in the group_field loop when
    // perf_event_context.pinned_groups/flexible_groups offset is absent.
    #[test]
    fn walk_perf_events_missing_group_field_offsets_returns_empty() {
        use memf_core::test_builders::{flags as ptf, SyntheticPhysMem};

        let task_vaddr: u64 = 0xFFFF_8800_0030_0000;
        let ctx_vaddr: u64 = 0xFFFF_8800_0031_0000;

        let task_paddr: u64 = 0x041_000;
        let ctx_paddr: u64 = 0x042_000;

        let tasks_offset: u64 = 0x10;
        let ctxp_offset: u64 = 0x20;
        let pid_offset: u64 = 0x30;
        let comm_offset: u64 = 0x38;

        let isf = IsfBuilder::new()
            .add_symbol("init_task", task_vaddr)
            .add_struct("task_struct", 0x400)
            .add_field("task_struct", "tasks", tasks_offset, "pointer")
            .add_field("task_struct", "perf_event_ctxp", ctxp_offset, "pointer")
            .add_field("task_struct", "pid", pid_offset, "unsigned int")
            .add_field("task_struct", "comm", comm_offset, "char")
            // perf_event_context has NO pinned_groups or flexible_groups fields
            // → the inner loop continues immediately for both field names
            .add_struct("perf_event_context", 0x200)
            .build_json();
        let resolver = IsfResolver::from_value(&isf).unwrap();

        // init_task page: self-pointing tasks, ctxp = ctx_vaddr
        let mut task_page = [0u8; 4096];
        let self_ptr = task_vaddr + tasks_offset;
        task_page[tasks_offset as usize..tasks_offset as usize + 8]
            .copy_from_slice(&self_ptr.to_le_bytes());
        task_page[ctxp_offset as usize..ctxp_offset as usize + 8]
            .copy_from_slice(&ctx_vaddr.to_le_bytes());
        task_page[pid_offset as usize..pid_offset as usize + 4]
            .copy_from_slice(&777u32.to_le_bytes());

        // ctx page: all zeros (no events)
        let ctx_page = [0u8; 4096];

        let (cr3, mem) = PageTableBuilder::new()
            .map_4k(task_vaddr, task_paddr, ptf::WRITABLE)
            .write_phys(task_paddr, &task_page)
            .map_4k(ctx_vaddr, ctx_paddr, ptf::WRITABLE)
            .write_phys(ctx_paddr, &ctx_page)
            .build();

        let vas = VirtualAddressSpace::new(mem, cr3, TranslationMode::X86_64FourLevel);
        let reader: ObjectReader<SyntheticPhysMem> = ObjectReader::new(vas, Box::new(resolver));

        let result = walk_perf_events(&reader).unwrap();
        assert!(
            result.is_empty(),
            "missing group field offsets → inner loop continues → no events"
        );
    }

    // --- walk_perf_events: non-null ctx_ptr, pinned_groups present, empty group list ---
    // Exercises reading head_addr + first_event_list, then breaking because
    // cursor == head_addr immediately (self-pointing or zero list head).
    #[test]
    fn walk_perf_events_empty_group_list_returns_empty() {
        use memf_core::test_builders::{flags as ptf, SyntheticPhysMem};

        let task_vaddr: u64 = 0xFFFF_8800_0032_0000;
        let ctx_vaddr: u64 = 0xFFFF_8800_0033_0000;

        let task_paddr: u64 = 0x043_000;
        let ctx_paddr: u64 = 0x044_000;

        let tasks_offset: u64 = 0x10;
        let ctxp_offset: u64 = 0x20;
        let pid_offset: u64 = 0x30;
        let comm_offset: u64 = 0x38;

        // perf_event_context: pinned_groups@0x10, flexible_groups@0x18
        let pinned_offset: u64 = 0x10;
        let flexible_offset: u64 = 0x18;

        let isf = IsfBuilder::new()
            .add_symbol("init_task", task_vaddr)
            .add_struct("task_struct", 0x400)
            .add_field("task_struct", "tasks", tasks_offset, "pointer")
            .add_field("task_struct", "perf_event_ctxp", ctxp_offset, "pointer")
            .add_field("task_struct", "pid", pid_offset, "unsigned int")
            .add_field("task_struct", "comm", comm_offset, "char")
            .add_struct("perf_event_context", 0x200)
            .add_field(
                "perf_event_context",
                "pinned_groups",
                pinned_offset,
                "list_head",
            )
            .add_field(
                "perf_event_context",
                "flexible_groups",
                flexible_offset,
                "list_head",
            )
            .add_struct("perf_event", 0x200)
            .add_field("perf_event", "group_entry", 0u64, "list_head")
            .build_json();
        let resolver = IsfResolver::from_value(&isf).unwrap();

        let mut task_page = [0u8; 4096];
        let self_ptr = task_vaddr + tasks_offset;
        task_page[tasks_offset as usize..tasks_offset as usize + 8]
            .copy_from_slice(&self_ptr.to_le_bytes());
        task_page[ctxp_offset as usize..ctxp_offset as usize + 8]
            .copy_from_slice(&ctx_vaddr.to_le_bytes());
        task_page[pid_offset as usize..pid_offset as usize + 4]
            .copy_from_slice(&888u32.to_le_bytes());

        // ctx page: pinned_groups list head points to itself (empty list)
        let pinned_head = ctx_vaddr + pinned_offset;
        let flexible_head = ctx_vaddr + flexible_offset;
        let mut ctx_page = [0u8; 4096];
        ctx_page[pinned_offset as usize..pinned_offset as usize + 8]
            .copy_from_slice(&pinned_head.to_le_bytes());
        ctx_page[flexible_offset as usize..flexible_offset as usize + 8]
            .copy_from_slice(&flexible_head.to_le_bytes());

        let (cr3, mem) = PageTableBuilder::new()
            .map_4k(task_vaddr, task_paddr, ptf::WRITABLE)
            .write_phys(task_paddr, &task_page)
            .map_4k(ctx_vaddr, ctx_paddr, ptf::WRITABLE)
            .write_phys(ctx_paddr, &ctx_page)
            .build();

        let vas = VirtualAddressSpace::new(mem, cr3, TranslationMode::X86_64FourLevel);
        let reader: ObjectReader<SyntheticPhysMem> = ObjectReader::new(vas, Box::new(resolver));

        let result = walk_perf_events(&reader).unwrap();
        assert!(
            result.is_empty(),
            "self-pointing group list (empty) → no perf events enumerated"
        );
    }

    // --- walk_perf_events: init_task tasks read fails → returns empty ---
    // Exercises line 91-93: read_field(init_task_addr, "task_struct", "tasks") Err → Ok(Vec::new()).
    #[test]
    fn walk_perf_events_tasks_read_fails_returns_empty() {
        // init_task symbol present, tasks+ctxp offsets resolved, but the address is unmapped
        // so reading tasks pointer fails → early return Ok(Vec::new()).
        let isf = IsfBuilder::new()
            .add_symbol("init_task", 0xFFFF_DEAD_CAFE_0000) // unmapped
            .add_struct("task_struct", 0x400)
            .add_field("task_struct", "tasks", 0x10, "pointer")
            .add_field("task_struct", "perf_event_ctxp", 0x20, "pointer")
            .add_field("task_struct", "pid", 0x30, "unsigned int")
            .add_field("task_struct", "comm", 0x38, "char")
            .build_json();
        let resolver = IsfResolver::from_value(&isf).unwrap();
        let (cr3, mem) = PageTableBuilder::new().build();
        let vas = VirtualAddressSpace::new(mem, cr3, TranslationMode::X86_64FourLevel);
        let reader = ObjectReader::new(vas, Box::new(resolver));

        let result = walk_perf_events(&reader).unwrap();
        assert!(
            result.is_empty(),
            "unreadable init_task → early return empty"
        );
    }

    // --- walk_perf_events: non-empty tasks list AND event in group list ---
    // Exercises the task-list walking loop body (lines 97-111) by providing a
    // second task in the list, AND exercises the inner perf_event_context group
    // traversal body (lines 151-204) by placing one event in the pinned_groups list.
    #[test]
    fn walk_perf_events_one_task_with_one_event_in_pinned_groups() {
        use memf_core::test_builders::{flags as ptf, SyntheticPhysMem};

        // Memory layout (all physical addresses < 16 MB):
        //
        //  init_task @ init_vaddr / init_paddr
        //  task2     @ t2_vaddr   / t2_paddr      (linked in tasks list)
        //  ctx       @ ctx_vaddr  / ctx_paddr      (perf_event_context for task2)
        //  event     @ ev_vaddr   / ev_paddr       (perf_event in pinned_groups)
        //
        // tasks list offsets (inside task_struct):
        //   tasks         @ 0x10  (list_head, 8-byte next pointer)
        //   perf_event_ctxp @ 0x20 (pointer to ctx)
        //   pid           @ 0x30  (u32)
        //   comm          @ 0x38  (16 bytes)
        //
        // perf_event_context offsets:
        //   pinned_groups @ 0x00  (list_head — next pointer is first 8 bytes)
        //   flexible_groups @ 0x08
        //
        // perf_event offsets:
        //   group_entry @ 0x00  (list_head — node for pinned/flexible list)
        //   attr        @ 0x20  (perf_event_attr; type@+0 u32, config@+8 u64, sample_period@+16 u64)

        let tasks_offset: u64 = 0x10;
        let ctxp_offset: u64 = 0x20;
        let pid_offset: u64 = 0x30;
        let comm_offset: u64 = 0x38;

        let pinned_offset: u64 = 0x00;
        let flexible_offset: u64 = 0x08;

        let group_entry_offset: u64 = 0x00;
        let attr_offset: u64 = 0x20;

        let init_vaddr: u64 = 0xFFFF_8800_0080_0000;
        let init_paddr: u64 = 0x0080_0000;
        let t2_vaddr: u64 = 0xFFFF_8800_0081_0000;
        let t2_paddr: u64 = 0x0081_0000;
        let ctx_vaddr: u64 = 0xFFFF_8800_0082_0000;
        let ctx_paddr: u64 = 0x0082_0000;
        let ev_vaddr: u64 = 0xFFFF_8800_0083_0000;
        let ev_paddr: u64 = 0x0083_0000;

        // init_task page:
        //   tasks.next @ tasks_offset → t2_vaddr + tasks_offset  (points to task2's list node)
        //   ctxp       @ ctxp_offset  → 0  (no perf context for init)
        //   pid        @ pid_offset   → 0
        let mut init_page = [0u8; 4096];
        let t2_list_node = t2_vaddr + tasks_offset;
        init_page[tasks_offset as usize..tasks_offset as usize + 8]
            .copy_from_slice(&t2_list_node.to_le_bytes());
        // ctxp already 0

        // task2 page:
        //   tasks.next @ tasks_offset → init_vaddr + tasks_offset (wraps back → end of walk)
        //   ctxp       @ ctxp_offset  → ctx_vaddr
        //   pid        @ pid_offset   → 42
        //   comm       @ comm_offset  → "spy\0"
        let mut t2_page = [0u8; 4096];
        let init_list_node = init_vaddr + tasks_offset;
        t2_page[tasks_offset as usize..tasks_offset as usize + 8]
            .copy_from_slice(&init_list_node.to_le_bytes());
        t2_page[ctxp_offset as usize..ctxp_offset as usize + 8]
            .copy_from_slice(&ctx_vaddr.to_le_bytes());
        t2_page[pid_offset as usize..pid_offset as usize + 4].copy_from_slice(&42u32.to_le_bytes());
        t2_page[comm_offset as usize..comm_offset as usize + 3].copy_from_slice(b"spy");

        // perf_event_context page:
        //   pinned_groups (list_head) @ pinned_offset:
        //     next = ev_vaddr + group_entry_offset   (the event's group_entry node)
        //   flexible_groups @ flexible_offset:
        //     next = ctx_vaddr + flexible_offset     (self-pointer → empty flexible list)
        let mut ctx_page = [0u8; 4096];
        let ev_list_node = ev_vaddr + group_entry_offset;
        ctx_page[pinned_offset as usize..pinned_offset as usize + 8]
            .copy_from_slice(&ev_list_node.to_le_bytes());
        // When the inner loop advances from the event node, it reads cursor (ev_list_node)
        // first 8 bytes, which will be the event page offset 0 = the next in group_entry.
        // We make that point back to the pinned_groups head so the loop exits.
        // pinned head addr = ctx_vaddr + pinned_offset
        let pinned_head = ctx_vaddr + pinned_offset;
        let flex_head = ctx_vaddr + flexible_offset;
        ctx_page[flexible_offset as usize..flexible_offset as usize + 8]
            .copy_from_slice(&flex_head.to_le_bytes());

        // perf_event page:
        //   group_entry (list_head) @ group_entry_offset:
        //     first 8 bytes (next pointer) = pinned_head  (so loop exits after this event)
        //   attr @ attr_offset:
        //     type (u32 @ +0) = 4  (PERF_TYPE_RAW → suspicious)
        //     config (u64 @ +8) = 0xDEAD
        //     sample_period (u64 @ +16) = 1000
        let mut ev_page = [0u8; 4096];
        ev_page[group_entry_offset as usize..group_entry_offset as usize + 8]
            .copy_from_slice(&pinned_head.to_le_bytes());
        ev_page[attr_offset as usize..attr_offset as usize + 4]
            .copy_from_slice(&4u32.to_le_bytes()); // PERF_TYPE_RAW
        ev_page[attr_offset as usize + 8..attr_offset as usize + 16]
            .copy_from_slice(&0xDEADu64.to_le_bytes());
        ev_page[attr_offset as usize + 16..attr_offset as usize + 24]
            .copy_from_slice(&1000u64.to_le_bytes());

        let isf = IsfBuilder::new()
            .add_symbol("init_task", init_vaddr)
            // list_head required by walk_list internals
            .add_struct("list_head", 0x10)
            .add_field("list_head", "next", 0x00u64, "pointer")
            .add_struct("task_struct", 0x400)
            .add_field("task_struct", "tasks", tasks_offset, "pointer")
            .add_field("task_struct", "perf_event_ctxp", ctxp_offset, "pointer")
            .add_field("task_struct", "pid", pid_offset, "unsigned int")
            .add_field("task_struct", "comm", comm_offset, "char")
            .add_struct("perf_event_context", 0x200)
            .add_field(
                "perf_event_context",
                "pinned_groups",
                pinned_offset,
                "list_head",
            )
            .add_field(
                "perf_event_context",
                "flexible_groups",
                flexible_offset,
                "list_head",
            )
            .add_struct("perf_event", 0x200)
            .add_field("perf_event", "group_entry", group_entry_offset, "list_head")
            .add_field("perf_event", "attr", attr_offset, "pointer")
            .build_json();
        let resolver = IsfResolver::from_value(&isf).unwrap();

        let (cr3, mem) = PageTableBuilder::new()
            .map_4k(init_vaddr, init_paddr, ptf::WRITABLE)
            .write_phys(init_paddr, &init_page)
            .map_4k(t2_vaddr, t2_paddr, ptf::WRITABLE)
            .write_phys(t2_paddr, &t2_page)
            .map_4k(ctx_vaddr, ctx_paddr, ptf::WRITABLE)
            .write_phys(ctx_paddr, &ctx_page)
            .map_4k(ev_vaddr, ev_paddr, ptf::WRITABLE)
            .write_phys(ev_paddr, &ev_page)
            .build();

        let vas = VirtualAddressSpace::new(mem, cr3, TranslationMode::X86_64FourLevel);
        let reader: ObjectReader<SyntheticPhysMem> = ObjectReader::new(vas, Box::new(resolver));

        let result = walk_perf_events(&reader).unwrap();
        // Must find exactly one event (RAW PMU on task2/pid=42/"spy")
        assert_eq!(
            result.len(),
            1,
            "expected one perf_event from task2's pinned_groups"
        );
        assert_eq!(result[0].pid, 42);
        assert_eq!(result[0].comm, "spy");
        assert_eq!(result[0].event_type, 4); // PERF_TYPE_RAW
        assert_eq!(result[0].config, 0xDEAD);
        assert_eq!(result[0].sample_period, 1000);
        assert!(
            result[0].is_suspicious,
            "RAW PMU event must be flagged suspicious"
        );
    }

    // --- walk_perf_events: PerfEventInfo serialization ---
    #[test]
    fn perf_event_info_serializes() {
        let info = PerfEventInfo {
            pid: 12,
            comm: "spy".to_string(),
            event_type: 4,
            event_type_name: "RAW".to_string(),
            config: 0xDEAD,
            sample_period: 1000,
            is_suspicious: true,
        };
        let json = serde_json::to_string(&info).unwrap();
        assert!(json.contains("\"pid\":12"));
        assert!(json.contains("RAW"));
        assert!(json.contains("\"is_suspicious\":true"));
    }
}