-
Notifications
You must be signed in to change notification settings - Fork 2
/
btf.go
2031 lines (1697 loc) · 52 KB
/
btf.go
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
package gobpfld
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"math/big"
"strconv"
"unsafe"
"github.com/dylandreimerink/gobpfld/bpfsys"
"github.com/dylandreimerink/gobpfld/bpftypes"
"github.com/dylandreimerink/gobpfld/internal/cstr"
"github.com/dylandreimerink/gobpfld/kernelsupport"
)
// TODO add field to store kernel structure ID's (for map BTFVMLinuxValueTypeID)
// TODO Add global registry for BTF objects to translate IDs to FDs
// TODO Add fuzzing, we should never get panics only errors, critical for stability of library users. (go 1.18)
// TODO (bonus) make code generators for BTF so we can generate C and Go code like bpftool does
// TODO (bonus) test against VMLinux (/sys/kernel/btf/vmlinux)
// TODO (bonus) implement libbpf compatible CO:RE(Compile Once Run Everywhere).
// This works by looking at the BTF of the compiled program to see what it wants to access and rewriting
// the program using the VMLinux on the machine at runtime. This would enable users to compile architecture
// specific kprobe or uprobe code and run it everywhere.
// BTF Type and String info
type BTF struct {
// Parsed type information, the index of the types is equal to their ID's
Types []BTFType
// Parsed Lines information with ELF section relative instruction offsets
Lines []BTFLine
// Parsed function information with ELF section relative instruction offsets
Funcs []BTFFunc
// A mapping of BTF types indexed on name, used to find the currect types for BPF Maps
typesByName map[string]BTFType
// The parsed BTF header
btfHdr *btfHeader
// Contains the full, raw BTF header, string and type bytes.
// Used to load into the kernel.
rawType []byte
StringsTbl StringTbl
// The parsed BTF EXT header
btfExtHdr *btfExtHeader
// Indicates if the BTF is already loaded into the kernel
loaded bool
// The file descriptor of the BTF assigned by the kernel
fd bpfsys.BPFfd
}
func NewBTF() *BTF {
return &BTF{
typesByName: make(map[string]BTFType),
}
}
func (btf *BTF) Fd() (bpfsys.BPFfd, error) {
if !btf.loaded {
return 0, fmt.Errorf("btf is not loaded")
}
return btf.fd, nil
}
type BTFLoadOpts struct {
LogLevel bpftypes.BPFLogLevel
LogSize int
}
func (btf *BTF) Load(opts BTFLoadOpts) (string, error) {
if btf.loaded {
return "", fmt.Errorf("btf is already loaded")
}
if btf.rawType == nil {
return "", fmt.Errorf("btf has no raw type info")
}
// Set a default log size if none is specified
if opts.LogSize == 0 {
opts.LogSize = defaultBPFVerifierLogSize
}
serialized, err := btf.SerializeBTF()
if err != nil {
return "", fmt.Errorf("btf serialization: %w", err)
}
verifierLogBytes := make([]byte, opts.LogSize)
attr := bpfsys.BPFAttrBTFLoad{
BTF: uintptr(unsafe.Pointer(&serialized[0])),
BTFSize: uint32(len(serialized)),
BTFLogBuf: uintptr(unsafe.Pointer(&verifierLogBytes[0])),
BTFLogSize: uint32(opts.LogSize),
BTFLogLevel: opts.LogLevel,
}
fd, err := bpfsys.BTFLoad(&attr)
if err != nil {
return cstr.BytesToString(verifierLogBytes), err
}
btf.fd = fd
btf.loaded = true
return cstr.BytesToString(verifierLogBytes), nil
}
// ErrMissingBTFData is returned when a datastructure indicates that there should be additional bytes but
// the given bytes slice doesn't contain any.
var ErrMissingBTFData = errors.New("missing indicated bytes in slice")
// ParseBTF parses BTF type and string data.
func (btf *BTF) ParseBTF(btfBytes []byte) error {
btf.rawType = btfBytes
headerOffset := uint32(0)
var err error
btf.btfHdr, headerOffset, err = parseBTFHeader(btfBytes)
if err != nil {
return fmt.Errorf("parse header: %w", err)
}
btfLen := len(btfBytes)
if btfLen < int(headerOffset+btf.btfHdr.StringOffset+btf.btfHdr.StringLength) {
return fmt.Errorf("byte sequence shorten than indicated string offset + length")
}
stringsStart := headerOffset + btf.btfHdr.StringOffset
stringsEnd := headerOffset + btf.btfHdr.StringOffset + btf.btfHdr.StringLength
btf.StringsTbl = StringTblFromBlob(btfBytes[stringsStart:stringsEnd])
if btfLen < int(headerOffset+btf.btfHdr.TypeOffset+btf.btfHdr.TypeLength) {
return fmt.Errorf("byte sequence shorten than indicated type offset + length")
}
typesStart := headerOffset + btf.btfHdr.TypeOffset
typesEnd := headerOffset + btf.btfHdr.TypeOffset + btf.btfHdr.TypeLength
btfTypes := btfBytes[typesStart:typesEnd]
var readError error
off := 0
read32 := func() uint32 {
defer func() {
off = off + 4
}()
// return a 0, instread of panicing
if off+4 > len(btfTypes) {
readError = ErrMissingBTFData
return 0
}
v := btf.btfHdr.byteOrder.Uint32(btfTypes[off : off+4])
return v
}
// Type ID 0 is reserved for void, this initial item will make it so that the index in this slice
// is equal to the Type IDs used by other types.
btf.Types = append(btf.Types, &BTFVoidType{})
for off < len(btfTypes) {
ct := (btfType{
NameOffset: read32(),
Info: read32(),
SizeType: read32(),
}).ToCommonType(&btf.StringsTbl)
// The current amount of elements is equal to the index of the next element.
ct.TypeID = len(btf.Types)
var btfType BTFType
switch ct.Kind {
case BTF_KIND_INT:
ct.Size = ct.sizeType
typeData := read32()
btfType = &BTFIntType{
commonType: ct,
Encoding: BTFIntEncoding((typeData & 0x0f000000) >> 24),
Offset: uint8((typeData & 0x00ff0000) >> 16),
Bits: uint8(typeData & 0x000000ff),
}
case BTF_KIND_PTR:
btfType = &BTFPtrType{
commonType: ct,
}
case BTF_KIND_ARRAY:
arr := &BTFArrayType{
commonType: ct,
}
arr.typeID = read32()
arr.indexTypeID = read32()
arr.NumElements = read32()
btfType = arr
case BTF_KIND_STRUCT, BTF_KIND_UNION:
ct.Size = ct.sizeType
members := make([]BTFMember, ct.VLen)
for i := 0; i < int(ct.VLen); i++ {
members[i].Name = btf.StringsTbl.GetStringAtOffset(int(read32()))
members[i].typeID = read32()
// https://elixir.bootlin.com/linux/v5.15.3/source/include/uapi/linux/btf.h#L132
offset := read32()
if ct.KindFlag == 1 {
// If the kind_flag is set, the btf_member.offset contains both member bitfield size and bit offset.
members[i].BitfieldSize = offset >> 24
members[i].BitOffset = offset & 0xffffff
} else {
// If the type info kind_flag is not set, the offset contains only bit offset of the member.
members[i].BitOffset = offset
}
}
if ct.Kind == BTF_KIND_STRUCT {
btfType = &BTFStructType{
commonType: ct,
Members: members,
}
break
}
btfType = &BTFUnionType{
commonType: ct,
Members: members,
}
case BTF_KIND_ENUM:
ct.Size = ct.sizeType
options := make([]BTFEnumOption, ct.VLen)
for i := 0; i < int(ct.VLen); i++ {
options[i].Name = btf.StringsTbl.GetStringAtOffset(int(read32()))
options[i].Value = int32(read32())
}
btfType = &BTFEnumType{
commonType: ct,
Options: options,
}
case BTF_KIND_FWD:
btfType = &BTFForwardType{
commonType: ct,
}
case BTF_KIND_TYPEDEF:
btfType = &BTFTypeDefType{
commonType: ct,
}
case BTF_KIND_VOLATILE:
btfType = &BTFVolatileType{
commonType: ct,
}
case BTF_KIND_CONST:
btfType = &BTFConstType{
commonType: ct,
}
case BTF_KIND_RESTRICT:
btfType = &BTFRestrictType{
commonType: ct,
}
case BTF_KIND_FUNC:
btfType = &BTFFuncType{
commonType: ct,
}
case BTF_KIND_FUNC_PROTO:
params := make([]BTFFuncProtoParam, ct.VLen)
for i := 0; i < int(ct.VLen); i++ {
params[i].Name = btf.StringsTbl.GetStringAtOffset(int(read32()))
params[i].typeID = read32()
}
btfType = &BTFFuncProtoType{
commonType: ct,
Params: params,
}
case BTF_KIND_VAR:
btfType = &BTFVarType{
commonType: ct,
Linkage: read32(),
}
case BTF_KIND_DATASEC:
// The offset of the SizeType uint32 of common type
ctSizeTypeOff := off - 4
variables := make([]BTFDataSecVariable, ct.VLen)
for i := 0; i < int(ct.VLen); i++ {
variables[i].typeID = read32()
variables[i].offsetOffset = int(typesStart) + off
variables[i].Offset = read32()
variables[i].Size = read32()
}
dataSec := &BTFDataSecType{
commonType: ct,
Variables: variables,
sizeOffset: int(typesStart) + ctSizeTypeOff,
}
btfType = dataSec
case BTF_KIND_FLOAT:
ct.Size = ct.sizeType
btfType = &BTFFloatType{
commonType: ct,
}
case BTF_KIND_DECL_TAG:
btfType = &BTFDeclTagType{
commonType: ct,
ComponentIdx: read32(),
}
default:
return fmt.Errorf("unknown BTF kind: %d", ct.Kind)
}
btf.Types = append(btf.Types, btfType)
if ct.Name != "" {
btf.typesByName[ct.Name] = btfType
}
}
if readError != nil {
return readError
}
// Range over all types and resolve type references
for _, btfType := range btf.Types {
switch t := btfType.(type) {
case *BTFPtrType:
t.Type = btf.Types[t.sizeType]
case *BTFArrayType:
t.Type = btf.Types[t.typeID]
t.IndexType = btf.Types[t.indexTypeID]
case *BTFStructType:
for i, member := range t.Members {
t.Members[i].Type = btf.Types[member.typeID]
}
case *BTFUnionType:
for i, member := range t.Members {
t.Members[i].Type = btf.Types[member.typeID]
}
case *BTFTypeDefType:
t.Type = btf.Types[t.sizeType]
case *BTFVolatileType:
t.Type = btf.Types[t.sizeType]
case *BTFConstType:
t.Type = btf.Types[t.sizeType]
case *BTFRestrictType:
t.Type = btf.Types[t.sizeType]
case *BTFFuncType:
t.Type = btf.Types[t.sizeType]
case *BTFFuncProtoType:
t.Type = btf.Types[t.sizeType]
for i, param := range t.Params {
t.Params[i].Type = btf.Types[param.typeID]
}
case *BTFVarType:
t.Type = btf.Types[t.sizeType]
case *BTFDataSecType:
for i, variable := range t.Variables {
t.Variables[i].Type = btf.Types[variable.typeID]
}
case *BTFDeclTagType:
t.Type = btf.Types[t.sizeType]
}
}
// Loop over all types again, this time to verify them
// for _, btfType := range btf.Types {
// TODO implement verification for all types.
// TODO call verification
// }
return nil
}
// ParseBTFExt parses
func (btf *BTF) ParseBTFExt(btfBytes []byte) error {
var err error
headerOffset := uint32(0)
btf.btfExtHdr, headerOffset, err = parseBTFExtHeader(btfBytes)
if err != nil {
return fmt.Errorf("parse header: %w", err)
}
funcsStart := headerOffset + btf.btfExtHdr.FuncOffset
funcsEnd := headerOffset + btf.btfExtHdr.FuncOffset + btf.btfExtHdr.FuncLength
funcs := btfBytes[funcsStart:funcsEnd]
var readError error
off := 0
read32 := func() uint32 {
defer func() {
off = off + 4
}()
// return a 0, instread of panicing
if off+4 > len(funcs) {
readError = ErrMissingBTFData
return 0
}
v := btf.btfExtHdr.byteOrder.Uint32(funcs[off : off+4])
return v
}
funcRecordSize := read32()
for off < len(funcs) {
sectionOffset := read32()
sectionName := btf.StringsTbl.GetStringAtOffset(int(sectionOffset))
numInfo := read32()
for i := 0; i < int(numInfo); i++ {
if funcRecordSize < 8 {
panic("func record smaller than min expected size")
}
f := BTFFunc{
Section: sectionName,
SectionOffset: sectionOffset,
}
f.InstructionOffset = btf.btfExtHdr.byteOrder.Uint32(funcs[off : off+4])
f.TypeID = btf.btfExtHdr.byteOrder.Uint32(funcs[off+4 : off+8])
f.Type = btf.Types[f.TypeID]
btf.Funcs = append(btf.Funcs, f)
// Increment by funcRecordSize, since newer version of BTF might start using larger records.
// This makes the code forward compatible
off += int(funcRecordSize)
}
}
if readError != nil {
return err
}
linesStart := headerOffset + btf.btfExtHdr.LineOffset
linesEnd := headerOffset + btf.btfExtHdr.LineOffset + btf.btfExtHdr.LineLength
lines := btfBytes[linesStart:linesEnd]
off = 0
read32 = func() uint32 {
defer func() {
off = off + 4
}()
// return a 0, instread of panicing
if off+4 > len(lines) {
readError = ErrMissingBTFData
return 0
}
v := btf.btfExtHdr.byteOrder.Uint32(lines[off : off+4])
return v
}
lineRecordSize := read32()
for off < len(lines) {
sectionOffset := read32()
sectionName := btf.StringsTbl.GetStringAtOffset(int(sectionOffset))
numInfo := read32()
for i := 0; i < int(numInfo); i++ {
if lineRecordSize < 16 {
panic("line record smaller than min expected size")
}
l := BTFLine{
Section: sectionName,
SectionOffset: sectionOffset,
}
l.InstructionOffset = btf.btfExtHdr.byteOrder.Uint32(lines[off : off+4])
l.FileNameOffset = btf.btfExtHdr.byteOrder.Uint32(lines[off+4 : off+8])
l.FileName = btf.StringsTbl.GetStringAtOffset(int(l.FileNameOffset))
l.LineOffset = btf.btfExtHdr.byteOrder.Uint32(lines[off+8 : off+12])
l.Line = btf.StringsTbl.GetStringAtOffset(int(l.LineOffset))
col := btf.btfExtHdr.byteOrder.Uint32(lines[off+12 : off+16])
l.LineNumber = col >> 10
l.ColumnNumber = col & 0x3FF
btf.Lines = append(btf.Lines, l)
// Increment by lineRecordSize, since newer version of BTF might start using larger records.
// This makes the code forward compatible
off += int(lineRecordSize)
}
}
if readError != nil {
return err
}
return nil
}
// SerializeBTF takes the contents BTF.Types and serializes it into a byte slice which can be loaded into the kernel
func (btf *BTF) SerializeBTF() ([]byte, error) {
var buf bytes.Buffer
const hdrLen = 6 * 4
// Empty header, patched later
buf.Write(make([]byte, hdrLen))
btf.StringsTbl.Serialize()
for _, t := range btf.Types[1:] {
b, err := t.Serialize(&btf.StringsTbl, btf.btfHdr.byteOrder)
if err != nil {
return nil, err
}
buf.Write(b)
}
typeOff := uint32(0)
typeLen := uint32(buf.Len() - hdrLen)
strOff := typeLen
strLen := uint32(len(btf.StringsTbl.btfStringBlob))
buf.Write(btf.StringsTbl.btfStringBlob)
bytes := buf.Bytes()
btf.btfHdr.byteOrder.PutUint16(bytes[0:2], btfMagic)
// TODO hard code version/flags or get them from the exported fields in BTF
bytes[2] = btf.btfHdr.Version
bytes[3] = btf.btfHdr.Flags
btf.btfHdr.byteOrder.PutUint32(bytes[4:8], hdrLen)
btf.btfHdr.byteOrder.PutUint32(bytes[8:12], typeOff)
btf.btfHdr.byteOrder.PutUint32(bytes[12:16], typeLen)
btf.btfHdr.byteOrder.PutUint32(bytes[16:20], strOff)
btf.btfHdr.byteOrder.PutUint32(bytes[20:24], strLen)
return bytes, nil
}
type StringTbl struct {
Strings []string
offsets map[string]int
btfStringBlob []byte
}
func StringTblFromBlob(blob []byte) StringTbl {
tbl := StringTbl{
offsets: make(map[string]int),
btfStringBlob: blob,
}
off := 0
for _, s := range bytes.Split(blob, []byte{0}) {
name := string(s)
tbl.Strings = append(tbl.Strings, name)
tbl.offsets[name] = off
off += len(s) + 1
}
// Dirty fix, since we use split, the last element will register as ""
// This will reset the map entry so an empty string will always give offset 0
tbl.offsets[""] = 0
tbl.Strings = tbl.Strings[:len(tbl.Strings)-1]
return tbl
}
func (st *StringTbl) Serialize() {
st.offsets = make(map[string]int, len(st.Strings))
var buf bytes.Buffer
for _, s := range st.Strings {
st.offsets[s] = buf.Len()
buf.WriteString(s)
buf.WriteByte(0)
}
st.btfStringBlob = buf.Bytes()
}
func (st *StringTbl) GetStringAtOffset(offset int) string {
// TODO implement stricter parsing and throw errors instead of returning empty strings.
// NOTE current code relies on the fact that offset == 0 will return a "" which is still valid.
// only throw errors on offsets outside of the `strings` bounds
var name string
if offset < len(st.btfStringBlob) {
idx := bytes.IndexByte(st.btfStringBlob[offset:], 0x00)
if idx == -1 {
name = string(st.btfStringBlob[offset:])
} else {
name = string(st.btfStringBlob[offset : offset+idx])
}
}
return name
}
func (st *StringTbl) StrToOffset(str string) int {
return st.offsets[str]
}
// BTFFunc the go version of bpf_func_info. Which is used to link a instruction offset to a function type.
// https://elixir.bootlin.com/linux/v5.15.3/source/include/uapi/linux/bpf.h#L6165
type BTFFunc struct {
// The ELF section in which the function is defined
Section string
// Offset in the strings table to the name of the section
SectionOffset uint32
// Offset from the start of the ELF section to the function
InstructionOffset uint32
// The resolved Type of the Function
Type BTFType
// The TypeID, used to resolve Type
TypeID uint32
}
func (bf BTFFunc) ToKernel() BTFKernelFunc {
return BTFKernelFunc{
InstructionOffset: bf.InstructionOffset,
TypeID: bf.TypeID,
}
}
// BTFKernelFuncSize size of BTFKernelFunc in bytes
var BTFKernelFuncSize = int(unsafe.Sizeof(BTFKernelFunc{}))
// BTFKernelFunc is the version of the BTFFunc struct the way the kernel want to see it.
type BTFKernelFunc struct {
InstructionOffset uint32
TypeID uint32
}
// BTFLine the go version of bpf_line_info. Which maps an instruction to a source code.
// https://elixir.bootlin.com/linux/v5.15.3/source/include/uapi/linux/bpf.h#L6173
type BTFLine struct {
// The ELF section in which the line is defined
Section string
// The offset into the strings table for the section name
SectionOffset uint32
// Offset from the start of the ELF section to the function
InstructionOffset uint32
// The name and path of the source file
FileName string
// The offset into the strings table for the file name
FileNameOffset uint32
// The full line of source code
Line string
// The offset into the strings table for the line.
LineOffset uint32
// The line number within the file
LineNumber uint32
// The column number within Line of the instruction
ColumnNumber uint32
}
func (bl BTFLine) ToKernel() BTFKernelLine {
return BTFKernelLine{
InstructionOffset: bl.InstructionOffset,
FileNameOffset: bl.FileNameOffset,
LineOffset: bl.LineOffset,
LineCol: (bl.LineNumber << 10) & bl.ColumnNumber,
}
}
// BTFKernelLineSize size of BTFKernelLine in bytes
var BTFKernelLineSize = int(unsafe.Sizeof(BTFKernelLine{}))
// BTFKernelLine is the version of the BTFLine struct the way the kernel want to see it.
type BTFKernelLine struct {
InstructionOffset uint32
FileNameOffset uint32
LineOffset uint32
LineCol uint32
}
// BTFMap is a struct which describes a BPF map
type BTFMap struct {
Key BTFType
Value BTFType
}
// BTFType is a BTF type, each Kind has its own corresponding BTFType.
type BTFType interface {
// Returns the TypeID of the type, which is determined by the position of the type within the encoded
// BTF bytes sequence.
GetID() int
GetKind() BTFKind
GetName() string
// Serialize to BTF binary representation
Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)
}
type BTFValueFormater interface {
// Format a byteslice of data to something human-readable using the BTF type information.
// The resulting output is written to `w``, if `pretty` is true the output is pretty printed(with whitespace).
// The func returns the remaining bytes and/or an error.
FormatValue(b []byte, w io.Writer, pretty bool) ([]byte, error)
}
var _ BTFValueFormater = (*BTFIntType)(nil)
// BTFIntType is the type of KIND_INT, it represents a integer type.
type BTFIntType struct {
commonType
// Extra information, mainly useful for pretty printing
Encoding BTFIntEncoding
// specifies the starting bit offset to calculate values for this int
Offset uint8
// The number of actual bits held by this int type
Bits uint8
}
func (t *BTFIntType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error) {
commonBytes := (commonType{
Name: t.Name,
KindFlag: 0,
Kind: BTF_KIND_INT,
VLen: 0,
sizeType: t.Size,
}.ToBTFType(strTbl).ToBytes(order))
// TODO validate t.Encoding, t.Offset, t.Bits
typeBytes := uint32sToBytes(order, uint32(t.Encoding)<<24|uint32(t.Offset)<<16|uint32(t.Bits))
return append(commonBytes, typeBytes...), nil
}
func (t *BTFIntType) FormatValue(b []byte, w io.Writer, pretty bool) ([]byte, error) {
bytes := (t.Bits / 8)
if bytes == 0 {
bytes = 1
}
if len(b) < int(bytes) {
return nil, fmt.Errorf("'%s' not enough bytes, want '%d' got '%d'", t.Name, bytes, len(b))
}
if t.Offset != 0 {
return nil, fmt.Errorf("'%s' non-0 offset int formatting not implemented", t.Name)
}
switch t.Bits {
case 128:
var i big.Int
_, err := fmt.Fprint(w, i.SetBytes(b[:bytes]).Text(10))
if err != nil {
return nil, fmt.Errorf("'%s' error writing bigint: %w", t.Name, err)
}
switch t.Encoding {
case 0:
_, err := fmt.Fprint(w, i)
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
case INT_SIGNED:
return nil, fmt.Errorf("'%s' signed printing of 128 bit number not implemented", t.Name)
case INT_CHAR:
_, err := fmt.Fprintf(w, "%032x", i.Bytes())
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
case INT_BOOL:
_, err := fmt.Fprint(w, i.Sign() > 0)
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
default:
return nil, fmt.Errorf("'%s' unsupported encoding '%d'", t.Name, t.Encoding)
}
case 64:
i := binary.LittleEndian.Uint64(b[:bytes])
switch t.Encoding {
case 0:
_, err := fmt.Fprint(w, i)
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
case INT_SIGNED:
_, err := fmt.Fprint(w, int64(i))
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
case INT_CHAR:
_, err := fmt.Fprintf(w, "%016x", i)
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
case INT_BOOL:
_, err := fmt.Fprint(w, i > 0)
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
default:
return nil, fmt.Errorf("'%s' unsupported encoding '%d'", t.Name, t.Encoding)
}
case 32:
i := binary.LittleEndian.Uint32(b[:bytes])
switch t.Encoding {
case 0:
_, err := fmt.Fprint(w, i)
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
case INT_SIGNED:
_, err := fmt.Fprint(w, int32(i))
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
case INT_CHAR:
_, err := fmt.Fprintf(w, "%08x", i)
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
case INT_BOOL:
_, err := fmt.Fprint(w, i > 0)
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
default:
return nil, fmt.Errorf("'%s' unsupported encoding '%d'", t.Name, t.Encoding)
}
case 16:
i := binary.LittleEndian.Uint16(b[:bytes])
switch t.Encoding {
case 0:
_, err := fmt.Fprint(w, i)
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
case INT_SIGNED:
_, err := fmt.Fprint(w, int16(i))
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
case INT_CHAR:
_, err := fmt.Fprintf(w, "%04x", i)
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
case INT_BOOL:
_, err := fmt.Fprint(w, i > 0)
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
default:
return nil, fmt.Errorf("'%s' unsupported encoding '%d'", t.Name, t.Encoding)
}
case 8:
switch t.Encoding {
case 0:
_, err := fmt.Fprint(w, b[0])
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
case INT_SIGNED:
_, err := fmt.Fprint(w, int8(b[0]))
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
case INT_CHAR:
_, err := fmt.Fprintf(w, "%02x", b[0])
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
case INT_BOOL:
_, err := fmt.Fprint(w, b[0] > 0)
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
default:
return nil, fmt.Errorf("'%s' unsupported encoding '%d'", t.Name, t.Encoding)
}
case 1:
i := b[0] & 1
switch t.Encoding {
case 0, INT_SIGNED:
_, err := fmt.Fprint(w, i)
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
case INT_CHAR:
_, err := fmt.Fprintf(w, "%02x", b[0])
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
case INT_BOOL:
_, err := fmt.Fprint(w, b[0] > 0)
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}
default:
return nil, fmt.Errorf("'%s' unsupported encoding '%d'", t.Name, t.Encoding)
}
default:
return nil, fmt.Errorf("'%s' int bitsize '%d' formatting not implemented", t.Name, t.Bits)
}
return b[bytes:], nil
}
// BTFIntEncoding is used to indicate what the integer encodes, used to determine how to pretty print an integer.
type BTFIntEncoding uint8
const (
// INT_SIGNED the int should be printed at a signed integer
INT_SIGNED BTFIntEncoding = 1 << iota
// INT_CHAR the int should be printed as hex encoded
INT_CHAR
// INT_BOOL the int should be printed as a boolean
INT_BOOL
)
var btfIntEncToStr = map[BTFIntEncoding]string{
0: "(none)",
INT_SIGNED: "Signed",
INT_CHAR: "Char",
INT_BOOL: "Bool",
}
func (ie BTFIntEncoding) String() string {
return fmt.Sprintf("%s (%d)", btfIntEncToStr[ie], ie)
}
var _ BTFValueFormater = (*BTFPtrType)(nil)
// BTFPtrType is the type for KIND_PTR, which represents a pointer type which points to some other type.
type BTFPtrType struct {
commonType
}
func (t *BTFPtrType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error) {
return (commonType{
Name: "",
KindFlag: 0,
Kind: BTF_KIND_PTR,
VLen: 0,
sizeType: uint32(t.Type.GetID()),
}.ToBTFType(strTbl).ToBytes(order)), nil
}
func (t *BTFPtrType) FormatValue(b []byte, w io.Writer, pretty bool) ([]byte, error) {
_, err := fmt.Fprint(w, "*")
if err != nil {
return nil, fmt.Errorf("'%s' write error: %w", t.Name, err)
}