ktstr 0.17.0

Test harness for Linux process schedulers
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
use super::*;

// ----- BTF type edge cases ------------------------------------

/// `struct_member_at` skips bitfield members (members with
/// `bitfield_size > 0`) even when their byte offset matches the
/// query. A LDX through a `Pointer{T}` register at the bitfield's
/// byte offset must NOT seed a `LoadedU64Field` state, so no
/// pattern accumulates and no cast emits.
#[test]
fn struct_member_at_skips_bitfield_at_target_offset() {
    // BTF: u64(1), T(kind_flag=1) with a u64 bitfield at byte
    // offset 8 (bitfield_size = 32 bits). The byte offset matches
    // the LDX target but the bitfield_size > 0 makes
    // struct_member_at return None.
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_f = push_name(&mut strings, "f");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::StructBitfields {
            name_off: n_t,
            size: 16,
            members: vec![SynMemberBits {
                name_off: n_f,
                type_id: 1,
                bit_offset: 8 * 8,      // byte offset 8
                bitfield_size_bits: 32, // bitfield -> skip
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    // r2 = *(u64*)(r1 + 8): handle_ldx queries struct_member_at(T, 8).
    // The bitfield at 8 is skipped; struct_member_at returns None;
    // r2 becomes Unknown; no LoadedU64Field; no pattern recorded.
    // r3 = *(u64*)(r2 + 0) on Unknown source records nothing.
    let insns = vec![ldx(BPF_SIZE_DW, 2, 1, 8), ldx(BPF_SIZE_DW, 3, 2, 0), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "bitfield at target offset must not seed cast: {map:?}"
    );
}

/// `struct_member_at` skips members whose bit offset is not a
/// multiple of 8 (`bit_off % 8 != 0`) -- bit-position members
/// inside a kind_flag=1 struct that happen to lie between byte
/// boundaries cannot serve as a u64 LDX source. Even though the
/// byte derived from the bit position would round to the LDX
/// target offset, the alignment guard rejects.
#[test]
fn struct_member_at_skips_non_byte_aligned_member() {
    // T (kind_flag=1) with a u64 member at bit_offset = 65 (NOT
    // a multiple of 8; integer-divided by 8 gives byte 8). The
    // alignment guard rejects regardless of bitfield_size_bits.
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_f = push_name(&mut strings, "f");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::StructBitfields {
            name_off: n_t,
            size: 24,
            members: vec![SynMemberBits {
                name_off: n_f,
                type_id: 1,
                bit_offset: 65,        // NOT a multiple of 8
                bitfield_size_bits: 0, // not a bitfield
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    // r2 = *(u64*)(r1 + 8): struct_member_at scans T's members,
    // sees bit_offset 65 % 8 = 1, skips. r2 stays Unknown.
    let insns = vec![ldx(BPF_SIZE_DW, 2, 1, 8), ldx(BPF_SIZE_DW, 3, 2, 0), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "non-byte-aligned member must not seed cast: {map:?}"
    );
}

/// `member_size_bytes` returns `None` for terminal types whose
/// size is not resolvable from BTF alone (Func, FuncProto, Void,
/// Fwd, Var, Datasec). The `build_layout_index` loop must handle
/// `None` by skipping the member rather than panicking. Stress
/// the path by constructing a candidate struct whose members
/// include one each of Fwd, Func, and Void; the matcher must not
/// include those member positions in the (offset, size) layout
/// map. Without this guard the matcher would either crash on the
/// `expect`-style unwrap or emit a candidate the renderer cannot
/// chase.
#[test]
fn member_size_bytes_unsupported_terminals_skipped() {
    // BTF:
    //   id 1: u64
    //   id 2: T   { u64 f @ 8 }       -- source struct
    //   id 3: Fwd struct (kind_flag=0)
    //   id 4: FuncProto returning void, no params
    //   id 5: Func -> id 4
    //   id 6: U  { fwd_ref @ 0; func_ref @ 8; void_ref @ 16; u64 v @ 24 }
    //
    //   The members typed as Fwd / Func / Void all return None
    //   from member_size_bytes, so layout_index for U skips them.
    //   The single u64 at offset 24 makes U a candidate at
    //   (offset=24, size=8) ONLY. The LDX pattern accesses
    //   offset=24 (size 8); intersection -> {U}.
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_u = push_name(&mut strings, "U");
    let n_fwd_target = push_name(&mut strings, "fwd_struct");
    let n_func = push_name(&mut strings, "fn");
    let n_fwd_ref = push_name(&mut strings, "fwd_ref");
    let n_func_ref = push_name(&mut strings, "func_ref");
    let n_void_ref = push_name(&mut strings, "void_ref");
    let n_v = push_name(&mut strings, "v");
    let n_f = push_name(&mut strings, "f");
    let types = vec![
        // id 1: u64
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        // id 2: source T { u64 f @ 8 }
        SynType::Struct {
            name_off: n_t,
            size: 16,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        // id 3: Fwd (struct).
        SynType::Fwd {
            name_off: n_fwd_target,
            kind_flag: 0,
        },
        // id 4: FuncProto -> void, no params.
        SynType::FuncProto {
            return_type_id: 0,
            params: vec![],
        },
        // id 5: Func -> id 4.
        SynType::Func {
            name_off: n_func,
            type_id: 4,
            linkage: 1,
        },
        // id 6: U with members of unsupported sizes plus one
        // sized u64 member. Production must skip the unsupported
        // ones and include only (offset=24, size=8).
        SynType::Struct {
            name_off: n_u,
            size: 32,
            members: vec![
                SynMember {
                    name_off: n_fwd_ref,
                    type_id: 3, // Fwd -> None size
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_func_ref,
                    type_id: 5, // Func -> None size
                    byte_offset: 8,
                },
                SynMember {
                    name_off: n_void_ref,
                    type_id: 0, // Void -> None size
                    byte_offset: 16,
                },
                SynMember {
                    name_off: n_v,
                    type_id: 1, // u64 -> Some(8)
                    byte_offset: 24,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let u_id = 6;
    // r2 = *(u64*)(r1 + 8); cast r2 (arena evidence); r3 =
    // *(u64*)(r2 + 24). The pattern (offset=24, size=8) must
    // intersect to {U} only -- Fwd / Func / Void members at
    // offsets 0/8/16 are skipped during layout indexing.
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 24),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: u_id,
            addr_space: AddrSpace::Arena,
        }),
        "unsupported terminals must be skipped without crashing: {map:?}"
    );
}

/// `build_layout_index` skips bitfield members (those with
/// `bitfield_size > 0`). A struct whose only u64 sits as a
/// bitfield does NOT register in the (offset, size) layout map,
/// so it cannot be a candidate even when the access pattern
/// "would" match its byte position. The matcher converges on the
/// struct that has a NON-bitfield member at the queried position.
#[test]
fn build_layout_index_skips_bitfields_in_candidates() {
    // BTF: u64(1), T(2, u64@8) source. Q1(3, kind_flag=1) with a
    // u64 BITFIELD at byte 0 (size 32 bits) -- must NOT register
    // as a candidate. Q2(4) with a u64 NON-bitfield at byte 0 --
    // sole candidate. Pattern (offset=0, size=8) -> {Q2} only.
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_q1 = push_name(&mut strings, "Q1");
    let n_q2 = push_name(&mut strings, "Q2");
    let n_f = push_name(&mut strings, "f");
    let n_a = push_name(&mut strings, "a");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        // T has u64@8 source field.
        SynType::Struct {
            name_off: n_t,
            size: 16,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        // Q1 (kind_flag=1) with bitfield u64 at byte 0
        // (bitfield_size = 32 bits). Production must skip during
        // layout indexing because bitfield_size > 0.
        SynType::StructBitfields {
            name_off: n_q1,
            size: 8,
            members: vec![SynMemberBits {
                name_off: n_a,
                type_id: 1,
                bit_offset: 0,
                bitfield_size_bits: 32,
            }],
        },
        // Q2 with a normal u64 at byte 0 -- included in layout.
        SynType::Struct {
            name_off: n_q2,
            size: 8,
            members: vec![SynMember {
                name_off: n_a,
                type_id: 1,
                byte_offset: 0,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let q2_id = 4;
    // Sequence: r2 = *(u64*)(r1 + 8); cast r2 (arena evidence);
    // r3 = *(u64*)(r2 + 0).
    // Pattern (0, 8): layout includes Q2 only (Q1's bitfield
    // skipped). Map records (T, 8) -> (Q2, Arena).
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q2_id,
            addr_space: AddrSpace::Arena,
        }),
        "bitfield candidate must be skipped: {map:?}"
    );
}

/// `BTF_KIND_UNION` participates in `build_layout_index` and
/// `struct_member_at` identically to `BTF_KIND_STRUCT` -- `btf-rs`
/// aliases `Union = Struct`, and production matches both via
/// `Type::Struct(s) | Type::Union(s)`. Verify a kptr STX through
/// a parent typed as a union records correctly, AND a candidate
/// search resolves to a union when its layout uniquely matches.
#[test]
fn union_works_like_struct_for_layout_and_member_lookup() {
    // BTF:
    //   id 1: u64
    //   id 2: T (struct, kptr target) { u64 x @ 0 }
    //   id 3: T*
    //   id 4: P (UNION) { u64 slot @ 16 }
    //   id 5: SourceU (struct) { u64 f @ 8 }
    //   id 6: TargetU (UNION) { u64 a @ 0 } -- candidate target
    //
    // Two checks in one test:
    //   (a) STX through a Pointer{P=union} into P.slot at offset
    //       16 records (P, 16) -> T (Kernel).
    //   (b) LDX through a SourceU producing LoadedU64Field then
    //       deref at offset 0 (size 8) finds TargetU (the only
    //       struct/union with u64@0 in this BTF after dropping
    //       SourceU which has u64@8 not u64@0).
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_p = push_name(&mut strings, "P");
    let n_su = push_name(&mut strings, "SourceU");
    let n_tu = push_name(&mut strings, "TargetU");
    let n_x = push_name(&mut strings, "x");
    let n_slot = push_name(&mut strings, "slot");
    let n_f = push_name(&mut strings, "f");
    let n_a = push_name(&mut strings, "a");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        // T has its u64 at offset 8 (NOT 0) so layout(0, 8) is
        // uniquely satisfied by TargetU below — production must
        // converge on TargetU only when intersecting candidates.
        SynType::Struct {
            name_off: n_t,
            size: 16,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        SynType::Ptr { type_id: 2 }, // id 3: T*
        // id 4: P as a UNION with a u64 slot at byte 16.
        SynType::Union {
            name_off: n_p,
            size: 24,
            members: vec![SynMember {
                name_off: n_slot,
                type_id: 1,
                byte_offset: 16,
            }],
        },
        // id 5: SourceU as a struct with u64 source field at
        // offset 8.
        SynType::Struct {
            name_off: n_su,
            size: 16,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        // id 6: TargetU as a UNION with u64 a at offset 0. Sole
        // candidate for the (0, 8) access pattern (after dropping
        // the source struct SourceU which has u64@8 not u64@0).
        // Ensures the layout index walks Union the same as Struct.
        SynType::Union {
            name_off: n_tu,
            size: 8,
            members: vec![SynMember {
                name_off: n_a,
                type_id: 1,
                byte_offset: 0,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let p_id = 4;
    let source_u_id = 5;
    let target_u_id = 6;
    // Block 1: kptr through union parent.
    //   r1 = Pointer{P=union}; r6 = Pointer{T}.
    //   *(u64*)(r1 + 16) = r6  -> kptr_findings[(P,16)] = T.
    // Block 2: arena LDX through union target.
    //   r2 = Pointer{SourceU}; r3 = *(u64*)(r2 + 8); r4 = *(u64*)(r3 + 0).
    //   Pattern (0, 8) -> {TargetU}; (SourceU, 8) -> (TargetU, Arena).
    // Add arena_confirmed evidence (arena evidence) on r3 between the load
    // of SourceU.f and the deref through it.
    let insns = vec![
        stx(BPF_SIZE_DW, 1, 6, 16),
        ldx(BPF_SIZE_DW, 3, 2, 8),
        addr_space_cast(3, 3, 1),
        ldx(BPF_SIZE_DW, 4, 3, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: p_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 2,
                struct_type_id: source_u_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(p_id, 16)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "kptr through union parent must record: {map:?}"
    );
    assert_eq!(
        map.get(&(source_u_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: target_u_id,
            addr_space: AddrSpace::Arena,
        }),
        "union target must be a layout candidate: {map:?}"
    );
}

/// `build_layout_index`'s walk advances type ids `1..=max_id`
/// using `consecutive_fail` to short-circuit pathological /
/// synthesized BTFs. After 256 consecutive failed
/// `resolve_type_by_id` calls the loop breaks. To exercise this
/// path the test relies on the fact that `max_seen_type_id +
/// CANDIDATE_SEARCH_SLACK` (= 65538 here) is far above the
/// legitimate ids in the BTF, so the walk WOULD iterate ~65k
/// failed lookups without the cap; the consecutive fail cap of
/// 256 short-circuits early. Verify that:
///   - the matcher still finds the legitimate candidate (loop
///     visits valid ids before the cap kicks in),
///   - the matcher does not panic when many failed ids accumulate.
#[test]
fn build_layout_index_consecutive_fail_cap_short_circuits() {
    // BTF: u64(1), T(2, u64@8 source), Q(3, u64@0 unique target).
    // Type ids 4..=65538 would all fail -- production stops after
    // 256 consecutive fails. The legitimate candidate at id 3 is
    // found before the cap activates, so the cast still emits.
    let (blob, t_id, q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    // Even though ids 4..=65538 (max_seen=2 + slack=65536) all
    // resolve to errors, the consecutive_fail cap (256) stops the
    // loop early without panic, and Q(3) is recorded normally.
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "valid candidate must be found before fail cap; sparse \
             BTF must not panic: {map:?}"
    );
}

/// Non-bitfield members (`bitfield_size_bits = 0`) inside a
/// `kind_flag=1` struct ARE included in `build_layout_index`. The
/// production guard
/// `matches!(m.bitfield_size(), Some(s) if s > 0)` only matches
/// when the size is strictly positive. With kind_flag=1 every
/// member exposes `bitfield_size = Some(0)` for non-bitfield
/// members; production must NOT skip them.
#[test]
fn kind_flag_struct_includes_non_bitfield_members() {
    // BTF:
    //   id 1: u64
    //   id 2: T (kind_flag=0) { u64 src @ 8 }   -- source struct
    //   id 3: Q (kind_flag=1) { u64 a @ 0,
    //                            bf u64 b @ 64 (bitfield 32) }
    // Q has a non-bitfield u64 at byte 0. Production must include
    // it in layout (kind_flag=1, but bitfield_size=Some(0) since
    // bitfield_size_bits=0). The bitfield member at byte 8 is
    // skipped (bitfield_size_bits=32 > 0). Pattern (0, 8) -> {Q}.
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_q = push_name(&mut strings, "Q");
    let n_src = push_name(&mut strings, "src");
    let n_a = push_name(&mut strings, "a");
    let n_b = push_name(&mut strings, "b");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 16,
            members: vec![SynMember {
                name_off: n_src,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        // Q (kind_flag=1) has a non-bitfield u64 at byte 0 AND a
        // bitfield u64 at byte 8 (32-bit field). The non-bitfield
        // member must remain in layout despite kind_flag=1.
        SynType::StructBitfields {
            name_off: n_q,
            size: 16,
            members: vec![
                SynMemberBits {
                    name_off: n_a,
                    type_id: 1,
                    bit_offset: 0,
                    bitfield_size_bits: 0,
                },
                SynMemberBits {
                    name_off: n_b,
                    type_id: 1,
                    bit_offset: 64,
                    bitfield_size_bits: 32,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let q_id = 3;
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "non-bitfield member of kind_flag=1 struct must be a \
             layout candidate: {map:?}"
    );
}

// ----- Stack edge cases ---------------------------------------

/// `handle_stx`'s r10 spill guard treats a store with `off >= 0`
/// as out-of-spec for BPF (the stack grows DOWN; slots live at
/// negative offsets). The guard removes any prior slot at that
/// offset rather than saving state. Symmetrically, `handle_ldx`'s
/// r10 reload guard rejects loads with `off >= 0` and produces
/// Unknown. Verify the STX path's invalidation: a write with
/// `off >= 0` through r10 must remove any previously saved slot
/// state at that offset so a later DW reload returns Unknown.
#[test]
fn stack_off_non_negative_through_r10_invalidates() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // *(u64 *)(r10 + 0) = R1   ; off >= 0 spill: dropped, no
    //                            ; state saved at slot 0
    // R3 = *(u64 *)(r10 + 0)   ; off >= 0 reload: returns Unknown
    // *(u64 *)(R6 + slot_off) = R3
    //                          ; R3 Unknown -> no kptr finding
    let insns = vec![
        stx(BPF_SIZE_DW, 10, 1, 0),
        ldx(BPF_SIZE_DW, 3, 10, 0),
        stx(BPF_SIZE_DW, 6, 3, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "non-negative r10 store must not save state, reload \
             returns Unknown: {map:?}"
    );
}

/// `field_byte_offset` returns `None` for negative offsets when
/// the base register is NOT r10 (stack-relative loads are handled
/// separately via the r10 fast path). On a struct-pointer base,
/// a negative `off` is undefined behavior -- kernel struct fields
/// have non-negative byte offsets relative to the struct base.
/// Production drops dst to Unknown via
/// `field_byte_offset(off) -> None` and the LDX records nothing.
#[test]
fn negative_off_in_non_r10_context_drops() {
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    // r2 = *(u64 *)(r1 - 8): r1 is Pointer{T}, NOT r10. Negative
    // off goes to the Pointer arm of handle_ldx and produces
    // None in field_byte_offset, dropping dst to Unknown. No
    // pattern recorded.
    // r3 = *(u64 *)(r2 + 0): r2 Unknown -> no record.
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, -8),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "negative offset through Pointer{{T}} must drop, no \
             pattern recorded: {map:?}"
    );
}

/// Two consecutive STX-through-r10 spills with the SAME source
/// register state (Pointer{T}) overwrite the slot with a value
/// indistinguishable from the prior contents. Production stores
/// the second spill via `self.stack_slots.insert(off, regs[src])`
/// which replaces by key but does not collapse to Conflicting.
/// A later reload restores the same Pointer{T}; a subsequent STX
/// of the reloaded register into a parent slot must record the
/// kptr finding as `Single(T)` -- NOT `Conflicting`.
#[test]
fn stack_spill_same_target_stays_single() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // *(u64 *)(r10 - 8) = R1   ; spill Pointer{T} (slot=Pointer{T})
    // *(u64 *)(r10 - 8) = R1   ; spill Pointer{T} again -- same
    //                            ; target type, slot replaced
    //                            ; with same value, NOT Conflicting
    // R3 = *(u64 *)(r10 - 8)   ; reload as Pointer{T}
    // *(u64 *)(R6 + slot_off) = R3
    //                          ; records (P, slot_off) -> T
    let insns = vec![
        stx(BPF_SIZE_DW, 10, 1, -8),
        stx(BPF_SIZE_DW, 10, 1, -8),
        ldx(BPF_SIZE_DW, 3, 10, -8),
        stx(BPF_SIZE_DW, 6, 3, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(p_id, slot_off)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "spill of identical Pointer{{T}} must reload as Pointer{{T}}, \
             kptr stays Single: {map:?}"
    );
}

// ----- kfunc edge cases ---------------------------------------

/// `handle_kfunc_call` walks the FuncProto's return type through
/// `bpf_map::resolve_to_struct_id`. A return type that resolves
/// to a non-struct pointer (e.g. `int *`, `void *`) yields `None`
/// from the resolver, so R0 stays Unknown. A subsequent STX of
/// R0 into a u64 slot must NOT record a kptr finding.
#[test]
fn kfunc_call_returning_int_ptr_leaves_r0_unknown() {
    let slot_off: u32 = 16;
    // BTF:
    //   id 1: u64
    //   id 2: P (struct with u64 slot @ slot_off) -- kptr parent
    //         seed type for the post-call STX
    //   id 3: int* (Ptr -> u64). Pointee peels to Type::Int, so
    //         resolve_to_struct_id returns None.
    //   id 4: FuncProto returning id 3 (int*)
    //   id 5: Func -> id 4
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_p = push_name(&mut strings, "P");
    let n_slot = push_name(&mut strings, "slot");
    let n_kfunc = push_name(&mut strings, "bpf_returns_int_ptr");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_p,
            size: slot_off + 8,
            members: vec![SynMember {
                name_off: n_slot,
                type_id: 1,
                byte_offset: slot_off,
            }],
        },
        SynType::Ptr { type_id: 1 }, // id 3: u64*
        SynType::FuncProto {
            return_type_id: 3,
            params: vec![],
        },
        SynType::Func {
            name_off: n_kfunc,
            type_id: 4,
            linkage: 1,
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let p_id = 2;
    let kfunc_id = 5;
    // call kfunc returning int*; *(P + slot) = R0. R0 must be
    // Unknown (the return type's pointee resolves to Int, not
    // Struct, so resolve_to_struct_id returns None).
    let insns = vec![
        kfunc_call(kfunc_id),
        stx(BPF_SIZE_DW, 6, 0, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: p_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "kfunc returning int* must leave R0 Unknown: {map:?}"
    );
}

/// `handle_kfunc_call` short-circuits when the FuncProto's
/// `return_type_id == 0` (void return). R0 stays Unknown after
/// the standard r0..r5 clobber. A subsequent STX of R0 into a
/// u64 slot must NOT record a kptr finding.
#[test]
fn kfunc_call_void_return_leaves_r0_unknown() {
    let slot_off: u32 = 16;
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_p = push_name(&mut strings, "P");
    let n_slot = push_name(&mut strings, "slot");
    let n_kfunc = push_name(&mut strings, "bpf_void_return");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_p,
            size: slot_off + 8,
            members: vec![SynMember {
                name_off: n_slot,
                type_id: 1,
                byte_offset: slot_off,
            }],
        },
        // id 3: FuncProto -> void (return_type_id = 0).
        SynType::FuncProto {
            return_type_id: 0,
            params: vec![],
        },
        // id 4: Func -> id 3.
        SynType::Func {
            name_off: n_kfunc,
            type_id: 3,
            linkage: 1,
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let p_id = 2;
    let kfunc_id = 4;
    let insns = vec![
        kfunc_call(kfunc_id),
        stx(BPF_SIZE_DW, 6, 0, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: p_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "kfunc with void return must leave R0 Unknown: {map:?}"
    );
}

/// `handle_kfunc_call`'s `imm` may resolve directly to a
/// `Type::FuncProto` (no `Type::Func` wrapper). Production peels
/// `Type::Func -> Type::FuncProto` when needed but also accepts a
/// FuncProto id directly. A kfunc call with `imm` == FuncProto id
/// must seed R0 from the proto's return type just as it would
/// from a Func wrapper.
#[test]
fn kfunc_call_with_funcproto_id_directly() {
    let slot_off: u32 = 16;
    // BTF:
    //   id 1: u64
    //   id 2: T (kptr target struct) { u64 x @ 0 }
    //   id 3: T*
    //   id 4: P (struct holding the kptr slot)
    //   id 5: FuncProto -> T*  (no Func wrapper)
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_p = push_name(&mut strings, "P");
    let n_x = push_name(&mut strings, "x");
    let n_slot = push_name(&mut strings, "slot");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Ptr { type_id: 2 }, // id 3: T*
        SynType::Struct {
            name_off: n_p,
            size: slot_off + 8,
            members: vec![SynMember {
                name_off: n_slot,
                type_id: 1,
                byte_offset: slot_off,
            }],
        },
        // id 5: FuncProto returning T* -- pass id=5 directly to
        // kfunc_call's imm so the resolver hits the Type::FuncProto
        // arm, not Type::Func -> peel.
        SynType::FuncProto {
            return_type_id: 3,
            params: vec![],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let p_id = 4;
    let proto_id = 5;
    // kfunc call with imm = proto_id (id 5 = FuncProto). R0 must
    // be set to Pointer{T} via the FuncProto-direct path.
    let insns = vec![
        kfunc_call(proto_id),
        stx(BPF_SIZE_DW, 6, 0, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: p_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(p_id, slot_off)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "kfunc with direct FuncProto id must seed R0 from return \
             type: {map:?}"
    );
}