-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathebpf_c_codegen.ml
More file actions
3418 lines (3065 loc) · 159 KB
/
Copy pathebpf_c_codegen.ml
File metadata and controls
3418 lines (3065 loc) · 159 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.
*)
(** eBPF C Code Generation from IR
This module generates idiomatic eBPF C code from the IR representation.
The generated code is compatible with clang -target bpf compilation.
Key features:
- Map definitions using SEC("maps") sections
- Standard BPF helper function calls
- Context field access
- Bounds checking as C conditionals
- Structured control flow
*)
open Ir
open Printf
module StringSet = Set.Make(String)
(** Memory region types for dynptr API selection *)
type memory_region_type =
| PacketData (* XDP/TC packet data - use bpf_dynptr_from_xdp/skb *)
| MapValue (* Map lookup result - use bpf_dynptr_from_mem *)
| RingBuffer (* Ring buffer data - use bpf_dynptr_from_ringbuf *)
| LocalStack (* Local stack variables - use regular access *)
| RegularMemory (* Other memory - use enhanced safety *)
(** Enhanced memory region detection using provided region information *)
type enhanced_memory_info = {
region_type: memory_region_type;
bounds_verified: bool;
size_hint: int option;
}
(** Variable name to enhanced memory info mapping *)
type memory_info_map = (string, enhanced_memory_info) Hashtbl.t
(** Detect memory region type from IR value semantics *)
let detect_memory_region_type ir_val =
match ir_val.value_desc with
| IRVariable _ -> LocalStack (* Variables are typically stack-allocated *)
| IRMapRef _ -> RegularMemory (* Map references *)
| IRLiteral _ -> RegularMemory (* Literals *)
| IRTempVariable _ -> RegularMemory (* Temporary variables *)
| _ -> RegularMemory
(** Check if IR value represents map-derived data - heuristic approach *)
let is_map_value_parameter ir_val =
match ir_val.val_type with
| IRPointer (IRStruct _, _) ->
(* Struct pointers that are variables could be from map lookups *)
(match ir_val.value_desc with
| IRVariable name ->
(* Heuristic: variables with certain names are likely map-derived *)
String.contains name '_' && (String.length name > 3)
| _ -> false)
| _ -> false
(** Enhanced memory region detection using provided memory info *)
let detect_memory_region_enhanced ?(memory_info_map=None) ir_val =
match memory_info_map with
| Some info_map ->
(* Use provided memory region information *)
(match ir_val.value_desc with
| IRVariable var_name ->
(try
let info = Hashtbl.find info_map var_name in
info.region_type
with
| Not_found -> LocalStack) (* Default for unknown variables *)
| IRMapRef _ -> RegularMemory
| IRLiteral _ -> RegularMemory
| IRTempVariable _ -> RegularMemory
| _ -> RegularMemory)
| None ->
(* Fallback to heuristic detection *)
detect_memory_region_type ir_val
(** Callback dependency information for ordered emission *)
type callback_dependency = {
name: string;
start_val: Ir.ir_value;
end_val: Ir.ir_value;
counter_val: Ir.ir_value;
body_instructions: Ir.ir_instruction list;
}
(** C code generation context *)
type c_context = {
(* Generated C code lines *)
mutable output_lines: string list;
(* Current indentation level *)
mutable indent_level: int;
(* Variable counter for generating unique names *)
mutable var_counter: int;
(* Label counter for control flow *)
mutable label_counter: int;
(* Include statements needed *)
mutable includes: string list;
(* Map definitions that need to be emitted *)
mutable map_definitions: ir_map_def list;
(* Next label ID for generating unique callback function names *)
mutable next_label_id: int;
(* Pending callbacks to be emitted *)
mutable pending_callbacks: string list;
(* Pre-collected callback dependencies for ordered emission *)
mutable callback_dependencies: callback_dependency list;
(* Current error variable for try/catch blocks *)
mutable current_error_var: string option;
(* Current catch label for try/catch blocks *)
mutable current_catch_label: string option;
(* Pinned global variables for transparent access *)
mutable pinned_globals: string list;
(* Flag to indicate if we're generating code for a return context *)
mutable in_return_context: bool;
(* Pending string literals to be emitted at scope boundaries *)
mutable pending_string_literals: (string * string * int) list; (* (var_name, content, size) *)
(* Flag to defer string literal emission *)
mutable defer_string_literals: bool;
(* Track which registers have been declared to avoid redeclaration *)
mutable declared_registers: (int, unit) Hashtbl.t;
(* Current function's context type for proper field access generation *)
mutable current_function_context_type: string option;
(* Track dynptr-backed pointers for proper field assignment *)
mutable dynptr_backed_pointers: (string, string) Hashtbl.t; (* pointer_var -> dynptr_var *)
}
let create_c_context () = {
output_lines = [];
indent_level = 0;
var_counter = 0;
label_counter = 0;
includes = [];
map_definitions = [];
next_label_id = 0;
pending_callbacks = [];
callback_dependencies = [];
current_error_var = None;
current_catch_label = None;
pinned_globals = [];
in_return_context = false;
pending_string_literals = [];
defer_string_literals = false;
declared_registers = Hashtbl.create 32;
current_function_context_type = None;
dynptr_backed_pointers = Hashtbl.create 32;
}
(** Get the appropriate fallback return value when bpf_tail_call() fails.
bpf_tail_call() is not guaranteed to succeed; when it fails execution
continues past the call site. Every arm that uses a tail call must have
an explicit return so the eBPF verifier can confirm all paths exit. *)
let get_tail_call_fallback_return ctx =
match ctx.current_function_context_type with
| Some "xdp" -> "XDP_PASS"
| Some "tc" -> "TC_ACT_OK"
| _ -> "0"
(** Helper functions for code generation *)
(** Calculate the size of a type for dynptr field assignment operations.
This function should only be called with basic value types that are valid
for struct field assignments. The type checker ensures only compatible
types reach this point. *)
let rec calculate_type_size ir_type =
match ir_type with
(* Basic integer types *)
| IRU8 | IRI8 | IRChar -> 1
| IRU16 | IRI16 -> 2
| IRU32 | IRI32 | IRF32 -> 4
| IRU64 | IRI64 | IRF64 -> 8
| IRBool -> 1
(* String and pointer types (valid in some field contexts) *)
| IRStr _ -> 1 (* Size of individual char *)
| IRPointer (_, _) -> 8 (* Pointer size *)
(* Array elements - recurse to get element size *)
| IRArray (elem_type, _, _) -> calculate_type_size elem_type
(* These types should never appear in field assignments due to type checking *)
| IRVoid ->
failwith "calculate_type_size: IRVoid should not appear in field assignments"
| IRStruct (struct_name, _) ->
failwith ("calculate_type_size: IRStruct should not appear in field assignments, got: " ^ struct_name)
| IREnum (enum_name, _) ->
failwith ("calculate_type_size: IREnum should not appear in field assignments, got: " ^ enum_name)
| IRResult (_, _) ->
failwith "calculate_type_size: IRResult should not appear in field assignments"
(* IRAction removed - xdp_action is now handled as regular enum *)
| IRTypeAlias (alias_name, _) ->
failwith ("calculate_type_size: IRTypeAlias should be resolved by type checker, got: " ^ alias_name)
| IRStructOps (ops_name, _) ->
failwith ("calculate_type_size: IRStructOps should not appear in field assignments, got: " ^ ops_name)
| IRFunctionPointer (_, _) ->
failwith "calculate_type_size: IRFunctionPointer should not appear in field assignments"
| IRRingbuf (_, _) ->
failwith "calculate_type_size: IRRingbuf should not appear in field assignments"
let indent ctx = String.make (ctx.indent_level * 4) ' '
let emit_line ctx line =
ctx.output_lines <- ctx.output_lines @ [(indent ctx ^ line)]
let emit_blank_line ctx =
ctx.output_lines <- ctx.output_lines @ [""]
let concat = List.concat
let concat_map f l = List.concat (List.map f l)
let concat_map_opt f = function
| Some l -> concat_map f l
| None -> []
let increase_indent ctx = ctx.indent_level <- ctx.indent_level + 1
let decrease_indent ctx = ctx.indent_level <- ctx.indent_level - 1
let add_include ctx include_name =
if not (List.mem include_name ctx.includes) then
ctx.includes <- include_name :: ctx.includes
let fresh_var ctx prefix =
ctx.var_counter <- ctx.var_counter + 1;
sprintf "%s_%d" prefix ctx.var_counter
(** Helper to check if a position indicates a kernel-defined type *)
let is_kernel_defined_type = Codegen_common.is_kernel_defined_pos
(** Helper to check if a struct should be included, excluding struct_ops *)
let should_include_struct_with_struct_ops = Codegen_common.should_include_struct
let fresh_label ctx prefix =
ctx.label_counter <- ctx.label_counter + 1;
sprintf "%s_%d" prefix ctx.label_counter
(** Initialize all modular context code generators *)
let initialize_context_generators () =
Kernelscript_context.Xdp_codegen.register ();
Kernelscript_context.Tc_codegen.register ();
Kernelscript_context.Kprobe_codegen.register ();
Kernelscript_context.Tracepoint_codegen.register ();
Kernelscript_context.Fprobe_codegen.register ();
Kernelscript_context.Perf_event_codegen.register ()
(** Emit a safe str_N_t to str_M_t copy. The naive
`__builtin_memcpy(&dst, &src, sizeof(src))` is wrong whenever the two
str_N_t types have different sizes: layouts diverge, so the source's
`.len` field gets memcpy'd into the destination's `.data[]` array and the
destination's `.len` is left uninitialized (or filled with garbage past
the end of src). Field-level copy respects the length-prefixed semantics
regardless of either side's declared capacity. *)
let emit_str_copy ctx ~dest ~src =
emit_line ctx (sprintf "%s.len = %s.len;" dest src);
emit_line ctx (sprintf "__builtin_memcpy(%s.data, %s.data, %s.len);" dest src src)
(** Emit all pending string literal declarations *)
let emit_pending_string_literals ctx =
List.iter (fun (var_name, content, size) ->
let len = String.length content in
let max_content_len = size in (* Full size available for content *)
let actual_len = min len max_content_len in
let truncated_s = if actual_len < len then String.sub content 0 actual_len else content in
emit_line ctx (sprintf "str_%d_t %s = {" size var_name);
emit_line ctx (sprintf " .data = \"%s\"," (String.escaped truncated_s));
emit_line ctx (sprintf " .len = %d" actual_len);
emit_line ctx "};";
) (List.rev ctx.pending_string_literals);
ctx.pending_string_literals <- []
(** Escape string for C string literal *)
let escape_c_string s =
String.escaped s
(** Type conversion from IR types to C types *)
let ebpf_type_from_ir_type = Codegen_common.ir_type_to_c Codegen_common.EbpfKernel
(** Type conversion for kfunc signatures. Unlike ebpf_type_from_ir_type, this keeps
[IRBool] as C [bool] rather than collapsing it to [__u8], so the emitted prototype
matches the kernel's actual kfunc signature (kfunc/extern type matching is strict). *)
let rec kfunc_signature_type_to_c = function
| Ir.IRU8 -> "__u8" | Ir.IRU16 -> "__u16" | Ir.IRU32 -> "__u32" | Ir.IRU64 -> "__u64"
| Ir.IRI8 -> "__s8" | Ir.IRI16 -> "__s16" | Ir.IRI32 -> "__s32" | Ir.IRI64 -> "__s64"
| Ir.IRBool -> "bool" | Ir.IRChar -> "char" | Ir.IRVoid -> "void"
| Ir.IRPointer (inner_type, _) -> sprintf "%s*" (kfunc_signature_type_to_c inner_type)
| other -> ebpf_type_from_ir_type other
(** Generate proper C declaration for eBPF, handling function pointers correctly *)
let generate_ebpf_c_declaration = Codegen_common.c_declaration Codegen_common.EbpfKernel
(** Map type conversion *)
let ir_map_type_to_c_type = function
| IRHash -> "BPF_MAP_TYPE_HASH"
| IRMapArray -> "BPF_MAP_TYPE_ARRAY"
| IRPercpu_hash -> "BPF_MAP_TYPE_PERCPU_HASH"
| IRPercpu_array -> "BPF_MAP_TYPE_PERCPU_ARRAY"
| IRLru_hash -> "BPF_MAP_TYPE_LRU_HASH"
(** Collect all string sizes used in the program *)
let rec collect_string_sizes_from_type = function
| IRStr size -> [size]
| IRPointer (inner_type, _) -> collect_string_sizes_from_type inner_type
| IRArray (inner_type, _, _) -> collect_string_sizes_from_type inner_type
| IRResult (ok_type, err_type) ->
(collect_string_sizes_from_type ok_type) @ (collect_string_sizes_from_type err_type)
| _ -> []
let collect_string_sizes_from_value ir_val =
collect_string_sizes_from_type ir_val.val_type
let collect_string_sizes_from_expr ir_expr =
match ir_expr.expr_desc with
| IRValue ir_val -> collect_string_sizes_from_value ir_val
| IRBinOp (left, _, right) ->
(collect_string_sizes_from_value left) @ (collect_string_sizes_from_value right)
| IRUnOp (_, ir_val) -> collect_string_sizes_from_value ir_val
| IRCast (ir_val, target_type) ->
(collect_string_sizes_from_value ir_val) @ (collect_string_sizes_from_type target_type)
| IRFieldAccess (obj_val, _) -> collect_string_sizes_from_value obj_val
| IRStructLiteral (_, field_assignments) ->
List.fold_left (fun acc (_, field_val) ->
acc @ (collect_string_sizes_from_value field_val)
) [] field_assignments
| IRMatch (matched_val, arms) ->
(* Collect string sizes from matched expression and all arms *)
(collect_string_sizes_from_value matched_val) @
(List.fold_left (fun acc arm ->
acc @ (collect_string_sizes_from_value arm.ir_arm_value)
) [] arms)
let rec collect_string_sizes_from_instr ir_instr =
match ir_instr.instr_desc with
| IRAssign (dest_val, expr) ->
(collect_string_sizes_from_value dest_val) @ (collect_string_sizes_from_expr expr)
| IRConstAssign (dest_val, expr) ->
(collect_string_sizes_from_value dest_val) @ (collect_string_sizes_from_expr expr)
| IRVariableDecl (_dest_val, typ, init_expr_opt) ->
(* New unified variable declaration - collect from both variable type and initializer *)
let var_type_sizes = collect_string_sizes_from_type typ in
let init_sizes = match init_expr_opt with
| Some init_expr -> collect_string_sizes_from_expr init_expr
| None -> []
in
var_type_sizes @ init_sizes
| IRCall (_, args, ret_opt) ->
let args_sizes = concat_map collect_string_sizes_from_value args in
let ret_sizes = match ret_opt with Some ret_val -> collect_string_sizes_from_value ret_val | None -> [] in
args_sizes @ ret_sizes
| IRMapLoad (map_val, key_val, dest_val, _) ->
(collect_string_sizes_from_value map_val) @
(collect_string_sizes_from_value key_val) @
(collect_string_sizes_from_value dest_val)
| IRMapStore (map_val, key_val, value_val, _) ->
(collect_string_sizes_from_value map_val) @
(collect_string_sizes_from_value key_val) @
(collect_string_sizes_from_value value_val)
| IRMapDelete (map_val, key_val) ->
(collect_string_sizes_from_value map_val) @
(collect_string_sizes_from_value key_val)
| IRConfigFieldUpdate (map_val, key_val, _field, value_val) ->
(collect_string_sizes_from_value map_val) @
(collect_string_sizes_from_value key_val) @
(collect_string_sizes_from_value value_val)
| IRStructFieldAssignment (obj_val, _field, value_val) ->
(collect_string_sizes_from_value obj_val) @
(collect_string_sizes_from_value value_val)
| IRConfigAccess (_config_name, _field_name, result_val) ->
collect_string_sizes_from_value result_val
| IRContextAccess (dest_val, _context_type, _field_name) ->
collect_string_sizes_from_value dest_val
| IRBoundsCheck (ir_val, _, _) ->
collect_string_sizes_from_value ir_val
| IRJump _ -> []
| IRCondJump (cond_val, _, _) ->
collect_string_sizes_from_value cond_val
| IRIf (cond_val, then_instrs, else_instrs_opt) ->
let cond_sizes = collect_string_sizes_from_value cond_val in
let then_sizes = concat_map collect_string_sizes_from_instr then_instrs in
let else_sizes = concat_map_opt collect_string_sizes_from_instr else_instrs_opt in
cond_sizes @ then_sizes @ else_sizes
| IRIfElseChain (conditions_and_bodies, final_else) ->
let cond_sizes = concat_map (fun (cond_val, then_instrs) ->
let cond_sz = collect_string_sizes_from_value cond_val in
let then_sz = concat_map collect_string_sizes_from_instr then_instrs in
cond_sz @ then_sz
) conditions_and_bodies in
let else_sizes = match final_else with
| Some else_instrs -> concat_map collect_string_sizes_from_instr else_instrs
| None -> []
in
cond_sizes @ else_sizes
| IRMatchReturn (matched_val, arms) ->
let matched_sizes = collect_string_sizes_from_value matched_val in
let arms_sizes = List.fold_left (fun acc arm ->
let pattern_sizes = match arm.match_pattern with
| IRConstantPattern const_val -> collect_string_sizes_from_value const_val
| IRDefaultPattern -> []
in
let action_sizes = match arm.return_action with
| IRReturnValue ret_val -> collect_string_sizes_from_value ret_val
| IRReturnCall (_, args) -> List.fold_left (fun acc arg ->
acc @ (collect_string_sizes_from_value arg)) [] args
| IRReturnTailCall (_, args, _) -> List.fold_left (fun acc arg ->
acc @ (collect_string_sizes_from_value arg)) [] args
in
acc @ pattern_sizes @ action_sizes
) [] arms in
matched_sizes @ arms_sizes
| IRReturn ret_opt ->
(match ret_opt with
| Some ret_val -> collect_string_sizes_from_value ret_val
| None -> [])
| IRComment _ -> [] (* Comments don't contain values *)
| IRBpfLoop (start_val, end_val, counter_val, ctx_val, body_instructions) ->
(collect_string_sizes_from_value start_val) @
(collect_string_sizes_from_value end_val) @
(collect_string_sizes_from_value counter_val) @
(collect_string_sizes_from_value ctx_val) @
(concat_map collect_string_sizes_from_instr body_instructions)
| IRBreak -> []
| IRContinue -> []
| IRCondReturn (cond_val, ret_if_true, ret_if_false) ->
let cond_sizes = collect_string_sizes_from_value cond_val in
let true_sizes = match ret_if_true with
| Some ret_val -> collect_string_sizes_from_value ret_val
| None -> []
in
let false_sizes = match ret_if_false with
| Some ret_val -> collect_string_sizes_from_value ret_val
| None -> []
in
cond_sizes @ true_sizes @ false_sizes
| IRTry (try_instructions, _catch_clauses) ->
concat_map collect_string_sizes_from_instr try_instructions
| IRThrow _error_code ->
[] (* Throw statements don't contain values to collect *)
| IRDefer defer_instructions ->
concat_map collect_string_sizes_from_instr defer_instructions
| IRTailCall (_, args, _) ->
concat_map collect_string_sizes_from_value args
| IRStructOpsRegister (instance_val, struct_ops_val) ->
(collect_string_sizes_from_value instance_val) @ (collect_string_sizes_from_value struct_ops_val)
| IRObjectNew (dest_val, _) ->
collect_string_sizes_from_value dest_val
| IRObjectNewWithFlag (dest_val, _, flag_val) ->
(collect_string_sizes_from_value dest_val) @ (collect_string_sizes_from_value flag_val)
| IRObjectDelete ptr_val ->
collect_string_sizes_from_value ptr_val
| IRRingbufOp (ringbuf_val, _) ->
collect_string_sizes_from_value ringbuf_val
let collect_string_sizes_from_function ir_func =
concat_map (fun block -> concat_map collect_string_sizes_from_instr block.instructions) ir_func.basic_blocks
let collect_string_sizes_from_multi_program ir_multi_prog =
let program_sizes = concat_map (fun ir_prog -> collect_string_sizes_from_function ir_prog.entry_function) (Ir.get_programs ir_multi_prog) in
(* Also collect from kernel functions *)
let kernel_func_sizes = concat_map (fun ir_func -> collect_string_sizes_from_function ir_func) (Ir.get_kernel_functions ir_multi_prog) in
(* Also collect from struct field types in source_declarations *)
let struct_field_sizes = concat_map (fun decl ->
match decl.Ir.decl_desc with
| Ir.IRDeclStructDef (_, fields, _) ->
concat_map (fun (_, field_type) -> collect_string_sizes_from_type field_type) fields
| _ -> []
) ir_multi_prog.Ir.source_declarations in
program_sizes @ kernel_func_sizes @ struct_field_sizes
(** Collect enum definitions from IR types *)
let collect_enum_definitions ir_multi_prog =
let enum_map = Hashtbl.create 16 in
(* Build a set of kernel-defined enum names from source_declarations *)
let kernel_defined_enums = List.fold_left (fun acc decl ->
match decl.Ir.decl_desc with
| Ir.IRDeclEnumDef (name, _, pos) when is_kernel_defined_type pos ->
StringSet.add name acc
| _ -> acc
) StringSet.empty ir_multi_prog.Ir.source_declarations in
let rec collect_from_type = function
| IREnum (name, values) -> Hashtbl.replace enum_map name values
| IRPointer (inner_type, _) -> collect_from_type inner_type
| IRArray (inner_type, _, _) -> collect_from_type inner_type
| IRResult (ok_type, err_type) ->
collect_from_type ok_type; collect_from_type err_type
| _ -> ()
in
let collect_from_map_def map_def =
collect_from_type map_def.map_key_type;
collect_from_type map_def.map_value_type
in
let collect_from_value ir_val =
collect_from_type ir_val.val_type;
(* Also collect from enum constants *)
(match ir_val.value_desc with
| IREnumConstant (enum_name, constant_name, value) ->
(* Filter out kernel-defined enums using the set built from source_declarations *)
if not (StringSet.mem enum_name kernel_defined_enums) then (
let current_values = try Hashtbl.find enum_map enum_name with Not_found -> [] in
let updated_values = (constant_name, value) :: (List.filter (fun (name, _) -> name <> constant_name) current_values) in
Hashtbl.replace enum_map enum_name updated_values
)
| _ -> ())
in
let collect_from_expr ir_expr =
match ir_expr.expr_desc with
| IRValue ir_val -> collect_from_value ir_val
| IRBinOp (left, _, right) ->
collect_from_value left; collect_from_value right
| IRUnOp (_, ir_val) -> collect_from_value ir_val
| IRCast (ir_val, target_type) ->
collect_from_value ir_val; collect_from_type target_type
| IRFieldAccess (obj_val, _) -> collect_from_value obj_val
| IRStructLiteral (_, field_assignments) ->
List.iter (fun (_, field_val) -> collect_from_value field_val) field_assignments
| IRMatch (matched_val, arms) ->
(* Collect from matched expression and all arms *)
collect_from_value matched_val;
List.iter (fun arm -> collect_from_value arm.ir_arm_value) arms
in
let rec collect_from_instr ir_instr =
match ir_instr.instr_desc with
| IRAssign (dest_val, expr) ->
collect_from_value dest_val; collect_from_expr expr
| IRVariableDecl (_dest_val, _typ, init_expr_opt) ->
(* New unified variable declaration *)
(match init_expr_opt with
| Some init_expr -> collect_from_expr init_expr
| None -> ())
| IRCall (_, args, ret_opt) ->
List.iter collect_from_value args;
(match ret_opt with Some ret_val -> collect_from_value ret_val | None -> ())
| IRMapLoad (map_val, key_val, dest_val, _) ->
collect_from_value map_val; collect_from_value key_val; collect_from_value dest_val
| IRMapStore (map_val, key_val, value_val, _) ->
collect_from_value map_val; collect_from_value key_val; collect_from_value value_val
| IRMapDelete (map_val, key_val) ->
collect_from_value map_val; collect_from_value key_val
| IRReturn (Some ret_val) -> collect_from_value ret_val
| IRIf (cond_val, then_instrs, else_instrs_opt) ->
collect_from_value cond_val;
List.iter collect_from_instr then_instrs;
(match else_instrs_opt with Some instrs -> List.iter collect_from_instr instrs | None -> ())
| _ -> ()
in
let collect_from_function ir_func =
List.iter (fun block ->
List.iter collect_from_instr block.instructions
) ir_func.basic_blocks
in
(* Collect from global maps *)
List.iter collect_from_map_def (Ir.get_global_maps ir_multi_prog);
(* Collect from all programs *)
List.iter (fun ir_prog ->
collect_from_function ir_prog.entry_function;
) (Ir.get_programs ir_multi_prog);
enum_map
(** Generate enum definition *)
let generate_enum_definition ctx enum_name enum_values =
emit_line ctx (sprintf "enum %s {" enum_name);
increase_indent ctx;
let value_count = List.length enum_values in
List.iteri (fun i (const_name, value) ->
let line = sprintf "%s = %s%s" const_name (Ast.IntegerValue.to_string value) (if i = value_count - 1 then "" else ",") in
emit_line ctx line
) enum_values;
decrease_indent ctx;
emit_line ctx "};";
emit_blank_line ctx
(** Generate enum definitions *)
let generate_enum_definitions ctx ir_multi_prog =
let enum_map = collect_enum_definitions ir_multi_prog in
if Hashtbl.length enum_map > 0 then (
let all_enums = Hashtbl.fold (fun enum_name enum_values acc ->
(* Only include enums that have values *)
if enum_values <> [] then
(enum_name, enum_values) :: acc
else
acc
) enum_map [] in
if all_enums <> [] then (
emit_line ctx "/* Enum definitions */";
List.iter (fun (enum_name, enum_values) ->
generate_enum_definition ctx enum_name enum_values
) all_enums;
emit_blank_line ctx
)
)
(** Generate string type definitions *)
let generate_string_typedefs ctx ir_multi_prog =
let all_sizes = collect_string_sizes_from_multi_program ir_multi_prog in
let unique_sizes = List.sort_uniq compare all_sizes in
if unique_sizes <> [] then (
emit_line ctx "/* String type definitions */";
List.iter (fun size ->
emit_line ctx (sprintf "typedef struct { char data[%d]; __u16 len; } str_%d_t;" (size + 1) size)
) unique_sizes;
emit_blank_line ctx
)
(** Generate config struct definition and map *)
let generate_config_map_definition ctx config_decl =
let config_name = config_decl.config_name in
let struct_name = sprintf "%s_config" config_name in
(* Generate C struct for config *)
emit_line ctx (sprintf "struct %s {" struct_name);
increase_indent ctx;
List.iter (fun field ->
let field_declaration = match field.field_type with
| IRU8 -> sprintf "__u8 %s;" field.field_name
| IRU16 -> sprintf "__u16 %s;" field.field_name
| IRU32 -> sprintf "__u32 %s;" field.field_name
| IRU64 -> sprintf "__u64 %s;" field.field_name
| IRI8 -> sprintf "__s8 %s;" field.field_name
| IRBool -> sprintf "__u8 %s;" field.field_name (* bool -> u8 for BPF compatibility *)
| IRChar -> sprintf "char %s;" field.field_name
| IRArray (IRU16, size, _) -> sprintf "__u16 %s[%d];" field.field_name size
| IRArray (IRU32, size, _) -> sprintf "__u32 %s[%d];" field.field_name size
| IRArray (IRU64, size, _) -> sprintf "__u64 %s[%d];" field.field_name size
| _ -> sprintf "__u32 %s;" field.field_name (* fallback *)
in
emit_line ctx field_declaration
) config_decl.config_fields;
decrease_indent ctx;
emit_line ctx "};";
emit_blank_line ctx;
(* Generate array map for config (single entry at index 0) *)
let map_name = sprintf "%s_config_map" config_name in
emit_line ctx "struct {";
increase_indent ctx;
emit_line ctx "__uint(type, BPF_MAP_TYPE_ARRAY);";
emit_line ctx "__uint(max_entries, 1);";
emit_line ctx "__uint(key_size, sizeof(__u32));";
emit_line ctx (sprintf "__uint(value_size, sizeof(struct %s));" struct_name);
decrease_indent ctx;
emit_line ctx (sprintf "} %s SEC(\".maps\");" map_name);
emit_blank_line ctx;
(* Generate helper function to access config *)
emit_line ctx (sprintf "static inline struct %s* get_%s_config(void) {" struct_name config_name);
increase_indent ctx;
emit_line ctx "__u32 key = 0;";
emit_line ctx (sprintf "struct %s *config = bpf_map_lookup_elem(&%s, &key);" struct_name map_name);
emit_line ctx "if (!config) {";
increase_indent ctx;
emit_line ctx "/* Config not initialized - this should not happen in normal operation */";
emit_line ctx "return NULL;";
decrease_indent ctx;
emit_line ctx "}";
emit_line ctx "return config;";
decrease_indent ctx;
emit_line ctx "}";
emit_blank_line ctx
(** Check if IR multi-program contains object allocation instructions *)
let rec check_object_allocation_usage_in_instrs instrs =
List.exists (fun instr ->
match instr.instr_desc with
| IRObjectNew (_, _) | IRObjectDelete _ -> true
| IRIf (_, then_body, else_body) ->
(check_object_allocation_usage_in_instrs then_body) ||
(match else_body with
| Some else_instrs -> check_object_allocation_usage_in_instrs else_instrs
| None -> false)
| IRIfElseChain (conditions_and_bodies, final_else) ->
(List.exists (fun (_, then_body) ->
check_object_allocation_usage_in_instrs then_body
) conditions_and_bodies) ||
(match final_else with
| Some else_instrs -> check_object_allocation_usage_in_instrs else_instrs
| None -> false)
| IRBpfLoop (_, _, _, _, body_instrs) ->
check_object_allocation_usage_in_instrs body_instrs
| IRTry (try_instrs, catch_clauses) ->
(check_object_allocation_usage_in_instrs try_instrs) ||
(List.exists (fun clause ->
check_object_allocation_usage_in_instrs clause.catch_body
) catch_clauses)
| IRDefer defer_instrs ->
check_object_allocation_usage_in_instrs defer_instrs
| _ -> false
) instrs
let check_object_allocation_usage_in_function ir_func =
List.exists (fun block ->
check_object_allocation_usage_in_instrs block.instructions
) ir_func.basic_blocks
let check_object_allocation_usage ir_multi_prog =
(* Check all programs *)
(List.exists (fun ir_prog ->
check_object_allocation_usage_in_function ir_prog.entry_function
) (Ir.get_programs ir_multi_prog)) ||
(* Check kernel functions *)
(List.exists check_object_allocation_usage_in_function (Ir.get_kernel_functions ir_multi_prog))
(** Check if a single IR program contains object allocation instructions *)
let check_object_allocation_usage_in_program ir_prog =
check_object_allocation_usage_in_function ir_prog.entry_function
(** Check if dynptr functionality is used in IR instructions *)
let rec check_dynptr_usage_in_instrs instrs =
List.exists (fun instr ->
match instr.instr_desc with
| IRRingbufOp (_, _) -> true (* Ring buffer operations always use dynptr *)
| IRStructFieldAssignment (obj_val, _, _) ->
(* Struct field assignments on packet data or map values use dynptr *)
(match detect_memory_region_enhanced obj_val with
| PacketData | MapValue -> true
| _ -> false)
| IRAssign (_, expr) ->
(* Check if assignment expressions use enhanced memory access patterns *)
check_dynptr_usage_in_expr expr
| IRCall (_, args, _) ->
(* Check function call arguments for enhanced memory patterns *)
List.exists check_dynptr_usage_in_value args
| IRIf (condition, then_body, else_body) ->
(check_dynptr_usage_in_value condition) ||
(check_dynptr_usage_in_instrs then_body) ||
(match else_body with
| Some else_instrs -> check_dynptr_usage_in_instrs else_instrs
| None -> false)
| IRIfElseChain (conditions_and_bodies, final_else) ->
(List.exists (fun (condition, then_body) ->
(check_dynptr_usage_in_value condition) ||
(check_dynptr_usage_in_instrs then_body)
) conditions_and_bodies) ||
(match final_else with
| Some else_instrs -> check_dynptr_usage_in_instrs else_instrs
| None -> false)
| IRBpfLoop (_, _, _, _, body_instrs) ->
check_dynptr_usage_in_instrs body_instrs
| _ -> false
) instrs
and check_dynptr_usage_in_expr expr =
match expr.expr_desc with
| IRValue value -> check_dynptr_usage_in_value value
| IRBinOp (left, _, right) ->
(check_dynptr_usage_in_value left) || (check_dynptr_usage_in_value right)
| IRUnOp (IRDeref, value) ->
(* Dereference operations on packet data or map values use dynptr *)
(match detect_memory_region_enhanced value with
| PacketData | MapValue -> true
| _ -> false)
| IRUnOp (_, value) -> check_dynptr_usage_in_value value
| IRFieldAccess (obj_value, _) ->
(* Field access on packet data or map values uses dynptr *)
(match detect_memory_region_enhanced obj_value with
| PacketData | MapValue -> true
| _ -> false)
| IRCast (value, _) -> check_dynptr_usage_in_value value
| _ -> false
and check_dynptr_usage_in_value value =
match value.value_desc with
| IRMapAccess (_, _, _) -> true (* Map access may use enhanced patterns *)
| _ -> false
(** Check if dynptr functionality is used in a function *)
let check_dynptr_usage_in_function ir_func =
List.exists (fun basic_block ->
check_dynptr_usage_in_instrs basic_block.instructions
) ir_func.basic_blocks
(** Check if dynptr functionality is used in a multi-program *)
let check_dynptr_usage ir_multi_prog =
(* Conservative approach: include dynptr for XDP/TC programs or any enhanced memory access *)
(List.exists (fun ir_prog ->
match ir_prog.program_type with
| Xdp | Tc -> true (* XDP/TC commonly use packet data access *)
| _ -> check_dynptr_usage_in_function ir_prog.entry_function
) (Ir.get_programs ir_multi_prog)) ||
(* Check kernel functions *)
(List.exists check_dynptr_usage_in_function (Ir.get_kernel_functions ir_multi_prog))
(** Check if a single IR program uses dynptr functionality *)
let check_dynptr_usage_in_program ir_prog =
match ir_prog.program_type with
| Xdp | Tc -> true (* XDP/TC commonly use packet data access *)
| _ -> check_dynptr_usage_in_function ir_prog.entry_function
(** Generate dynptr safety macros and helper functions *)
let generate_dynptr_macros ctx =
emit_line ctx "/* eBPF Dynptr API integration for enhanced pointer safety */";
emit_line ctx "/* Using system-provided bpf_dynptr_* helper functions from bpf_helpers.h */";
emit_blank_line ctx;
(* Generate enhanced dynptr safety macros *)
emit_line ctx "/* Enhanced dynptr safety macros */";
emit_line ctx "#define DYNPTR_SAFE_ACCESS(dynptr, offset, size, type) \\";
emit_line ctx " ({ \\";
emit_line ctx " type *__ptr = (type*)bpf_dynptr_data(dynptr, offset, sizeof(type)); \\";
emit_line ctx " __ptr ? *__ptr : (type){0}; \\";
emit_line ctx " })";
emit_blank_line ctx;
emit_line ctx "#define DYNPTR_SAFE_WRITE(dynptr, offset, value, type) \\";
emit_line ctx " ({ \\";
emit_line ctx " type __tmp = (value); \\";
emit_line ctx " bpf_dynptr_write(dynptr, offset, &__tmp, sizeof(type), 0); \\";
emit_line ctx " })";
emit_blank_line ctx;
emit_line ctx "#define DYNPTR_SAFE_READ(dst, dynptr, offset, type) \\";
emit_line ctx " bpf_dynptr_read(dst, sizeof(type), dynptr, offset, 0)";
emit_blank_line ctx;
(* Fallback macros for regular pointers *)
emit_line ctx "/* Fallback macros for regular pointer operations */";
emit_line ctx "#define SAFE_DEREF(ptr) \\";
emit_line ctx " ({ \\";
emit_line ctx " typeof(*ptr) __val = {0}; \\";
emit_line ctx " if (ptr) { \\";
emit_line ctx " __builtin_memcpy(&__val, ptr, sizeof(__val)); \\";
emit_line ctx " } \\";
emit_line ctx " __val; \\";
emit_line ctx " })";
emit_blank_line ctx;
emit_line ctx "#define SAFE_PTR_ACCESS(ptr, field) \\";
emit_line ctx " ({ \\";
emit_line ctx " typeof((ptr)->field) __val = {0}; \\";
emit_line ctx " if (ptr) { \\";
emit_line ctx " __val = (ptr)->field; \\";
emit_line ctx " } \\";
emit_line ctx " __val; \\";
emit_line ctx " })";
emit_blank_line ctx
(** Generate standard eBPF includes *)
let generate_includes ctx ?(program_types=[]) ?(ir_multi_prog=None) ?(ir_program=None) () =
(* Use vmlinux.h which contains all kernel types from BTF *)
let vmlinux_includes = [
"#include \"vmlinux.h\"";
] in
(* Only include essential eBPF helpers, vmlinux.h provides all kernel types *)
let standard_includes = [
"#include <bpf/bpf_helpers.h>";
] in
(* Get context-specific includes for macros not in vmlinux.h *)
let context_includes = List.fold_left (fun acc prog_type ->
let context_type = match prog_type with
| Ast.Tc -> Some "tc"
| Ast.Probe probe_type ->
(match probe_type with
| Ast.Kprobe -> Some "kprobe" (* Only kprobe needs pt_regs includes *)
| Ast.Fprobe -> Some "fprobe") (* Fprobe needs BPF tracing includes *)
| _ -> None
in
match context_type with
| Some ctx_type ->
let includes = Kernelscript_context.Context_codegen.get_context_includes ctx_type in
acc @ includes
| None -> acc
) [] program_types in
(* Remove duplicates between all include sets *)
let all_base_includes = vmlinux_includes @ standard_includes in
let unique_context_includes = List.filter (fun inc ->
not (List.mem inc all_base_includes)) context_includes in
(* For kprobe programs, still use vmlinux.h but include context-specific macro headers *)
let has_kprobe = List.exists (function Ast.Probe Ast.Kprobe -> true | _ -> false) program_types in
if has_kprobe then (
(* Use vmlinux.h and context-specific headers for macros *)
let vmlinux_and_helpers = [
"#include \"vmlinux.h\"";
"#include <bpf/bpf_helpers.h>";
] in
List.iter (emit_line ctx) vmlinux_and_helpers;
List.iter (emit_line ctx) unique_context_includes;
emit_blank_line ctx
) else (
(* For non-kprobe programs, use vmlinux.h and standard processing *)
let all_includes = vmlinux_includes @ standard_includes @ unique_context_includes in
List.iter (emit_line ctx) all_includes;
emit_blank_line ctx;
(* Only include object allocation code if the program actually uses new() or delete() *)
let uses_object_allocation = match ir_multi_prog, ir_program with
| Some multi_prog, _ -> check_object_allocation_usage multi_prog
| None, Some single_prog -> check_object_allocation_usage_in_program single_prog
| None, None -> false (* Conservative: don't include if we can't analyze *)
in
if uses_object_allocation then (
(* Use proper kernel implementation: extern declarations and macros *)
emit_line ctx "extern void *bpf_obj_new_impl(__u64 local_type_id__k, void *meta__ign) __ksym;";
emit_line ctx "extern void bpf_obj_drop_impl(void *p__alloc, void *meta__ign) __ksym;";
emit_blank_line ctx;
(* Use exact kernel implementation for proper typeof handling *)
emit_line ctx "#define ___concat(a, b) a ## b";
emit_line ctx "#ifdef __clang__";
emit_line ctx "#define ___bpf_typeof(type) ((typeof(type) *) 0)";
emit_line ctx "#else";
emit_line ctx "#define ___bpf_typeof1(type, NR) ({ \\";
emit_line ctx " extern typeof(type) *___concat(bpf_type_tmp_, NR); \\";
emit_line ctx " ___concat(bpf_type_tmp_, NR); \\";
emit_line ctx "})";
emit_line ctx "#define ___bpf_typeof(type) ___bpf_typeof1(type, __COUNTER__)";
emit_line ctx "#endif";
emit_blank_line ctx;
(* Add BPF_TYPE_ID_LOCAL constant *)
emit_line ctx "#ifndef BPF_TYPE_ID_LOCAL";
emit_line ctx "#define BPF_TYPE_ID_LOCAL 1";
emit_line ctx "#endif";
emit_blank_line ctx;
emit_line ctx "#define bpf_core_type_id_kernel(type) __builtin_btf_type_id(*(type*)0, 0)";
emit_line ctx "#define bpf_obj_new(type) ((type *)bpf_obj_new_impl(bpf_core_type_id_kernel(type), NULL))";
emit_line ctx "#define bpf_obj_drop(ptr) bpf_obj_drop_impl(ptr, NULL)";
emit_blank_line ctx
)
)
(** Generate map definitions *)
let generate_map_definition ctx map_def =
let map_type_str = ir_map_type_to_c_type map_def.map_type in
let key_type_str = ebpf_type_from_ir_type map_def.map_key_type in
let value_type_str = ebpf_type_from_ir_type map_def.map_value_type in
emit_line ctx "struct {";
increase_indent ctx;
emit_line ctx (sprintf "__uint(type, %s);" map_type_str);
emit_line ctx (sprintf "__uint(max_entries, %d);" map_def.max_entries);
emit_line ctx (sprintf "__type(key, %s);" key_type_str);
emit_line ctx (sprintf "__type(value, %s);" value_type_str);
(* Add map flags if specified *)
if map_def.flags <> 0 then
emit_line ctx (sprintf "__uint(map_flags, 0x%x);" map_def.flags);
(* Note: We do NOT emit __uint(pinning, LIBBPF_PIN_BY_NAME) here when pin_path is specified.
Userspace code will handle pinning to the exact path specified in pin_path. *)
decrease_indent ctx;
emit_line ctx (sprintf "} %s SEC(\".maps\");" map_def.map_name);
emit_blank_line ctx
(** Generate a single regular (non-pinned, non-ringbuf) global variable *)
let generate_single_global_variable ctx global_var =
let c_type = ebpf_type_from_ir_type global_var.global_var_type in
let var_name = global_var.global_var_name in