-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathtest_struct_ops.ml
More file actions
1481 lines (1234 loc) · 55.6 KB
/
Copy pathtest_struct_ops.ml
File metadata and controls
1481 lines (1234 loc) · 55.6 KB
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
(*
* Copyright 2025 Multikernel Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*)
open Alcotest
open Kernelscript
open Ast
open Printf
(** Helper function to check if string contains substring *)
let contains_substr str substr =
try ignore (Str.search_forward (Str.regexp_string substr) str 0); true
with Not_found -> false
(** Test basic @struct_ops attribute parsing *)
let test_struct_ops_parsing () =
let program = {|
@struct_ops("tcp_congestion_ops")
struct MyTcpCong {
init: u32,
release: u32
}
fn main() -> i32 {
var tcp_ops = MyTcpCong { init: 1, release: 2 }
var result = register(tcp_ops)
return result
}
|} in
let ast = Parse.parse_string program in
(* Check that we have the expected declarations *)
check int "Number of declarations" 2 (List.length ast);
(* Check that the first declaration is a struct with @struct_ops attribute *)
(match List.hd ast with
| StructDecl struct_def ->
check string "Struct name" "MyTcpCong" struct_def.struct_name;
(match struct_def.struct_attributes with
| [AttributeWithArg (attr_name, attr_param)] ->
check string "Attribute name" "struct_ops" attr_name;
check string "Attribute parameter" "tcp_congestion_ops" attr_param
| _ -> fail "Expected single struct_ops attribute")
| _ -> fail "Expected StructDecl")
(** Test regular struct without @struct_ops attribute *)
let test_regular_struct_parsing () =
let program = {|
struct RegularStruct {
field1: u32,
field2: u64
}
fn main() -> i32 {
let instance = RegularStruct { field1: 1, field2: 2 }
return 0
}
|} in
let ast = Parse.parse_string program in
(* Check that the struct has no attributes *)
(match List.hd ast with
| StructDecl struct_def ->
check string "Struct name" "RegularStruct" struct_def.struct_name;
check int "No attributes" 0 (List.length struct_def.struct_attributes)
| _ -> fail "Expected StructDecl")
(** Test register() function type checking with struct_ops *)
let test_register_with_struct_ops () =
let program = {|
@struct_ops("tcp_congestion_ops")
impl MyTcpCong {
fn slow_start(sk: *u8) -> u32 {
return 1
}
fn cong_avoid(sk: *u8, ack: u32, acked: u32) -> void {
// Implementation
}
name: "my_tcp_cong",
owner: null,
}
fn main() -> i32 {
var result = register(MyTcpCong)
return result
}
|} in
let ast = Parse.parse_string program in
(* Type checking should succeed *)
let (typed_ast, _) = Type_checker.type_check_and_annotate_ast ast in
check bool "type check produces declarations" true (List.length typed_ast > 0)
(** Test register() function type checking rejects regular structs *)
let test_register_rejects_regular_struct () =
let program = {|
struct RegularStruct {
field1: u32,
field2: u64
}
fn main() -> i32 {
var instance = RegularStruct { field1: 1, field2: 2 }
var result = register(instance)
return result
}
|} in
let ast = Parse.parse_string program in
(* Type checking should fail *)
try
let _ = Type_checker.type_check_and_annotate_ast ast in
fail "register() with regular struct should fail type checking"
with
| Type_checker.Type_error (msg, _) ->
check bool "Error message mentions struct_ops requirement" true
(try ignore (Str.search_forward (Str.regexp "struct_ops") msg 0); true with Not_found -> false)
| _ -> fail "Expected Type_error for register() with regular struct"
(** Test multiple struct_ops in same program *)
let test_multiple_struct_ops () =
let program = {|
@struct_ops("tcp_congestion_ops")
impl TcpOps {
fn init(sk: *u8) -> u32 {
return 1
}
fn release(sk: *u8) -> void {
// Release implementation
}
name: "tcp_ops",
owner: null,
}
@struct_ops("bpf_iter_ops")
impl IterOps {
fn init_seq() -> u32 {
return 3
}
fn fini_seq() -> void {
// Cleanup implementation
}
name: "iter_ops",
owner: null,
}
fn main() -> i32 {
var result1 = register(TcpOps)
var result2 = register(IterOps)
return result1 + result2
}
|} in
let ast = Parse.parse_string program in
(* Both impl blocks should be parsed correctly *)
let impl_count = List.fold_left (fun acc decl ->
match decl with
| ImplBlock impl_block ->
if List.length impl_block.impl_attributes > 0 then acc + 1 else acc
| _ -> acc
) 0 ast in
check int "Number of struct_ops" 2 impl_count;
(* Type checking should succeed *)
let (typed_ast, _) = Type_checker.type_check_and_annotate_ast ast in
check bool "type check produces declarations" true (List.length typed_ast > 0)
(** Test IR generation for struct_ops *)
let test_struct_ops_ir_generation () =
let program = {|
@struct_ops("tcp_congestion_ops")
impl MyTcpCong {
fn init(sk: *u8) -> u32 {
return 1
}
fn release(sk: *u8) -> void {
// Release implementation
}
name: "my_tcp_cong",
owner: null,
}
@xdp fn xdp_prog(ctx: *xdp_md) -> xdp_action {
return 2
}
fn main() -> i32 {
var result = register(MyTcpCong)
return result
}
|} in
let ast = Parse.parse_string program in
let symbol_table = Symbol_table.build_symbol_table ast in
let (typed_ast, _) = Type_checker.type_check_and_annotate_ast ast in
let ir = Ir_generator.generate_ir typed_ast symbol_table "test" in
(* Check that struct_ops are collected in IR *)
check bool "IR contains struct_ops declarations" true (List.length (Ir.get_struct_ops_declarations ir) > 0);
(* Check the struct_ops declaration details *)
(match (Ir.get_struct_ops_declarations ir) with
| [declaration] ->
check string "Struct ops name" "MyTcpCong" declaration.ir_struct_ops_name;
check string "Kernel struct name" "tcp_congestion_ops" declaration.ir_kernel_struct_name
| _ -> fail "Expected exactly one struct_ops declaration in IR");
(* With impl blocks, the functions become individual eBPF programs *)
check bool "IR contains impl block programs" true (List.length (Ir.get_programs ir) >= 2); (* init and release functions *)
()
(** Test eBPF C code generation with struct_ops *)
let test_ebpf_struct_ops_codegen () =
let program = {|
@struct_ops("tcp_congestion_ops")
impl MyTcpCong {
fn init(sk: *u8) -> u32 {
return 1
}
fn release(sk: *u8) -> void {
// Release implementation
}
name: "my_tcp_cong",
owner: null,
}
@xdp fn xdp_prog(ctx: *xdp_md) -> xdp_action {
return 2
}
fn main() -> i32 {
var result = register(MyTcpCong)
return result
}
|} in
let ast = Parse.parse_string program in
let ast_with_structs = ast @ Test_utils.StructOps.builtin_ast in
let symbol_table = Symbol_table.build_symbol_table ast_with_structs in
let (typed_ast, _) = Type_checker.type_check_and_annotate_ast ast_with_structs in
let ir = Ir_generator.generate_ir typed_ast symbol_table "test" in
(* Generate eBPF C code *)
let (c_code, _) = Ebpf_c_codegen.compile_multi_to_c_with_analysis ir in
(* Basic generation checks *)
check bool "eBPF code generation completed" true (String.length c_code > 0);
(* Check for struct_ops section annotations *)
check bool "Contains struct_ops sections" true
(try ignore (Str.search_forward (Str.regexp "SEC(\"struct_ops") c_code 0); true with Not_found -> false);
(* Kernel struct definitions from .kh headers should NOT be emitted (vmlinux.h provides them) *)
(* Check that struct_ops instance is properly generated *)
check bool "Contains struct_ops instance definition" true
(try ignore (Str.search_forward (Str.regexp "SEC(\"\\.struct_ops\")") c_code 0); true with Not_found -> false);
check bool "Instance has correct struct type" true
(try ignore (Str.search_forward (Str.regexp "struct tcp_congestion_ops.*MyTcpCong") c_code 0); true with Not_found -> false)
(** Test userspace code generation with struct_ops *)
let test_userspace_struct_ops_codegen () =
let program = {|
@struct_ops("tcp_congestion_ops")
impl MyTcpCong {
fn init(sk: *u8) -> u32 {
return 1
}
fn release(sk: *u8) -> void {
// Release implementation
}
name: "my_tcp_cong",
owner: null,
}
@xdp fn xdp_prog(ctx: *xdp_md) -> xdp_action {
return 2
}
fn main() -> i32 {
var result = register(MyTcpCong)
return result
}
|} in
let ast = Parse.parse_string program in
let symbol_table = Symbol_table.build_symbol_table ast in
let (typed_ast, _) = Type_checker.type_check_and_annotate_ast ast in
let ir = Ir_generator.generate_ir typed_ast symbol_table "test" in
(* Generate userspace C code *)
let userspace_code = match ir.userspace_program with
| Some userspace_prog ->
Userspace_codegen.generate_complete_userspace_program_from_ir userspace_prog (Ir.get_global_maps ir) ir "test"
| None -> ""
in
(* Check that struct_ops registration code is generated *)
check bool "Contains struct_ops registration" true
(try ignore (Str.search_forward (Str.regexp "bpf_map__attach_struct_ops") userspace_code 0); true with Not_found -> false);
(* Check that struct_ops setup is included *)
check bool "Contains struct_ops setup" true
(try ignore (Str.search_forward (Str.regexp "MyTcpCong") userspace_code 0); true with Not_found -> false);
check bool "Contains memlock helper for struct_ops" true
(contains_substr userspace_code "static int bump_memlock_rlimit(void)");
check bool "Contains privilege helper for struct_ops" true
(contains_substr userspace_code "static int ensure_struct_ops_privileges(void)");
check bool "Main calls struct_ops runtime checks" true
(contains_substr userspace_code "if (bump_memlock_rlimit() < 0)" &&
contains_substr userspace_code "if (ensure_struct_ops_privileges() < 0)");
check bool "Contains struct_ops link global" true
(contains_substr userspace_code "static struct bpf_link *MyTcpCong_link = NULL;");
check bool "Contains struct_ops cleanup helper" true
(contains_substr userspace_code "static void cleanup_test(void)");
check bool "Contains wait helper for struct_ops" true
(contains_substr userspace_code "static void wait_for_unregister_request(void)");
check bool "Contains real attach helper for struct_ops" true
(contains_substr userspace_code "int attach_struct_ops_MyTcpCong(void)" &&
contains_substr userspace_code "MyTcpCong_link = bpf_map__attach_struct_ops(map);");
check bool "Contains real detach helper for struct_ops" true
(contains_substr userspace_code "int detach_struct_ops_MyTcpCong(void)" &&
contains_substr userspace_code "bpf_link__destroy(MyTcpCong_link);");
check bool "register() uses attach helper" true
(contains_substr userspace_code "attach_struct_ops_MyTcpCong()");
check bool "Struct_ops load failure includes EPERM hint" true
(contains_substr userspace_code "The kernel rejected BPF loading with EPERM. Make sure you run as root and the kernel supports struct_ops.");
check bool "Main waits for unregister request" true
(contains_substr userspace_code "wait_for_unregister_request();");
check bool "Main detaches struct_ops before exit" true
(contains_substr userspace_code "detach_struct_ops_MyTcpCong();");
check bool "Main registers struct_ops cleanup" true
(contains_substr userspace_code "atexit(cleanup_test);")
(** Test that malformed struct_ops attributes are parsed but should be caught *)
let test_malformed_struct_ops_attribute () =
let program = {|
@struct_ops
struct BadStruct {
field: u32
}
@xdp fn xdp_prog(ctx: *xdp_md) -> xdp_action {
return 2
}
fn main() -> i32 {
return 0
}
|} in
(* The parser accepts @struct_ops as SimpleAttribute *)
let ast = Parse.parse_string program in
(* For now, type checking passes this through - future enhancement could validate struct attributes *)
(* This test documents current behavior and can be enhanced when validation is added *)
let (typed_ast, _) = Type_checker.type_check_and_annotate_ast ast in
check bool "malformed struct_ops still produces declarations" true (List.length typed_ast > 0)
(** Test register() function with non-struct argument *)
let test_register_with_non_struct () =
let program = {|
fn main() -> i32 {
var x: u32 = 42
var result = register(x)
return result
}
|} in
let ast = Parse.parse_string program in
(* Type checking should fail *)
try
let _ = Type_checker.type_check_and_annotate_ast ast in
fail "register() with non-struct should fail type checking"
with
| Type_checker.Type_error _ -> ()
| e -> fail ("Expected Type_error, got: " ^ Printexc.to_string e)
(** Test nested struct_ops detection *)
let test_nested_struct_ops () =
let program = {|
@struct_ops("tcp_congestion_ops")
impl OuterImpl {
fn outer_func(sk: *u8) -> u32 {
return 42
}
name: "outer_impl",
owner: null,
}
@struct_ops("bpf_iter_ops")
impl InnerImpl {
fn inner_func() -> u64 {
return 100
}
name: "inner_impl",
owner: null,
}
fn main() -> i32 {
var result1 = register(OuterImpl)
var result2 = register(InnerImpl)
return result1 + result2
}
|} in
let ast = Parse.parse_string program in
(* Type checking should succeed - multiple impl blocks are allowed *)
let (typed_ast, _) = Type_checker.type_check_and_annotate_ast ast in
check bool "type check produces declarations" true (List.length typed_ast > 0)
(** Test symbol table integration with struct_ops *)
let test_symbol_table_struct_ops () =
let program = {|
@struct_ops("bpf_iter_ops")
struct IterOps {
init_seq: u32,
fini_seq: u32
}
fn main() -> i32 {
var ops = IterOps { init_seq: 1, fini_seq: 2 }
return 0
}
|} in
let ast = Parse.parse_string program in
let symbol_table = Symbol_table.build_symbol_table ast in
(* Check that struct_ops is added to symbol table *)
(match Symbol_table.lookup_symbol symbol_table "IterOps" with
| Some symbol ->
(match symbol.kind with
| TypeDef (StructDef (name, _, _)) -> check string "Struct name in symbol table" "IterOps" name
| _ -> fail "Expected StructDef in symbol table")
| None -> fail "struct_ops should be in symbol table")
(** Test that unknown struct_ops names are rejected *)
let test_unknown_struct_ops_name () =
let program = {|
@struct_ops("completely_made_up_struct_ops")
impl UnknownImpl {
fn some_func() -> u32 {
return 42
}
name: "unknown_impl",
owner: null,
}
fn main() -> i32 {
var result = register(UnknownImpl)
return result
}
|} in
let ast = Parse.parse_string program in
(* Type checking should fail for unknown struct_ops *)
try
let _ = Type_checker.type_check_and_annotate_ast ast in
fail "Unknown struct_ops name should fail type checking"
with
| Type_checker.Type_error (msg, _) ->
check bool "Error message mentions unknown struct_ops" true
(try ignore (Str.search_forward (Str.regexp "Unknown struct_ops\\|unknown.*struct_ops\\|Invalid struct_ops") msg 0); true with Not_found -> false)
| _ -> fail "Expected Type_error for unknown struct_ops name"
(** Test function prototype mismatches in struct_ops implementations *)
let test_struct_ops_wrong_return_type () =
let program = {|
@struct_ops("tcp_congestion_ops")
impl BadTcpCong {
fn ssthresh(sk: *u8) -> void { // WRONG: should return u32
// Implementation
}
name: "bad_tcp_cong",
owner: null,
}
fn main() -> i32 {
var result = register(BadTcpCong)
return result
}
|} in
let ast = Parse.parse_string program in
let ast_with_structs = ast @ Test_utils.StructOps.builtin_ast in
(* Type checking should fail for wrong return type *)
try
let _ = Type_checker.type_check_and_annotate_ast ast_with_structs in
fail "Wrong return type should fail validation"
with
| Type_checker.Type_error (msg, _) ->
check bool "Error message mentions return type mismatch" true
(try ignore (Str.search_forward (Str.regexp "return.*type\\|signature.*mismatch") msg 0); true with Not_found -> false)
| _ -> fail "Expected Type_error for wrong return type"
let test_struct_ops_missing_parameters () =
let program = {|
@struct_ops("tcp_congestion_ops")
impl BadTcpCong {
fn cong_avoid(sk: *u8) -> void { // WRONG: missing ack and acked parameters
// Implementation
}
name: "bad_tcp_cong",
owner: null,
}
fn main() -> i32 {
var result = register(BadTcpCong)
return result
}
|} in
let ast = Parse.parse_string program in
let ast_with_structs = ast @ Test_utils.StructOps.builtin_ast in
(* Type checking should fail for missing parameters *)
try
let _ = Type_checker.type_check_and_annotate_ast ast_with_structs in
fail "Missing parameters should fail validation"
with
| Type_checker.Type_error (msg, _) ->
check bool "Error message mentions parameter mismatch" true
(try ignore (Str.search_forward (Str.regexp "parameter.*mismatch\\|signature.*mismatch") msg 0); true with Not_found -> false)
| _ -> fail "Expected Type_error for missing parameters"
let test_struct_ops_extra_parameters () =
let program = {|
@struct_ops("tcp_congestion_ops")
impl BadTcpCong {
fn ssthresh(sk: *u8, extra: u32) -> u32 { // WRONG: extra parameter
return 16
}
name: "bad_tcp_cong",
owner: null,
}
fn main() -> i32 {
var result = register(BadTcpCong)
return result
}
|} in
let ast = Parse.parse_string program in
let ast_with_structs = ast @ Test_utils.StructOps.builtin_ast in
(* Type checking should fail for extra parameters *)
try
let _ = Type_checker.type_check_and_annotate_ast ast_with_structs in
fail "Extra parameters should fail validation"
with
| Type_checker.Type_error (msg, _) ->
check bool "Error message mentions parameter mismatch" true
(try ignore (Str.search_forward (Str.regexp "parameter.*count\\|signature.*mismatch") msg 0); true with Not_found -> false)
| _ -> fail "Expected Type_error for extra parameters"
let test_struct_ops_wrong_parameter_type () =
let program = {|
@struct_ops("tcp_congestion_ops")
impl BadTcpCong {
fn cong_avoid(sk: u32, ack: u32, acked: u32) -> void { // WRONG: sk should be *u8, not u32
// Implementation
}
name: "bad_tcp_cong",
owner: null,
}
fn main() -> i32 {
var result = register(BadTcpCong)
return result
}
|} in
let ast = Parse.parse_string program in
let ast_with_structs = ast @ Test_utils.StructOps.builtin_ast in
(* Type checking should fail for wrong parameter type *)
try
let _ = Type_checker.type_check_and_annotate_ast ast_with_structs in
fail "Wrong parameter type should fail validation"
with
| Type_checker.Type_error (msg, _) ->
check bool "Error message mentions parameter type mismatch" true
(try ignore (Str.search_forward (Str.regexp "parameter.*type\\|signature.*mismatch") msg 0); true with Not_found -> false)
| _ -> fail "Expected Type_error for wrong parameter type"
let test_struct_ops_missing_required_function () =
let program = {|
@struct_ops("tcp_congestion_ops")
impl IncompleteTcpCong {
// Missing functions are now allowed since most struct_ops functions are optional
name: "incomplete_tcp_cong",
owner: null,
}
fn main() -> i32 {
var result = register(IncompleteTcpCong)
return result
}
|} in
let ast = Parse.parse_string program in
let ast_with_structs = ast @ Test_utils.StructOps.builtin_ast in
(* Type checking should now succeed since functions are optional *)
let (typed_ast, _) = Type_checker.type_check_and_annotate_ast ast_with_structs in
check bool "type check produces declarations" true (List.length typed_ast > 0)
let test_struct_ops_correct_signatures () =
let program = {|
@struct_ops("tcp_congestion_ops")
impl CorrectTcpCong {
fn ssthresh(sk: *u8) -> u32 { // Correct signature
return 16
}
fn cong_avoid(sk: *u8, ack: u32, acked: u32) -> void { // Correct signature
// Implementation
}
// Only implementing some functions - others are optional
name: "correct_tcp_cong",
owner: null,
}
fn main() -> i32 {
var result = register(CorrectTcpCong)
return result
}
|} in
let ast = Parse.parse_string program in
let ast_with_structs = ast @ Test_utils.StructOps.builtin_ast in
(* Type checking should succeed for correct signatures *)
let (typed_ast, _) = Type_checker.type_check_and_annotate_ast ast_with_structs in
check bool "type check produces declarations" true (List.length typed_ast > 0)
(** BTF Integration Tests *)
(** Test struct_ops registry functionality *)
let test_struct_ops_registry () =
(* Test known struct_ops detection *)
check bool "tcp_congestion_ops is known" true (Struct_ops_registry.is_known_struct_ops "tcp_congestion_ops");
check bool "bpf_iter_ops is known" true (Struct_ops_registry.is_known_struct_ops "bpf_iter_ops");
check bool "unknown_struct_ops is not known" false (Struct_ops_registry.is_known_struct_ops "unknown_struct_ops");
(* Test struct_ops info retrieval *)
(match Struct_ops_registry.get_struct_ops_info "tcp_congestion_ops" with
| Some info ->
check string "tcp_congestion_ops description" "TCP congestion control operations" info.description;
check (option string) "tcp_congestion_ops version" (Some "5.6+") info.kernel_version
| None -> fail "Expected to find tcp_congestion_ops info");
(* Test getting all known struct_ops *)
let all_known = Struct_ops_registry.get_all_known_struct_ops () in
check bool "Contains tcp_congestion_ops" true (List.mem "tcp_congestion_ops" all_known);
check bool "Contains bpf_iter_ops" true (List.mem "bpf_iter_ops" all_known)
(** Test struct_ops usage example generation *)
let test_struct_ops_usage_examples () =
let tcp_example = Struct_ops_registry.generate_struct_ops_usage_example "tcp_congestion_ops" in
check bool "TCP example contains register" true
(try ignore (Str.search_forward (Str.regexp "register") tcp_example 0); true with Not_found -> false);
check bool "TCP example contains tcp_congestion_ops" true
(try ignore (Str.search_forward (Str.regexp "tcp_congestion_ops") tcp_example 0); true with Not_found -> false);
let unknown_example = Struct_ops_registry.generate_struct_ops_usage_example "unknown_struct_ops" in
check bool "Unknown example contains register" true
(try ignore (Str.search_forward (Str.regexp "register") unknown_example 0); true with Not_found -> false)
(** Test BTF template generation without actual BTF file *)
let test_btf_template_generation () =
(* Test template generation without BTF file should now error *)
(try
let _ = Btf_parser.generate_struct_ops_template None ["tcp_congestion_ops"] "test_project" in
fail "Expected error when no BTF file is provided"
with
| Failure msg when String.contains msg 'B' && String.contains msg 'T' && String.contains msg 'F' ->
check bool "missing BTF error mentions BTF" true (String.length msg > 0)
| e -> fail ("Expected BTF-related Failure, got: " ^ Printexc.to_string e));
(* Test with invalid BTF file path should also error *)
(try
let _ = Btf_parser.generate_struct_ops_template (Some "/nonexistent/btf") ["tcp_congestion_ops"] "test_project" in
fail "Expected error for non-existent BTF file"
with
| Failure msg when String.contains msg 'B' && String.contains msg 'T' && String.contains msg 'F' ->
check bool "invalid BTF error mentions BTF" true (String.length msg > 0)
| e -> fail ("Expected BTF-related Failure, got: " ^ Printexc.to_string e))
(** Test struct_ops initialization using main init command *)
let test_init_command_struct_ops_detection () =
(* This test would require setting up temporary directories and running the actual init command *)
(* For now, we'll test the underlying logic *)
(* Test that tcp_congestion_ops is recognized as a struct_ops *)
check bool "tcp_congestion_ops is recognized as struct_ops" true
(Struct_ops_registry.is_known_struct_ops "tcp_congestion_ops");
(* Test that regular program types are still recognized *)
let valid_program_types = ["xdp"; "tc"; "kprobe"; "uprobe"; "tracepoint"; "lsm"; "cgroup_skb"] in
List.iter (fun prog_type ->
check bool (sprintf "%s is valid program type" prog_type) true
(List.mem prog_type valid_program_types)
) valid_program_types
(** Test BTF extraction error handling *)
let test_btf_error_handling () =
(* Test verification with non-existent BTF file *)
(match Struct_ops_registry.verify_struct_ops_against_btf "/non/existent/btf" "tcp_congestion_ops" [("init", "u32")] with
| Error msg ->
check bool "Error message contains expected text" true
(String.contains msg 'B' && String.contains msg 'T' && String.contains msg 'F')
| Ok () -> fail "Expected error for non-existent BTF file");
(* Test extraction from non-existent BTF file *)
let definitions = Struct_ops_registry.extract_struct_ops_from_btf "/non/existent/btf" ["tcp_congestion_ops"] in
check int "No definitions extracted from non-existent file" 0 (List.length definitions)
(** Test struct_ops code generation *)
let test_struct_ops_code_generation () =
(* Create mock BTF type info *)
let mock_btf_type = {
Btf_binary_parser.name = "tcp_congestion_ops";
kind = "struct";
size = Some 64;
members = Some [
("init", "void*");
("cong_avoid", "void*");
("set_state", "void*");
("name", "char*");
];
kernel_defined = true;
} in
(* Test struct_ops definition generation *)
(match Struct_ops_registry.generate_struct_ops_definition mock_btf_type with
| Some definition ->
check bool "Definition contains @struct_ops attribute" true
(try ignore (Str.search_forward (Str.regexp "@struct_ops") definition 0); true with Not_found -> false);
check bool "Definition contains struct name" true
(try ignore (Str.search_forward (Str.regexp "tcp_congestion_ops") definition 0); true with Not_found -> false);
check bool "Definition contains init field" true
(try ignore (Str.search_forward (Str.regexp "init:") definition 0); true with Not_found -> false);
check bool "Definition contains cong_avoid field" true
(try ignore (Str.search_forward (Str.regexp "cong_avoid:") definition 0); true with Not_found -> false)
| None -> fail "Expected struct_ops definition to be generated")
(** Test selective struct inclusion in eBPF code - this would have caught the original bug *)
let test_selective_struct_inclusion_in_ebpf () =
let program = {|
// This struct should NOT be included in eBPF code - it's userspace-only
struct Args {
enable_debug: u32,
interface: str(16),
}
// This struct should be included in eBPF code - it's referenced by struct_ops
@struct_ops("tcp_congestion_ops")
impl TcpOps {
fn ssthresh(sk: *u8) -> u32 {
return 16
}
fn cong_avoid(sk: *u8, ack: u32, acked: u32) -> void {
// Implementation
}
name: "test_tcp_ops",
owner: null,
}
// This config struct should be included - it's used by eBPF programs
config network_config {
max_packet_size: u32 = 1500,
enable_logging: bool = true,
}
@xdp fn packet_filter(ctx: *xdp_md) -> xdp_action {
return 1
}
fn main(args: Args) -> i32 {
if (args.enable_debug > 0) {
var result = register(TcpOps)
return result
}
return 0
}
|} in
let ast = Parse.parse_string program in
let ast_with_structs = ast @ Test_utils.StructOps.builtin_ast in
let symbol_table = Symbol_table.build_symbol_table ast_with_structs in
let (typed_ast, _) = Type_checker.type_check_and_annotate_ast ast_with_structs in
let ir = Ir_generator.generate_ir typed_ast symbol_table "test" in
(* Generate eBPF C code *)
let (c_code, _) = Ebpf_c_codegen.compile_multi_to_c_with_analysis ir in
(* Check that all structs are included in eBPF code *)
check bool "Args struct should be in eBPF code (all structs included)" true
(contains_substr c_code "struct Args");
(* Check that struct_ops-referenced structs ARE included in eBPF code *)
check bool "tcp_congestion_ops struct should be in eBPF code (kernel struct)" true
(contains_substr c_code "struct tcp_congestion_ops");
(* Check that config structs ARE included in eBPF code *)
check bool "network_config struct should be in eBPF code (used by eBPF programs)" true
(contains_substr c_code "struct network_config");
(* Verify that eBPF code compiles without missing struct definition errors *)
check bool "eBPF code generation completed without errors" true (String.length c_code > 0);
(* Additional verification: check that string literals are handled properly *)
(* String literals should be embedded directly in the code, not as struct types *)
check bool "String literals are handled properly" true
(contains_substr c_code "test_tcp_ops")
(** Test compilation without struct definition errors *)
let test_struct_ops_compilation_completeness () =
let program = {|
@struct_ops("tcp_congestion_ops")
impl minimal_congestion_control {
fn ssthresh(sk: *u8) -> u32 {
return 16
}
fn cong_avoid(sk: *u8, ack: u32, acked: u32) -> void {
// Implementation
}
owner: null,
}
@xdp fn test_prog(ctx: *xdp_md) -> xdp_action {
return 1
}
fn main() -> i32 {
var result = register(minimal_congestion_control)
return result
}
|} in
let ast = Parse.parse_string program in
let ast_with_structs = ast @ Test_utils.StructOps.builtin_ast in
let symbol_table = Symbol_table.build_symbol_table ast_with_structs in
let (typed_ast, _) = Type_checker.type_check_and_annotate_ast ast_with_structs in
let ir = Ir_generator.generate_ir typed_ast symbol_table "test" in
(* Generate eBPF C code *)
let (c_code, _) = Ebpf_c_codegen.compile_multi_to_c_with_analysis ir in
(* The key test: verify that tcp_congestion_ops struct is complete and usable *)
check bool "Contains complete tcp_congestion_ops struct definition" true
(contains_substr c_code "struct tcp_congestion_ops");
(* Check that the struct_ops instance can be instantiated (key thing that was failing) *)
check bool "Contains struct_ops instance instantiation" true
(contains_substr c_code "minimal_congestion_control" && contains_substr c_code "struct tcp_congestion_ops");
(* Verify SEC annotations are present *)
check bool "Contains .struct_ops section" true
(contains_substr c_code "SEC(\".struct_ops\")");
(* Verify the compiler synthesizes a safe default name when omitted *)
check bool "Contains synthesized tcp_congestion_ops name" true
(contains_substr c_code ".name = \"minimal_cc\"");
(* Verify individual function SEC annotations *)
check bool "Contains struct_ops function sections" true
(contains_substr c_code "SEC(\"struct_ops/")
(** Test struct_ops internal calls stay as direct calls instead of tail calls *)
let test_struct_ops_internal_calls_are_direct () =
let program = {|
@struct_ops("tcp_congestion_ops")
impl minimal_congestion_control {
fn ssthresh(sk: *u8) -> u32 {
return 16
}
fn undo_cwnd(sk: *u8) -> u32 {
return ssthresh(sk)
}
}
|} in
let ast = Parse.parse_string program in
let ast_with_structs = ast @ Test_utils.StructOps.builtin_ast in
let symbol_table = Symbol_table.build_symbol_table ast_with_structs in
let (typed_ast, _) = Type_checker.type_check_and_annotate_ast ast_with_structs in
let ir = Ir_generator.generate_ir typed_ast symbol_table "test" in
let (c_code, _) = Ebpf_c_codegen.compile_multi_to_c_with_analysis ir in
check bool "struct_ops direct call emitted" true
(contains_substr c_code "ssthresh(sk)");
check bool "struct_ops tail call not emitted" false
(contains_substr c_code "bpf_tail_call(ctx, &prog_array")
(** Test that find_struct_ops_main_registration correctly identifies the
attach result variable, the struct_ops instance, and the terminal return
variable even when the returned variable name differs from the register()
result (e.g. an alias is assigned before the final return).
The generated lifecycle code must use the C names produced by
generate_c_value_from_ir, not the raw IR names, so that the emitted
code refers to var_result instead of the un-prefixed result and avoids
the "undeclared identifier" error that motivated this function. *)
let test_find_struct_ops_main_registration () =
(* Simple case: var result = register(MyTcpCong); return result *)
let program_simple = {|
@struct_ops("tcp_congestion_ops")
impl MyTcpCong {
fn init(sk: *u8) -> u32 { return 0 }
fn release(sk: *u8) -> void {}
name: "my_tcp_cong",
owner: null,
}
fn main() -> i32 {
var result = register(MyTcpCong)
return result
}
|} in
let ast = Parse.parse_string program_simple in
let symbol_table = Symbol_table.build_symbol_table ast in
let (typed_ast, _) = Type_checker.type_check_and_annotate_ast ast in
let ir = Ir_generator.generate_ir typed_ast symbol_table "test" in
let userspace_code = match ir.userspace_program with
| Some p -> Userspace_codegen.generate_complete_userspace_program_from_ir
p (Ir.get_global_maps ir) ir "test"
| None -> ""
in
(* The lifecycle code should use the correctly-prefixed C variable throughout *)
check bool "lifecycle uses var_result for attach status check" true
(contains_substr userspace_code "if (var_result != 0)");
check bool "lifecycle calls detach_struct_ops_MyTcpCong" true
(contains_substr userspace_code "var_result = detach_struct_ops_MyTcpCong()");
check bool "lifecycle returns var_result at the end" true
(contains_substr userspace_code "return var_result;");
check bool "register result stored via prefixed var_result, not bare result" true