-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbpf_code_generator.cpp
1789 lines (1654 loc) · 79.3 KB
/
bpf_code_generator.cpp
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 (c) eBPF for Windows contributors
// SPDX-License-Identifier: MIT
// Whenever bpf code generate output changes, bpf2c_tests will fail unless the
// expected files in tests\bpf2c_tests\expected are updated. The following
// script can be used to regenerate the expected files:
// generate_expected_bpf2c_output.ps1
//
// Usage:
// .\scripts\generate_expected_bpf2c_output.ps1 <build_output_path>
// Example:
// .\scripts\generate_expected_bpf2c_output.ps1 .\x64\Debug\
#include "bpf_code_generator.h"
// #include "ebpf_api.h"
// #include "ebpf_version.h"
// #define ebpf_inst ebpf_inst_btf
#include "libbtf/btf_map.h"
#include "libbtf/btf_parse.h"
#include "libbtf/btf_type_data.h"
// #include "spec_type_descriptors.hpp"
// #undef ebpf_inst
// #include <windows.h>
#include <cassert>
// #include <format>
#include <functional>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
#include <cstring>
#undef max
#if !defined(_countof)
#define _countof(array) (sizeof(array) / sizeof(array[0]))
#endif
#define INDENT " "
#define LINE_BREAK_WIDTH 120
#define EBPF_MODE_ATOMIC 0xc0
#define EBPF_ATOMIC_FETCH 0x01
#define EBPF_ATOMIC_ADD 0x00
#define EBPF_ATOMIC_ADD_FETCH (0x00 | EBPF_ATOMIC_FETCH)
#define EBPF_ATOMIC_OR 0x40
#define EBPF_ATOMIC_OR_FETCH (0x40 | EBPF_ATOMIC_FETCH)
#define EBPF_ATOMIC_AND 0x50
#define EBPF_ATOMIC_AND_FETCH (0x50 | EBPF_ATOMIC_FETCH)
#define EBPF_ATOMIC_XOR 0xa0
#define EBPF_ATOMIC_XOR_FETCH (0xa0 | EBPF_ATOMIC_FETCH)
#define EBPF_ATOMIC_XCHG (0xe0 | EBPF_ATOMIC_FETCH)
#define EBPF_ATOMIC_CMPXCHG (0xf0 | EBPF_ATOMIC_FETCH)
#define EBPF_OP_ATOMIC64 (INST_CLS_STX | EBPF_MODE_ATOMIC | INST_SIZE_DW)
#define EBPF_OP_ATOMIC (INST_CLS_STX | EBPF_MODE_ATOMIC | INST_SIZE_W)
static const std::string _register_names[11] = {
"r0",
"r1",
"r2",
"r3",
"r4",
"r5",
"r6",
"r7",
"r8",
"r9",
"r10",
};
enum class AluOperations
{
Add,
Sub,
Mul,
Div,
Or,
And,
Lsh,
Rsh,
Neg,
Mod,
Xor,
Mov,
Arsh,
ByteOrder,
};
static const std::string _predicate_format_string[] = {
"", // JA
"{}{} == {}{}", // JEQ
"{}{} > {}{}", // JGT
"{}{} >= {}{}", // JGE
"{}{} & {}{}", // JSET
"{}{} != {}{}", // JNE
"{}{} > {}{}", // JSGT
"{}{} >= {}{}", // JSGE
"", // CALL
"", // EXIT
"{}{} < {}{}", // JLT
"{}{} <= {}{}", // JLE
"{}{} < {}{}", // JSLT
"{}{} <= {}{}", // JSLE
};
#define ADD_OPCODE(X) \
{ \
static_cast<uint8_t>(X), std::string(#X) \
}
// remove EBPF_ATOMIC_ prefix
#define ADD_ATOMIC_OPCODE(X) \
{ \
static_cast<int32_t>(X), std::string(#X).substr(12) \
}
static std::map<int32_t, std::string> _atomic_opcode_name_strings = {
ADD_ATOMIC_OPCODE(EBPF_ATOMIC_ADD),
ADD_ATOMIC_OPCODE(EBPF_ATOMIC_ADD_FETCH),
ADD_ATOMIC_OPCODE(EBPF_ATOMIC_OR),
ADD_ATOMIC_OPCODE(EBPF_ATOMIC_OR_FETCH),
ADD_ATOMIC_OPCODE(EBPF_ATOMIC_AND),
ADD_ATOMIC_OPCODE(EBPF_ATOMIC_AND_FETCH),
ADD_ATOMIC_OPCODE(EBPF_ATOMIC_XOR),
ADD_ATOMIC_OPCODE(EBPF_ATOMIC_XOR_FETCH),
ADD_ATOMIC_OPCODE(EBPF_ATOMIC_XCHG),
ADD_ATOMIC_OPCODE(EBPF_ATOMIC_CMPXCHG)};
static std::map<uint8_t, std::string> _opcode_name_strings = {
ADD_OPCODE(EBPF_OP_ADD_IMM), ADD_OPCODE(EBPF_OP_ADD_REG), ADD_OPCODE(EBPF_OP_SUB_IMM),
ADD_OPCODE(EBPF_OP_SUB_REG), ADD_OPCODE(EBPF_OP_MUL_IMM), ADD_OPCODE(EBPF_OP_MUL_REG),
ADD_OPCODE(EBPF_OP_DIV_IMM), ADD_OPCODE(EBPF_OP_DIV_REG), ADD_OPCODE(EBPF_OP_OR_IMM),
ADD_OPCODE(EBPF_OP_OR_REG), ADD_OPCODE(EBPF_OP_AND_IMM), ADD_OPCODE(EBPF_OP_AND_REG),
ADD_OPCODE(EBPF_OP_LSH_IMM), ADD_OPCODE(EBPF_OP_LSH_REG), ADD_OPCODE(EBPF_OP_RSH_IMM),
ADD_OPCODE(EBPF_OP_RSH_REG), ADD_OPCODE(EBPF_OP_NEG), ADD_OPCODE(EBPF_OP_MOD_IMM),
ADD_OPCODE(EBPF_OP_MOD_REG), ADD_OPCODE(EBPF_OP_XOR_IMM), ADD_OPCODE(EBPF_OP_XOR_REG),
ADD_OPCODE(EBPF_OP_MOV_IMM), ADD_OPCODE(EBPF_OP_MOV_REG), ADD_OPCODE(EBPF_OP_ARSH_IMM),
ADD_OPCODE(EBPF_OP_ARSH_REG), ADD_OPCODE(EBPF_OP_LE), ADD_OPCODE(EBPF_OP_BE),
ADD_OPCODE(EBPF_OP_ADD64_IMM), ADD_OPCODE(EBPF_OP_ADD64_REG), ADD_OPCODE(EBPF_OP_SUB64_IMM),
ADD_OPCODE(EBPF_OP_SUB64_REG), ADD_OPCODE(EBPF_OP_MUL64_IMM), ADD_OPCODE(EBPF_OP_MUL64_REG),
ADD_OPCODE(EBPF_OP_DIV64_IMM), ADD_OPCODE(EBPF_OP_DIV64_REG), ADD_OPCODE(EBPF_OP_OR64_IMM),
ADD_OPCODE(EBPF_OP_OR64_REG), ADD_OPCODE(EBPF_OP_AND64_IMM), ADD_OPCODE(EBPF_OP_AND64_REG),
ADD_OPCODE(EBPF_OP_LSH64_IMM), ADD_OPCODE(EBPF_OP_LSH64_REG), ADD_OPCODE(EBPF_OP_RSH64_IMM),
ADD_OPCODE(EBPF_OP_RSH64_REG), ADD_OPCODE(EBPF_OP_NEG64), ADD_OPCODE(EBPF_OP_MOD64_IMM),
ADD_OPCODE(EBPF_OP_MOD64_REG), ADD_OPCODE(EBPF_OP_XOR64_IMM), ADD_OPCODE(EBPF_OP_XOR64_REG),
ADD_OPCODE(EBPF_OP_MOV64_IMM), ADD_OPCODE(EBPF_OP_MOV64_REG), ADD_OPCODE(EBPF_OP_ARSH64_IMM),
ADD_OPCODE(EBPF_OP_ARSH64_REG), ADD_OPCODE(EBPF_OP_LDXW), ADD_OPCODE(EBPF_OP_LDXH),
ADD_OPCODE(EBPF_OP_LDXB), ADD_OPCODE(EBPF_OP_LDXDW), ADD_OPCODE(EBPF_OP_STW),
ADD_OPCODE(EBPF_OP_STH), ADD_OPCODE(EBPF_OP_STB), ADD_OPCODE(EBPF_OP_STDW),
ADD_OPCODE(EBPF_OP_STXW), ADD_OPCODE(EBPF_OP_STXH), ADD_OPCODE(EBPF_OP_STXB),
ADD_OPCODE(EBPF_OP_STXDW), ADD_OPCODE(EBPF_OP_LDDW), ADD_OPCODE(EBPF_OP_JA),
ADD_OPCODE(EBPF_OP_JEQ_IMM), ADD_OPCODE(EBPF_OP_JEQ_REG), ADD_OPCODE(EBPF_OP_JGT_IMM),
ADD_OPCODE(EBPF_OP_JGT_REG), ADD_OPCODE(EBPF_OP_JGE_IMM), ADD_OPCODE(EBPF_OP_JGE_REG),
ADD_OPCODE(EBPF_OP_JSET_REG), ADD_OPCODE(EBPF_OP_JSET_IMM), ADD_OPCODE(EBPF_OP_JNE_IMM),
ADD_OPCODE(EBPF_OP_JNE_REG), ADD_OPCODE(EBPF_OP_JSGT_IMM), ADD_OPCODE(EBPF_OP_JSGT_REG),
ADD_OPCODE(EBPF_OP_JSGE_IMM), ADD_OPCODE(EBPF_OP_JSGE_REG), ADD_OPCODE(EBPF_OP_CALL),
ADD_OPCODE(EBPF_OP_EXIT), ADD_OPCODE(EBPF_OP_JLT_IMM), ADD_OPCODE(EBPF_OP_JLT_REG),
ADD_OPCODE(EBPF_OP_JLE_IMM), ADD_OPCODE(EBPF_OP_JLE_REG), ADD_OPCODE(EBPF_OP_JSLT_IMM),
ADD_OPCODE(EBPF_OP_JSLT_REG), ADD_OPCODE(EBPF_OP_JSLE_IMM), ADD_OPCODE(EBPF_OP_JSLE_REG),
ADD_OPCODE(EBPF_OP_ATOMIC64), ADD_OPCODE(EBPF_OP_ATOMIC)};
#define IS_ATOMIC_OPCODE(_opcode) \
(((_opcode)&INST_CLS_MASK) == INST_CLS_STX && ((_opcode)&INST_MODE_MASK) == EBPF_MODE_ATOMIC)
#define IS_JMP_CLASS_OPCODE(_opcode) \
(((_opcode)&INST_CLS_MASK) == INST_CLS_JMP || ((_opcode)&INST_CLS_MASK) == INST_CLS_JMP32)
#define IS_JMP32_CLASS_OPCODE(_opcode) (((_opcode)&INST_CLS_MASK) == INST_CLS_JMP32)
#define IS_SIGNED_CMP_OPCODE(_opcode) \
(((_opcode) >> 4) == (EBPF_MODE_JSGT >> 4) || ((_opcode) >> 4) == (EBPF_MODE_JSGE >> 4) || \
((_opcode) >> 4) == (EBPF_MODE_JSLT >> 4) || ((_opcode) >> 4) == (EBPF_MODE_JSLE >> 4))
/**
* @brief Global operator to permit concatenating a safe and unsafe string.
*
* @param[in] lhs Safe string.
* @param[in] rhs Unsafe string.
* @return Unsafe string containing safe string + unsafe string.
*/
bpf_code_generator::unsafe_string
operator+(const std::string& lhs, const bpf_code_generator::unsafe_string& rhs)
{
return bpf_code_generator::unsafe_string(lhs) + rhs;
}
std::string
bpf_code_generator::get_register_name(uint8_t id)
{
if (id >= _countof(_register_names)) {
throw bpf_code_generator_exception("invalid register id");
} else {
current_program->referenced_registers.insert(_register_names[id]);
return _register_names[id];
}
}
ELFIO::section*
bpf_code_generator::get_required_section(const bpf_code_generator::unsafe_string& name)
{
auto section = get_optional_section(name);
if (!section) {
throw bpf_code_generator_exception("ELF file has missing or invalid section " + name);
}
return section;
}
ELFIO::section*
bpf_code_generator::get_optional_section(const bpf_code_generator::unsafe_string& name)
{
auto section = reader.sections[name.raw()];
if (!is_section_valid(section)) {
return nullptr;
}
return section;
}
bool
bpf_code_generator::is_section_valid(const ELFIO::section* section)
{
if (!section) {
return false;
}
if (section->get_data() == nullptr) {
return false;
}
if (section->get_size() == 0) {
return false;
}
return true;
}
bpf_code_generator::bpf_code_generator(
std::istream& stream,
const bpf_code_generator::unsafe_string& c_name,
const std::optional<std::vector<uint8_t>>& elf_file_hash)
: current_program(nullptr), c_name(c_name), path(path), elf_file_hash(elf_file_hash)
{
if (!reader.load(stream)) {
throw bpf_code_generator_exception("can't process ELF file " + c_name);
}
extract_btf_information();
}
bpf_code_generator::bpf_code_generator(
const bpf_code_generator::unsafe_string& c_name, const std::vector<ebpf_inst>& instructions)
: c_name(c_name)
{
current_program = &programs[c_name];
get_register_name(0);
get_register_name(1);
get_register_name(10);
uint32_t offset = 0;
for (const auto& instruction : instructions) {
current_program->output.push_back({instruction, offset++});
}
}
std::vector<bpf_code_generator::unsafe_string>
bpf_code_generator::program_sections()
{
std::vector<bpf_code_generator::unsafe_string> section_names;
for (const auto& section : reader.sections) {
if (!is_section_valid(section.get())) {
continue;
}
bpf_code_generator::unsafe_string name = section->get_name();
if (name.empty() || (section->get_size() == 0) || name == ".text") {
continue;
}
if ((section->get_type() == 1) && (section->get_flags() == 6)) {
section_names.push_back(section->get_name());
}
}
if (section_names.empty()) {
auto text_section = get_optional_section(".text");
if (text_section) {
section_names.push_back(".text");
}
}
return section_names;
}
void
bpf_code_generator::parse(
const ebpf_api_program_info_t* program,
const GUID& program_type,
const GUID& attach_type,
const std::string& program_info_hash_type)
{
current_program = &programs[program->program_name];
get_register_name(0);
get_register_name(1);
get_register_name(10);
current_program->elf_section_name = program->section_name;
current_program->program_name = program->program_name;
current_program->offset_in_section = program->offset_in_section;
set_pe_section_name(program->section_name);
set_program_and_attach_type_and_hash_type(program_type, attach_type, program_info_hash_type);
extract_program(program);
extract_relocations_and_maps(program->section_name);
}
void
bpf_code_generator::set_program_and_attach_type_and_hash_type(
const GUID& program_type, const GUID& attach_type, const std::string& program_info_hash_type)
{
memcpy(¤t_program->program_type, &program_type, sizeof(GUID));
memcpy(¤t_program->expected_attach_type, &attach_type, sizeof(GUID));
current_program->program_info_hash_type = program_info_hash_type;
}
void
bpf_code_generator::set_program_hash_info(const std::optional<std::vector<uint8_t>>& program_info_hash)
{
current_program->program_info_hash = program_info_hash;
}
void
bpf_code_generator::generate(
const bpf_code_generator::unsafe_string& section_name, const bpf_code_generator::unsafe_string& program_name)
{
current_program = &programs[program_name];
generate_labels();
build_function_table();
encode_instructions(section_name);
}
std::vector<int32_t>
bpf_code_generator::get_helper_ids()
{
std::vector<int32_t> helper_ids;
for (const auto& [name, helper] : current_program->helper_functions) {
helper_ids.push_back(helper.id);
}
return helper_ids;
}
void
bpf_code_generator::extract_program(const ebpf_api_program_info_t* program_info)
{
std::vector<ebpf_inst> program{
reinterpret_cast<const ebpf_inst*>(program_info->raw_data),
reinterpret_cast<const ebpf_inst*>(program_info->raw_data + program_info->raw_data_size)};
uint32_t offset = 0;
for (const auto& instruction : program) {
current_program->output.push_back({instruction, offset++});
}
}
// BTF maps sections are identified as any section called ".maps".
// PREVAIL does not support multiple BTF map sections.
static bool
_is_btf_map_section(const std::string& name)
{
return name == ".maps";
}
// Legacy (non-BTF) maps sections are identified as any section called "maps", or matching "maps/<map-name>".
static bool
_is_legacy_map_section(const std::string& name)
{
std::string maps_prefix = "maps/";
return name == "maps" || (name.length() > 5 && name.compare(0, maps_prefix.length(), maps_prefix) == 0);
}
void
bpf_code_generator::visit_symbols(symbol_visitor_t visitor, const unsafe_string& section_name)
{
ELFIO::const_symbol_section_accessor symbols{reader, get_required_section(".symtab")};
auto target_section = get_required_section(section_name);
for (ELFIO::Elf_Xword index = 0; index < symbols.get_symbols_num(); index++) {
std::string unsafe_name{};
ELFIO::Elf64_Addr value{};
ELFIO::Elf_Xword size{};
unsigned char bind{};
unsigned char symbol_type{};
ELFIO::Elf_Half section_index{};
unsigned char other{};
symbols.get_symbol(index, unsafe_name, value, size, bind, symbol_type, section_index, other);
if (section_index != target_section->get_index()) {
continue;
}
if (unsafe_name.empty()) {
continue;
}
unsafe_string name(unsafe_name);
if (value > target_section->get_size()) {
throw bpf_code_generator_exception("invalid symbol value");
}
// Check for overflow of value + size
if ((value + size) < value) {
throw bpf_code_generator_exception("invalid symbol value");
}
if ((value + size) > target_section->get_size()) {
throw bpf_code_generator_exception("invalid symbol value");
}
if (section_index == target_section->get_index()) {
visitor(name, value, bind, symbol_type, size);
}
}
}
template <typename T>
static std::vector<T>
vector_of(const ELFIO::section& sec)
{
auto data = sec.get_data();
auto size = sec.get_size();
if ((size % sizeof(T) != 0) || size > UINT32_MAX || !data) {
throw std::runtime_error("Invalid argument to vector_of");
}
return {(T*)data, (T*)(data + size)};
}
// Parse a BTF maps section.
void
bpf_code_generator::parse_btf_maps_section(const unsafe_string& name)
{
auto map_section = get_optional_section(name);
if (map_section) {
auto btf_section = get_required_section(".BTF");
std::optional<libbtf::btf_type_data> btf_data = vector_of<std::byte>(*btf_section);
std::vector<EbpfMapDescriptor> map_descriptors;
auto map_data = libbtf::parse_btf_map_section(btf_data.value());
std::map<std::string, size_t> map_offsets;
size_t anonymous_map_count = 0;
for (auto& map : map_data) {
if (map.name.empty()) {
map.name = "__anonymous_" + std::to_string(++anonymous_map_count);
}
map_offsets.insert({map.name, map_descriptors.size()});
map_descriptors.push_back({
.original_fd = static_cast<int>(map.type_id),
.type = map.map_type,
.key_size = map.key_size,
.value_size = map.value_size,
.max_entries = map.max_entries,
.inner_map_fd = map.inner_map_type_id != 0 ? map.inner_map_type_id : -1,
});
}
auto map_name_to_index = map_offsets;
size_t index = 0;
std::map<std::pair<size_t, size_t>, unsafe_string> map_names_by_offset;
std::map<unsafe_string, size_t> map_names_to_values_offset;
// Emit map definitions in the same order as the maps in the .maps section.
visit_symbols(
[&](const unsafe_string& unsafe_symbol_name,
uint64_t symbol_value,
unsigned char bind,
unsigned char symbol_type,
uint64_t symbol_size) {
UNREFERENCED_PARAMETER(bind);
UNREFERENCED_PARAMETER(symbol_type);
UNREFERENCED_PARAMETER(symbol_size);
auto range = std::make_pair(symbol_value, symbol_value + symbol_size);
if (map_names_by_offset.find(range) == map_names_by_offset.end()) {
map_names_by_offset[range] = unsafe_symbol_name;
}
},
name);
// Add anonymous maps to the end of the map list.
size_t last_map_offset = map_names_by_offset.size() != 0 ? map_names_by_offset.rbegin()->first.second : 1;
for (auto& map : map_data) {
if (!map.name.starts_with("__anonymous")) {
continue;
}
map_names_by_offset[std::make_pair(last_map_offset, last_map_offset)] = map.name;
last_map_offset++;
}
for (const auto& [range, unsafe_symbol_name] : map_names_by_offset) {
if (map_name_to_index.find(unsafe_symbol_name.raw()) == map_name_to_index.end()) {
throw bpf_code_generator_exception("map symbol not found in map section");
}
ebpf_map_definition_in_file_t map_definition{};
EbpfMapDescriptor map_descriptor = map_descriptors[map_name_to_index[unsafe_symbol_name.raw()]];
map_definition.type = static_cast<ebpf_map_type_t>(map_descriptor.type);
map_definition.key_size = map_descriptor.key_size;
map_definition.value_size = map_descriptor.value_size;
map_definition.max_entries = map_descriptor.max_entries;
map_definition.id = map_descriptor.original_fd;
map_definition.inner_id = map_descriptor.inner_map_fd != -1 ? map_descriptor.inner_map_fd : 0;
// Get pinning data from the BTF data.
auto map_struct = btf_data->get_kind_type<libbtf::btf_kind_struct>(map_descriptor.original_fd);
for (const auto& member : map_struct.members) {
if (member.name == "pinning") {
// This should use value_from_BTF__uint from btf_parser.cpp, but it's static.
auto pinning_type_id = member.type;
// Dereference the pointer type.
pinning_type_id = btf_data->dereference_pointer(pinning_type_id);
// Get the array type.
auto pinning_type = btf_data->get_kind_type<libbtf::btf_kind_array>(pinning_type_id);
// Value is encoded as the number of elements in the array.
map_definition.pinning = static_cast<ebpf_pin_type_t>(pinning_type.count_of_elements);
}
// "values" is a variable length array of pointers to values.
// Compute the offset of the values array and resize the vector
// to hold the initial values.
if (member.name == "values") {
map_names_to_values_offset[unsafe_symbol_name] = member.offset_from_start_in_bits / 8;
if (map_names_to_values_offset[unsafe_symbol_name] > (range.second - range.first)) {
throw bpf_code_generator_exception("map values offset is outside of map range");
}
// Compute the number of initial values and resize the vector.
// Size is the number of bytes in the range minus the offset of the values array divided by the
// size of a pointer.
size_t value_count =
((range.second - range.first) - map_names_to_values_offset[unsafe_symbol_name]) /
sizeof(uintptr_t);
if (value_count > 0) {
// If the map is statically initialized, then the keys must be uint32_t.
if (map_definition.key_size != sizeof(uint32_t)) {
throw bpf_code_generator_exception("map keys must be uint32_t for static initialization");
}
map_initial_values[unsafe_symbol_name].resize(value_count);
}
}
}
map_definitions[unsafe_symbol_name] = {map_definition, index++};
}
// Extract any initial values for maps.
// Maps are stored in the .maps section. The symbols for the .maps section gives the starting and ending offset
// of each map. The relocations for the .maps section give the offset of the initial values for each map.
// Each relocation record is a pair of (offset, symbol) where the symbol is the map value to insert.
// To convert offset to index in the "values" field, the first step is to determine which map the offset is
// for. This is done by finding the map whose range contains the offset. Then the offset is converted to an
// index by subtracting the offset of the values array and dividing by the size of a pointer.
// Finally the value is inserted into the map's initial values vector at the computed index.
auto map_relocation_section = get_optional_section(".rel.maps");
if (map_relocation_section) {
ELFIO::const_symbol_section_accessor symbols{reader, get_required_section(".symtab")};
ELFIO::const_relocation_section_accessor relocation_reader{reader, map_relocation_section};
ELFIO::Elf_Xword relocation_count = relocation_reader.get_entries_num();
for (ELFIO::Elf_Xword relocation_index = 0; relocation_index < relocation_count; relocation_index++) {
ELFIO::Elf64_Addr offset{};
ELFIO::Elf_Word symbol{};
unsigned int type{};
ELFIO::Elf_Sxword addend{};
relocation_reader.get_entry(relocation_index, offset, symbol, type, addend);
{
std::string unsafe_name{};
ELFIO::Elf64_Addr value{};
ELFIO::Elf_Xword size{};
unsigned char bind{};
unsigned char symbol_type{};
ELFIO::Elf_Half section_index{};
unsigned char other{};
if (!symbols.get_symbol(
symbol, unsafe_name, value, size, bind, symbol_type, section_index, other)) {
throw bpf_code_generator_exception("Can't perform relocation at offset ", offset);
}
// Determine which map this offset is in.
// The map_names_by_offset map is sorted by start and end offset of the map.
// The lower_bound function returns the first entry where the (start, end) offset is >=
// (offset, 0). Because this range has an invalid end offset, it will never be an exact match
// and will always return the first map that starts after the offset.
auto iter = map_names_by_offset.lower_bound(std::make_pair(offset, 0));
// Boundary conditions are:
// 1. The offset is before the first map -> iter == map_names_by_offset.begin()
// 2. The offset is after the last map -> iter == map_names_by_offset.end()
// map_names_by_offset cannot be empty because there is at least one map.
// Select the previous map if it exists.
if (iter != map_names_by_offset.begin()) {
iter--;
} else {
// If there is no previous map, then the offset is before the first map.
throw bpf_code_generator_exception("Can't perform relocation at offset ", offset);
}
// Sanity check that the offset is within the map range.
if (offset < iter->first.first || offset > iter->first.second) {
throw bpf_code_generator_exception("Can't perform relocation at offset ", offset);
}
auto map_name = iter->second;
// Convert the relocation offset into an index in the initial value array.
// iter->first.first is the start of map data in the .maps section.
// map_names_to_values_offset[map_name] is the offset of the values array in the map data.
// offset is from the start of the .maps section where the relocation is performed.
// The index is the offset from the start of the values array divided by the size of a pointer.
size_t value_array_start = iter->first.first + map_names_to_values_offset[map_name];
size_t value_array_index = (offset - value_array_start) / sizeof(uintptr_t);
if (value_array_index >= map_initial_values[map_name].size()) {
throw bpf_code_generator_exception("Can't perform relocation at offset ", offset);
}
map_initial_values[map_name][value_array_index] = unsafe_name;
}
}
}
}
}
// Parse global data (currently map information) in the eBPF file.
void
bpf_code_generator::parse()
{
for (auto& section : reader.sections) {
std::string name = section->get_name();
if (_is_btf_map_section(name)) {
parse_btf_maps_section(name);
} else if (_is_legacy_map_section(name)) {
parse_legacy_maps_section(name);
}
}
}
static std::tuple<std::string, ELFIO::Elf_Half>
_get_symbol_name_and_section_index(ELFIO::const_symbol_section_accessor& symbols, ELFIO::Elf_Xword index)
{
std::string symbol_name;
ELFIO::Elf64_Addr value{};
ELFIO::Elf_Xword size{};
unsigned char bind{};
unsigned char type{};
ELFIO::Elf_Half section_index{};
unsigned char other{};
symbols.get_symbol(index, symbol_name, value, size, bind, type, section_index, other);
return {symbol_name, section_index};
}
// We should consider refactoring the code that parses ELF files into a form that can be used by both ebpf-verifier and
// bpf2c.
void
bpf_code_generator::parse_legacy_maps_section(const unsafe_string& name)
{
auto map_section = get_optional_section(name);
if (!map_section) {
return;
}
// Count the number of symbols that point into this maps section.
ELFIO::const_symbol_section_accessor symbols{reader, get_required_section(".symtab")};
int map_count = 0;
for (ELFIO::Elf_Xword index = 0; index < symbols.get_symbols_num(); index++) {
auto [symbol_name, section_index] = _get_symbol_name_and_section_index(symbols, index);
if ((section_index == map_section->get_index()) && !symbol_name.empty()) {
map_count++;
}
}
if (map_count == 0) {
return;
}
size_t data_size = map_section->get_size();
size_t map_record_size = data_size / map_count;
if (map_record_size == 0) {
return;
}
if (data_size % map_record_size != 0) {
throw bpf_code_generator_exception(
"bad maps section size, must be a multiple of " + std::to_string(map_record_size));
}
size_t old_map_count = map_definitions.size();
for (ELFIO::Elf_Xword i = 0; i < symbols.get_symbols_num(); i++) {
std::string unsafe_symbol_name;
ELFIO::Elf64_Addr symbol_value{};
unsigned char symbol_bind{};
unsigned char symbol_type{};
ELFIO::Elf_Half symbol_section_index{};
unsigned char symbol_other{};
ELFIO::Elf_Xword symbol_size{};
symbols.get_symbol(
i,
unsafe_symbol_name,
symbol_value,
symbol_size,
symbol_bind,
symbol_type,
symbol_section_index,
symbol_other);
if (symbol_section_index == map_section->get_index()) {
if (symbol_size != map_record_size) {
throw bpf_code_generator_exception("invalid map size");
}
if (symbol_value > map_section->get_size()) {
throw bpf_code_generator_exception("invalid symbol value");
}
if ((symbol_value + symbol_size) > map_section->get_size()) {
throw bpf_code_generator_exception("invalid symbol value");
}
// Copy the data from the record into an ebpf_map_definition_in_file_t structure,
// zero-padding any extra, and being careful not to overflow the buffer.
map_definitions[unsafe_symbol_name].definition = {};
memcpy(
&map_definitions[unsafe_symbol_name].definition,
map_section->get_data() + symbol_value,
min(sizeof(map_definitions[unsafe_symbol_name].definition), map_record_size));
map_definitions[unsafe_symbol_name].index = old_map_count + (symbol_value / map_record_size);
}
}
if (map_definitions.size() != old_map_count + map_count) {
throw bpf_code_generator_exception("bad maps section, map must have associated symbol");
}
}
void
bpf_code_generator::extract_relocations_and_maps(const bpf_code_generator::unsafe_string& section_name)
{
auto map_section = get_optional_section("maps");
ELFIO::const_symbol_section_accessor symbols{reader, get_required_section(".symtab")};
auto relocations = get_optional_section(".rel" + section_name);
if (!relocations) {
relocations = get_optional_section(".rela" + section_name);
}
if (relocations) {
ELFIO::const_relocation_section_accessor relocation_reader{reader, relocations};
ELFIO::Elf_Xword relocation_count = relocation_reader.get_entries_num();
for (ELFIO::Elf_Xword index = 0; index < relocation_count; index++) {
ELFIO::Elf64_Addr offset{};
ELFIO::Elf_Word symbol{};
unsigned int type{};
ELFIO::Elf_Sxword addend{};
relocation_reader.get_entry(index, offset, symbol, type, addend);
{
std::string unsafe_name{};
ELFIO::Elf64_Addr value{};
ELFIO::Elf_Xword size{};
unsigned char bind{};
unsigned char symbol_type{};
ELFIO::Elf_Half section_index{};
unsigned char other{};
if (!symbols.get_symbol(symbol, unsafe_name, value, size, bind, symbol_type, section_index, other)) {
throw bpf_code_generator_exception("Can't perform relocation at offset ", offset);
}
if (offset < current_program->offset_in_section ||
offset >= current_program->offset_in_section + current_program->output.size() * sizeof(ebpf_inst)) {
// Relocation is for a different program.
continue;
}
current_program->output[(offset - current_program->offset_in_section) / sizeof(ebpf_inst)].relocation =
unsafe_name;
if (map_section && section_index == map_section->get_index()) {
// Check that the map exists in the list of map definitions.
if (map_definitions.find(unsafe_name) == map_definitions.end()) {
throw bpf_code_generator_exception("map not found in map definitions: " + unsafe_name);
}
}
}
}
}
}
void
bpf_code_generator::extract_btf_information()
{
auto btf = get_optional_section(".BTF");
auto btf_ext = get_optional_section(".BTF.ext");
if (!btf || !btf_ext) {
return;
}
std::vector<std::byte> btf_data(
reinterpret_cast<const std::byte*>(btf->get_data()),
reinterpret_cast<const std::byte*>(btf->get_data()) + btf->get_size());
std::vector<std::byte> btf_ext_data(
reinterpret_cast<const std::byte*>(btf_ext->get_data()),
reinterpret_cast<const std::byte*>(btf_ext->get_data()) + btf_ext->get_size());
libbtf::btf_parse_line_information(
btf_data,
btf_ext_data,
[§ion_line_info = this->section_line_info](
const std::string& section,
uint32_t instruction_offset,
const std::string& file_name,
const std::string& source,
uint32_t line_number,
uint32_t column_number) {
line_info_t info{file_name, source, line_number, column_number};
section_line_info[section].emplace(instruction_offset / sizeof(ebpf_inst), info);
});
}
void
bpf_code_generator::generate_labels()
{
std::vector<output_instruction_t>& program_output = current_program->output;
// Tag jump targets
for (size_t i = 0; i < program_output.size(); i++) {
auto& output = program_output[i];
if (!IS_JMP_CLASS_OPCODE(output.instruction.opcode)) {
continue;
}
if (output.instruction.opcode == INST_OP_CALL) {
continue;
}
if (output.instruction.opcode == INST_OP_EXIT) {
continue;
}
int32_t offset =
((output.instruction.opcode == INST_OP_JA32) ? output.instruction.imm : output.instruction.offset);
if ((i + offset + 1) >= program_output.size()) {
throw bpf_code_generator_exception("invalid jump target", i);
}
program_output[i + offset + 1].jump_target = true;
}
// Add labels to instructions that are targets of jumps
size_t label_index = 1;
for (auto& output : program_output) {
if (!output.jump_target) {
continue;
}
output.label = "label_" + std::to_string(label_index++);
}
}
void
bpf_code_generator::build_function_table()
{
std::vector<output_instruction_t>& program_output = current_program->output;
// Gather helper_functions
size_t index = 0;
for (auto& output : program_output) {
if (output.instruction.opcode != INST_OP_CALL) {
continue;
}
bpf_code_generator::unsafe_string name;
if (!output.relocation.empty()) {
name = output.relocation;
} else {
name = "helper_id_";
name += std::to_string(output.instruction.imm);
}
if (current_program->helper_functions.find(name) == current_program->helper_functions.end()) {
current_program->helper_functions[name] = {output.instruction.imm, index++};
}
}
}
void
bpf_code_generator::encode_instructions(const bpf_code_generator::unsafe_string& section_name)
{
std::vector<output_instruction_t>& program_output = current_program->output;
auto program_name = !current_program->program_name.empty() ? current_program->program_name : section_name;
auto helper_array_prefix = program_name.c_identifier() + "_helpers[{}]";
// Encode instructions
for (size_t i = 0; i < program_output.size(); i++) {
auto& output = program_output[i];
auto& inst = output.instruction;
switch (inst.opcode & INST_CLS_MASK) {
case INST_CLS_ALU:
case INST_CLS_ALU64: {
std::string destination = get_register_name(inst.dst);
std::string source;
if (inst.opcode & INST_SRC_REG) {
source = get_register_name(inst.src);
} else {
source = "IMMEDIATE(" + std::to_string(inst.imm) + ")";
}
bool is64bit = (inst.opcode & INST_CLS_MASK) == INST_CLS_ALU64;
AluOperations operation = static_cast<AluOperations>(inst.opcode >> 4);
std::string swap_function;
std::string type;
switch (operation) {
case AluOperations::Add:
output.lines.push_back(std::format("{} += {};", destination, source));
break;
case AluOperations::Sub:
output.lines.push_back(std::format("{} -= {};", destination, source));
break;
case AluOperations::Mul:
output.lines.push_back(std::format("{} *= {};", destination, source));
break;
case AluOperations::Div:
if (is64bit) {
type = (inst.offset == 1) ? "(int64_t)" : "";
output.lines.push_back(std::format(
"{} = {} ? ({}{} / {}{}) : 0;", destination, source, type, destination, type, source));
} else {
type = (inst.offset == 1) ? "(int32_t)" : "(uint32_t)";
output.lines.push_back(std::format(
"{} = (uint32_t){} ? {}{} / {}{} : 0;", destination, source, type, destination, type, source));
}
break;
case AluOperations::Or:
output.lines.push_back(std::format("{} |= {};", destination, source));
break;
case AluOperations::And:
output.lines.push_back(std::format("{} &= {};", destination, source));
break;
case AluOperations::Lsh:
if (is64bit) {
// Shifts of >= 64 bits on 64-bit values result in undefined behavior so mask off the msb of the
// shift size, i.e., the 'source' in this case.
// Note: The 'duplication' of the following two lines for the 32-bit variant is deliberate as this
// allows the use of the (applicable) native size for the shift_mask variable, thus doing away with
// 'casting' that would otherwise be required. This also makes the code more readable.
uint64_t shift_mask = 0x3F;
output.lines.push_back(std::format("{} <<= ({} & {});", destination, source, shift_mask));
} else {
// Shifts of >= 32 bits on 32-bit values result in undefined behavior so mask off the msb of the
// shift size, i.e., the 'source' in this case.
uint32_t shift_mask = 0x1F;
output.lines.push_back(std::format("{} <<= ({} & {});", destination, source, shift_mask));
}
break;
case AluOperations::Rsh:
if (is64bit) {
// Shifts of >= 64 bits on 64-bit values result in undefined behavior so mask off the msb of the
// shift size, i.e., the 'source' in this case.
// Note: The 'duplication' of the following two lines for the 32-bit variant is deliberate as this
// allows the use of the (applicable) native size for the shift_mask variable, thus doing away with
// 'casting' that would otherwise be required. This also makes the code more readable.
uint64_t shift_mask = 0x3F;
output.lines.push_back(std::format("{} >>= ({} & {});", destination, source, shift_mask));
} else {
// Shifts of >= 32 bits on 32-bit values result in undefined behavior so mask off the msb of the
// shift size, i.e., the 'source' in this case.
// The one 'uint32_t' cast here is required to truncate the destination register's initial value to
// 32 bits prior to using it, given that this is a 32-bit rsh operation.
uint32_t shift_mask = 0x1F;
output.lines.push_back(std::format("{} = (uint32_t){};", destination, destination));
output.lines.push_back(std::format("{} >>= ({} & {});", destination, source, shift_mask));
}
break;
case AluOperations::Neg:
output.lines.push_back(std::format("{} = -(int64_t){};", destination, destination));
break;
case AluOperations::Mod:
if (is64bit) {
type = (inst.offset == 1) ? "(int64_t)" : "";
output.lines.push_back(std::format(
"{} = {} ? ({}{} % {}{}) : {}{};",
destination,
source,
type,
destination,
type,
source,
type,
destination));
} else {
type = (inst.offset == 1) ? "(int32_t)" : "(uint32_t)";
output.lines.push_back(std::format(
"{} = (uint32_t){} ? ({}{} % {}{}) : {}{};",
destination,
source,
type,
destination,
type,
source,
type,
destination));
}
break;
case AluOperations::Xor:
output.lines.push_back(std::format("{} ^= {};", destination, source));
break;
case AluOperations::Mov:
type = (is64bit) ? "(uint64_t)(int64_t)" : "(uint32_t)(int32_t)";
switch (inst.offset) {
case 0:
output.lines.push_back(std::format("{} = {};", destination, source));
break;
case 8:
output.lines.push_back(std::format("{} = {}(int8_t){};", destination, type, source));
break;