/
libbpfgo.go
1589 lines (1380 loc) · 41.8 KB
/
libbpfgo.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 libbpfgo
/*
#cgo LDFLAGS: -lelf -lz
#include "libbpfgo.h"
*/
import "C"
import (
"bytes"
"debug/elf"
"encoding/binary"
"errors"
"fmt"
"net"
"path/filepath"
"strings"
"sync"
"syscall"
"unsafe"
)
const (
// Maximum number of channels (RingBuffers + PerfBuffers) supported
maxEventChannels = 512
)
// MajorVersion returns the major semver version of libbpf.
func MajorVersion() int {
return C.LIBBPF_MAJOR_VERSION
}
// MinorVersion returns the minor semver version of libbpf.
func MinorVersion() int {
return C.LIBBPF_MINOR_VERSION
}
// LibbpfVersionString returns the string representation of the libbpf version which
// libbpfgo is linked against
func LibbpfVersionString() string {
return fmt.Sprintf("v%d.%d", MajorVersion(), MinorVersion())
}
type Module struct {
obj *C.struct_bpf_object
links []*BPFLink
perfBufs []*PerfBuffer
ringBufs []*RingBuffer
elf *elf.File
loaded bool
}
type BPFProg struct {
name string
prog *C.struct_bpf_program
module *Module
pinnedPath string
}
type LinkType int
const (
Tracepoint LinkType = iota
RawTracepoint
Kprobe
Kretprobe
LSM
PerfEvent
Uprobe
Uretprobe
Tracing
XDP
Cgroup
CgroupLegacy
Netns
Iter
)
type BPFLinkLegacy struct {
attachType BPFAttachType
cgroupDir string
}
type BPFLink struct {
link *C.struct_bpf_link
prog *BPFProg
linkType LinkType
eventName string
legacy *BPFLinkLegacy // if set, this is a fake BPFLink
}
func (l *BPFLink) DestroyLegacy(linkType LinkType) error {
switch l.linkType {
case CgroupLegacy:
return l.prog.DetachCgroupLegacy(
l.legacy.cgroupDir,
l.legacy.attachType,
)
}
return fmt.Errorf("unable to destroy legacy link")
}
func (l *BPFLink) Destroy() error {
if l.legacy != nil {
return l.DestroyLegacy(l.linkType)
}
if ret := C.bpf_link__destroy(l.link); ret < 0 {
return syscall.Errno(-ret)
}
l.link = nil
return nil
}
func (l *BPFLink) FileDescriptor() int {
return int(C.bpf_link__fd(l.link))
}
// Deprecated: use BPFLink.FileDescriptor() instead.
func (l *BPFLink) GetFd() int {
return l.FileDescriptor()
}
func (l *BPFLink) Pin(pinPath string) error {
path := C.CString(pinPath)
errC := C.bpf_link__pin(l.link, path)
C.free(unsafe.Pointer(path))
if errC != 0 {
return fmt.Errorf("failed to pin link %s to path %s: %w", l.eventName, pinPath, syscall.Errno(-errC))
}
return nil
}
func (l *BPFLink) Unpin(pinPath string) error {
path := C.CString(pinPath)
errC := C.bpf_link__unpin(l.link)
C.free(unsafe.Pointer(path))
if errC != 0 {
return fmt.Errorf("failed to unpin link %s from path %s: %w", l.eventName, pinPath, syscall.Errno(-errC))
}
return nil
}
type PerfBuffer struct {
pb *C.struct_perf_buffer
bpfMap *BPFMap
slot uint
eventsChan chan []byte
lostChan chan uint64
stop chan struct{}
closed bool
wg sync.WaitGroup
}
type RingBuffer struct {
rb *C.struct_ring_buffer
bpfMap *BPFMap
slot uint
stop chan struct{}
closed bool
wg sync.WaitGroup
}
type NewModuleArgs struct {
KConfigFilePath string
BTFObjPath string
BPFObjName string
BPFObjPath string
BPFObjBuff []byte
SkipMemlockBump bool
}
func NewModuleFromFile(bpfObjPath string) (*Module, error) {
return NewModuleFromFileArgs(NewModuleArgs{
BPFObjPath: bpfObjPath,
})
}
// LibbpfStrictMode is an enum as defined in https://github.com/libbpf/libbpf/blob/2cd2d03f63242c048a896179398c68d2dbefe3d6/src/libbpf_legacy.h#L23
type LibbpfStrictMode uint32
const (
LibbpfStrictModeAll LibbpfStrictMode = C.LIBBPF_STRICT_ALL
LibbpfStrictModeNone LibbpfStrictMode = C.LIBBPF_STRICT_NONE
LibbpfStrictModeCleanPtrs LibbpfStrictMode = C.LIBBPF_STRICT_CLEAN_PTRS
LibbpfStrictModeDirectErrs LibbpfStrictMode = C.LIBBPF_STRICT_DIRECT_ERRS
LibbpfStrictModeSecName LibbpfStrictMode = C.LIBBPF_STRICT_SEC_NAME
LibbpfStrictModeNoObjectList LibbpfStrictMode = C.LIBBPF_STRICT_NO_OBJECT_LIST
LibbpfStrictModeAutoRlimitMemlock LibbpfStrictMode = C.LIBBPF_STRICT_AUTO_RLIMIT_MEMLOCK
LibbpfStrictModeMapDefinitions LibbpfStrictMode = C.LIBBPF_STRICT_MAP_DEFINITIONS
)
func (b LibbpfStrictMode) String() (str string) {
x := map[LibbpfStrictMode]string{
LibbpfStrictModeAll: "LIBBPF_STRICT_ALL",
LibbpfStrictModeNone: "LIBBPF_STRICT_NONE",
LibbpfStrictModeCleanPtrs: "LIBBPF_STRICT_CLEAN_PTRS",
LibbpfStrictModeDirectErrs: "LIBBPF_STRICT_DIRECT_ERRS",
LibbpfStrictModeSecName: "LIBBPF_STRICT_SEC_NAME",
LibbpfStrictModeNoObjectList: "LIBBPF_STRICT_NO_OBJECT_LIST",
LibbpfStrictModeAutoRlimitMemlock: "LIBBPF_STRICT_AUTO_RLIMIT_MEMLOCK",
LibbpfStrictModeMapDefinitions: "LIBBPF_STRICT_MAP_DEFINITIONS",
}
str, ok := x[b]
if !ok {
str = LibbpfStrictModeNone.String()
}
return str
}
// NOTE: libbpf has started raising limits by default but, unfortunately, that
// seems to be failing in current libbpf version. The memory limit bump might be
// removed once this is sorted out.
func bumpMemlockRlimit() error {
var rLimit syscall.Rlimit
rLimit.Max = 512 << 20 /* 512 MBs */
rLimit.Cur = 512 << 20 /* 512 MBs */
err := syscall.Setrlimit(C.RLIMIT_MEMLOCK, &rLimit)
if err != nil {
return fmt.Errorf("error setting rlimit: %v", err)
}
return nil
}
func SetStrictMode(mode LibbpfStrictMode) {
C.libbpf_set_strict_mode(uint32(mode))
}
func NewModuleFromFileArgs(args NewModuleArgs) (*Module, error) {
f, err := elf.Open(args.BPFObjPath)
if err != nil {
return nil, err
}
C.cgo_libbpf_set_print_fn()
// If skipped, we rely on libbpf to do the bumping if deemed necessary
if !args.SkipMemlockBump {
// TODO: remove this once libbpf memory limit bump issue is solved
if err := bumpMemlockRlimit(); err != nil {
return nil, err
}
}
opts := C.struct_bpf_object_open_opts{}
opts.sz = C.sizeof_struct_bpf_object_open_opts
bpfFile := C.CString(args.BPFObjPath)
defer C.free(unsafe.Pointer(bpfFile))
// instruct libbpf to use user provided kernel BTF file
if args.BTFObjPath != "" {
btfFile := C.CString(args.BTFObjPath)
opts.btf_custom_path = btfFile
defer C.free(unsafe.Pointer(btfFile))
}
// instruct libbpf to use user provided KConfigFile
if args.KConfigFilePath != "" {
kConfigFile := C.CString(args.KConfigFilePath)
opts.kconfig = kConfigFile
defer C.free(unsafe.Pointer(kConfigFile))
}
obj, errno := C.bpf_object__open_file(bpfFile, &opts)
if obj == nil {
return nil, fmt.Errorf("failed to open BPF object at path %s: %w", args.BPFObjPath, errno)
}
return &Module{
obj: obj,
elf: f,
}, nil
}
func NewModuleFromBuffer(bpfObjBuff []byte, bpfObjName string) (*Module, error) {
return NewModuleFromBufferArgs(NewModuleArgs{
BPFObjBuff: bpfObjBuff,
BPFObjName: bpfObjName,
})
}
func NewModuleFromBufferArgs(args NewModuleArgs) (*Module, error) {
f, err := elf.NewFile(bytes.NewReader(args.BPFObjBuff))
if err != nil {
return nil, err
}
C.cgo_libbpf_set_print_fn()
// TODO: remove this once libbpf memory limit bump issue is solved
if err := bumpMemlockRlimit(); err != nil {
return nil, err
}
if args.BTFObjPath == "" {
args.BTFObjPath = "/sys/kernel/btf/vmlinux"
}
cBTFFilePath := C.CString(args.BTFObjPath)
defer C.free(unsafe.Pointer(cBTFFilePath))
cKconfigPath := C.CString(args.KConfigFilePath)
defer C.free(unsafe.Pointer(cKconfigPath))
cBPFObjName := C.CString(args.BPFObjName)
defer C.free(unsafe.Pointer(cBPFObjName))
cBPFBuff := unsafe.Pointer(C.CBytes(args.BPFObjBuff))
defer C.free(cBPFBuff)
cBPFBuffSize := C.size_t(len(args.BPFObjBuff))
if len(args.KConfigFilePath) <= 2 {
cKconfigPath = nil
}
cOpts, errno := C.cgo_bpf_object_open_opts_new(cBTFFilePath, cKconfigPath, cBPFObjName)
if cOpts == nil {
return nil, fmt.Errorf("failed to create bpf_object_open_opts to %s: %w", args.BPFObjName, errno)
}
defer C.cgo_bpf_object_open_opts_free(cOpts)
obj, errno := C.bpf_object__open_mem(cBPFBuff, cBPFBuffSize, cOpts)
if obj == nil {
return nil, fmt.Errorf("failed to open BPF object %s: %w", args.BPFObjName, errno)
}
return &Module{
obj: obj,
elf: f,
}, nil
}
func (m *Module) Close() {
for _, pb := range m.perfBufs {
pb.Close()
}
for _, rb := range m.ringBufs {
rb.Close()
}
for _, link := range m.links {
if link.link != nil {
link.Destroy()
}
}
C.bpf_object__close(m.obj)
}
func (m *Module) BPFLoadObject() error {
ret := C.bpf_object__load(m.obj)
if ret != 0 {
return fmt.Errorf("failed to load BPF object: %w", syscall.Errno(-ret))
}
m.loaded = true
m.elf.Close()
return nil
}
// InitGlobalVariable sets global variables (defined in .data or .rodata)
// in bpf code. It must be called before the BPF object is loaded.
func (m *Module) InitGlobalVariable(name string, value interface{}) error {
if m.loaded {
return errors.New("must be called before the BPF object is loaded")
}
s, err := getGlobalVariableSymbol(m.elf, name)
if err != nil {
return err
}
bpfMap, err := m.GetMap(s.sectionName)
if err != nil {
return err
}
// get current value
currMapValue, err := bpfMap.InitialValue()
if err != nil {
return err
}
// generate new value
newMapValue := make([]byte, bpfMap.ValueSize())
copy(newMapValue, currMapValue)
data := bytes.NewBuffer(nil)
if err := binary.Write(data, s.byteOrder, value); err != nil {
return err
}
varValue := data.Bytes()
start := s.offset
end := s.offset + len(varValue)
if len(varValue) > s.size || end > bpfMap.ValueSize() {
return errors.New("invalid value")
}
copy(newMapValue[start:end], varValue)
// save new value
err = bpfMap.SetInitialValue(unsafe.Pointer(&newMapValue[0]))
return err
}
func (m *Module) GetMap(mapName string) (*BPFMap, error) {
cs := C.CString(mapName)
bpfMapC, errno := C.bpf_object__find_map_by_name(m.obj, cs)
C.free(unsafe.Pointer(cs))
if bpfMapC == nil {
return nil, fmt.Errorf("failed to find BPF map %s: %w", mapName, errno)
}
bpfMap := &BPFMap{
bpfMap: bpfMapC,
module: m,
}
if !m.loaded {
bpfMap.bpfMapLow = &BPFMapLow{
fd: -1,
info: &BPFMapInfo{},
}
return bpfMap, nil
}
fd := bpfMap.FileDescriptor()
info, err := GetMapInfoByFD(fd)
if err != nil {
// Compatibility Note: Some older kernels lack BTF (BPF Type Format)
// support for specific BPF map types. In such scenarios, libbpf may
// fail (EPERM) when attempting to retrieve information for these maps.
// Reference: https://elixir.bootlin.com/linux/v5.15.75/source/tools/lib/bpf/gen_loader.c#L401
//
// However, we can still get some map info from the BPF map high level API.
bpfMap.bpfMapLow = &BPFMapLow{
fd: fd,
info: &BPFMapInfo{
Type: bpfMap.Type(),
ID: 0,
KeySize: uint32(bpfMap.KeySize()),
ValueSize: uint32(bpfMap.ValueSize()),
MaxEntries: bpfMap.MaxEntries(),
MapFlags: uint32(bpfMap.MapFlags()),
Name: bpfMap.Name(),
IfIndex: bpfMap.IfIndex(),
BTFVmlinuxValueTypeID: 0,
NetnsDev: 0,
NetnsIno: 0,
BTFID: 0,
BTFKeyTypeID: 0,
BTFValueTypeID: 0,
MapExtra: bpfMap.MapExtra(),
},
}
return bpfMap, nil
}
bpfMap.bpfMapLow = &BPFMapLow{
fd: fd,
info: info,
}
return bpfMap, nil
}
// BPFObjectProgramIterator iterates over maps in a BPF object
type BPFObjectIterator struct {
m *Module
prevProg *BPFProg
prevMap *BPFMap
}
func (m *Module) Iterator() *BPFObjectIterator {
return &BPFObjectIterator{
m: m,
prevProg: nil,
prevMap: nil,
}
}
func (it *BPFObjectIterator) NextMap() *BPFMap {
var startMap *C.struct_bpf_map
if it.prevMap != nil && it.prevMap.bpfMap != nil {
startMap = it.prevMap.bpfMap
}
m := C.bpf_object__next_map(it.m.obj, startMap)
if m == nil {
return nil
}
bpfMap := &BPFMap{
bpfMap: m,
module: it.m,
}
it.prevMap = bpfMap
if !bpfMap.module.loaded {
bpfMap.bpfMapLow = &BPFMapLow{
fd: -1,
info: &BPFMapInfo{},
}
return bpfMap
}
fd := bpfMap.FileDescriptor()
info, err := GetMapInfoByFD(fd)
if err != nil {
return nil
}
bpfMap.bpfMapLow = &BPFMapLow{
fd: fd,
info: info,
}
return bpfMap
}
func (it *BPFObjectIterator) NextProgram() *BPFProg {
var startProg *C.struct_bpf_program
if it.prevProg != nil && it.prevProg.prog != nil {
startProg = it.prevProg.prog
}
p := C.bpf_object__next_program(it.m.obj, startProg)
if p == nil {
return nil
}
cName := C.bpf_program__name(p)
prog := &BPFProg{
name: C.GoString(cName),
prog: p,
module: it.m,
}
it.prevProg = prog
return prog
}
// BPFLinkReader read data from a BPF link
type BPFLinkReader struct {
l *BPFLink
fd int
}
func (l *BPFLink) Reader() (*BPFLinkReader, error) {
fd, errno := C.bpf_iter_create(C.int(l.FileDescriptor()))
if fd < 0 {
return nil, fmt.Errorf("failed to create reader: %w", errno)
}
return &BPFLinkReader{
l: l,
fd: int(uintptr(fd)),
}, nil
}
func (i *BPFLinkReader) Read(p []byte) (n int, err error) {
return syscall.Read(i.fd, p)
}
func (i *BPFLinkReader) Close() error {
return syscall.Close(i.fd)
}
func (m *Module) GetProgram(progName string) (*BPFProg, error) {
cs := C.CString(progName)
prog, errno := C.bpf_object__find_program_by_name(m.obj, cs)
C.free(unsafe.Pointer(cs))
if prog == nil {
return nil, fmt.Errorf("failed to find BPF program %s: %w", progName, errno)
}
return &BPFProg{
name: progName,
prog: prog,
module: m,
}, nil
}
func (p *BPFProg) FileDescriptor() int {
return int(C.bpf_program__fd(p.prog))
}
// Deprecated: use BPFProg.FileDescriptor() instead.
func (p *BPFProg) GetFd() int {
return p.FileDescriptor()
}
func (p *BPFProg) Pin(path string) error {
absPath, err := filepath.Abs(path)
if err != nil {
return fmt.Errorf("invalid path: %s: %v", path, err)
}
cs := C.CString(absPath)
ret := C.bpf_program__pin(p.prog, cs)
C.free(unsafe.Pointer(cs))
if ret != 0 {
return fmt.Errorf("failed to pin program %s to %s: %w", p.name, path, syscall.Errno(-ret))
}
p.pinnedPath = absPath
return nil
}
func (p *BPFProg) Unpin(path string) error {
cs := C.CString(path)
ret := C.bpf_program__unpin(p.prog, cs)
C.free(unsafe.Pointer(cs))
if ret != 0 {
return fmt.Errorf("failed to unpin program %s to %s: %w", p.name, path, syscall.Errno(-ret))
}
p.pinnedPath = ""
return nil
}
func (p *BPFProg) GetModule() *Module {
return p.module
}
func (p *BPFProg) Name() string {
return C.GoString(C.bpf_program__name(p.prog))
}
// Deprecated: use BPFProg.Name() instead.
func (p *BPFProg) GetName() string {
return p.Name()
}
func (p *BPFProg) SectionName() string {
return C.GoString(C.bpf_program__section_name(p.prog))
}
// Deprecated: use BPFProg.SectionName() instead.
func (p *BPFProg) GetSectionName() string {
return p.SectionName()
}
func (p *BPFProg) PinPath() string {
return p.pinnedPath // There's no LIBBPF_API for bpf program
}
// Deprecated: use BPFProg.PinPath() instead.
func (p *BPFProg) GetPinPath() string {
return p.PinPath()
}
// BPFProgType is an enum as defined in https://elixir.bootlin.com/linux/latest/source/include/uapi/linux/bpf.h
type BPFProgType uint32
const (
BPFProgTypeUnspec BPFProgType = iota
BPFProgTypeSocketFilter
BPFProgTypeKprobe
BPFProgTypeSchedCls
BPFProgTypeSchedAct
BPFProgTypeTracepoint
BPFProgTypeXdp
BPFProgTypePerfEvent
BPFProgTypeCgroupSkb
BPFProgTypeCgroupSock
BPFProgTypeLwtIn
BPFProgTypeLwtOut
BPFProgTypeLwtXmit
BPFProgTypeSockOps
BPFProgTypeSkSkb
BPFProgTypeCgroupDevice
BPFProgTypeSkMsg
BPFProgTypeRawTracepoint
BPFProgTypeCgroupSockAddr
BPFProgTypeLwtSeg6Local
BPFProgTypeLircMode2
BPFProgTypeSkReuseport
BPFProgTypeFlowDissector
BPFProgTypeCgroupSysctl
BPFProgTypeRawTracepointWritable
BPFProgTypeCgroupSockopt
BPFProgTypeTracing
BPFProgTypeStructOps
BPFProgTypeExt
BPFProgTypeLsm
BPFProgTypeSkLookup
BPFProgTypeSyscall
)
func (b BPFProgType) Value() uint64 { return uint64(b) }
func (b BPFProgType) String() (str string) {
x := map[BPFProgType]string{
BPFProgTypeUnspec: "BPF_PROG_TYPE_UNSPEC",
BPFProgTypeSocketFilter: "BPF_PROG_TYPE_SOCKET_FILTER",
BPFProgTypeKprobe: "BPF_PROG_TYPE_KPROBE",
BPFProgTypeSchedCls: "BPF_PROG_TYPE_SCHED_CLS",
BPFProgTypeSchedAct: "BPF_PROG_TYPE_SCHED_ACT",
BPFProgTypeTracepoint: "BPF_PROG_TYPE_TRACEPOINT",
BPFProgTypeXdp: "BPF_PROG_TYPE_XDP",
BPFProgTypePerfEvent: "BPF_PROG_TYPE_PERF_EVENT",
BPFProgTypeCgroupSkb: "BPF_PROG_TYPE_CGROUP_SKB",
BPFProgTypeCgroupSock: "BPF_PROG_TYPE_CGROUP_SOCK",
BPFProgTypeLwtIn: "BPF_PROG_TYPE_LWT_IN",
BPFProgTypeLwtOut: "BPF_PROG_TYPE_LWT_OUT",
BPFProgTypeLwtXmit: "BPF_PROG_TYPE_LWT_XMIT",
BPFProgTypeSockOps: "BPF_PROG_TYPE_SOCK_OPS",
BPFProgTypeSkSkb: "BPF_PROG_TYPE_SK_SKB",
BPFProgTypeCgroupDevice: "BPF_PROG_TYPE_CGROUP_DEVICE",
BPFProgTypeSkMsg: "BPF_PROG_TYPE_SK_MSG",
BPFProgTypeRawTracepoint: "BPF_PROG_TYPE_RAW_TRACEPOINT",
BPFProgTypeCgroupSockAddr: "BPF_PROG_TYPE_CGROUP_SOCK_ADDR",
BPFProgTypeLwtSeg6Local: "BPF_PROG_TYPE_LWT_SEG6LOCAL",
BPFProgTypeLircMode2: "BPF_PROG_TYPE_LIRC_MODE2",
BPFProgTypeSkReuseport: "BPF_PROG_TYPE_SK_REUSEPORT",
BPFProgTypeFlowDissector: "BPF_PROG_TYPE_FLOW_DISSECTOR",
BPFProgTypeCgroupSysctl: "BPF_PROG_TYPE_CGROUP_SYSCTL",
BPFProgTypeRawTracepointWritable: "BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE",
BPFProgTypeCgroupSockopt: "BPF_PROG_TYPE_CGROUP_SOCKOPT",
BPFProgTypeTracing: "BPF_PROG_TYPE_TRACING",
BPFProgTypeStructOps: "BPF_PROG_TYPE_STRUCT_OPS",
BPFProgTypeExt: "BPF_PROG_TYPE_EXT",
BPFProgTypeLsm: "BPF_PROG_TYPE_LSM",
BPFProgTypeSkLookup: "BPF_PROG_TYPE_SK_LOOKUP",
BPFProgTypeSyscall: "BPF_PROG_TYPE_SYSCALL",
}
str = x[b]
if str == "" {
str = BPFProgTypeUnspec.String()
}
return str
}
type BPFAttachType uint32
const (
BPFAttachTypeCgroupInetIngress BPFAttachType = iota
BPFAttachTypeCgroupInetEgress
BPFAttachTypeCgroupInetSockCreate
BPFAttachTypeCgroupSockOps
BPFAttachTypeSKSKBStreamParser
BPFAttachTypeSKSKBStreamVerdict
BPFAttachTypeCgroupDevice
BPFAttachTypeSKMSGVerdict
BPFAttachTypeCgroupInet4Bind
BPFAttachTypeCgroupInet6Bind
BPFAttachTypeCgroupInet4Connect
BPFAttachTypeCgroupInet6Connect
BPFAttachTypeCgroupInet4PostBind
BPFAttachTypeCgroupInet6PostBind
BPFAttachTypeCgroupUDP4SendMsg
BPFAttachTypeCgroupUDP6SendMsg
BPFAttachTypeLircMode2
BPFAttachTypeFlowDissector
BPFAttachTypeCgroupSysctl
BPFAttachTypeCgroupUDP4RecvMsg
BPFAttachTypeCgroupUDP6RecvMsg
BPFAttachTypeCgroupGetSockOpt
BPFAttachTypeCgroupSetSockOpt
BPFAttachTypeTraceRawTP
BPFAttachTypeTraceFentry
BPFAttachTypeTraceFexit
BPFAttachTypeModifyReturn
BPFAttachTypeLSMMac
BPFAttachTypeTraceIter
BPFAttachTypeCgroupInet4GetPeerName
BPFAttachTypeCgroupInet6GetPeerName
BPFAttachTypeCgroupInet4GetSockName
BPFAttachTypeCgroupInet6GetSockName
BPFAttachTypeXDPDevMap
BPFAttachTypeCgroupInetSockRelease
BPFAttachTypeXDPCPUMap
BPFAttachTypeSKLookup
BPFAttachTypeXDP
BPFAttachTypeSKSKBVerdict
BPFAttachTypeSKReusePortSelect
BPFAttachTypeSKReusePortSelectorMigrate
BPFAttachTypePerfEvent
BPFAttachTypeTraceKprobeMulti
)
func (p *BPFProg) GetType() BPFProgType {
return BPFProgType(C.bpf_program__type(p.prog))
}
func (p *BPFProg) SetAutoload(autoload bool) error {
cbool := C.bool(autoload)
ret := C.bpf_program__set_autoload(p.prog, cbool)
if ret != 0 {
return fmt.Errorf("failed to set bpf program autoload: %w", syscall.Errno(-ret))
}
return nil
}
// AttachGeneric is used to attach the BPF program using autodetection
// for the attach target. You can specify the destination in BPF code
// via the SEC() such as `SEC("fentry/some_kernel_func")`
func (p *BPFProg) AttachGeneric() (*BPFLink, error) {
link, errno := C.bpf_program__attach(p.prog)
if link == nil {
return nil, fmt.Errorf("failed to attach program: %w", errno)
}
bpfLink := &BPFLink{
link: link,
prog: p,
linkType: Tracing,
eventName: fmt.Sprintf("tracing-%s", p.name),
}
return bpfLink, nil
}
// SetAttachTarget can be used to specify the program and/or function to attach
// the BPF program to. To attach to a kernel function specify attachProgFD as 0
func (p *BPFProg) SetAttachTarget(attachProgFD int, attachFuncName string) error {
cs := C.CString(attachFuncName)
ret := C.bpf_program__set_attach_target(p.prog, C.int(attachProgFD), cs)
C.free(unsafe.Pointer(cs))
if ret != 0 {
return fmt.Errorf("failed to set attach target for program %s %s %w", p.name, attachFuncName, syscall.Errno(-ret))
}
return nil
}
func (p *BPFProg) SetProgramType(progType BPFProgType) {
C.bpf_program__set_type(p.prog, C.enum_bpf_prog_type(int(progType)))
}
func (p *BPFProg) SetAttachType(attachType BPFAttachType) {
C.bpf_program__set_expected_attach_type(p.prog, C.enum_bpf_attach_type(int(attachType)))
}
// getCgroupDirFD returns a file descriptor for a given cgroup2 directory path
func getCgroupDirFD(cgroupV2DirPath string) (int, error) {
// revive:disable
const (
O_DIRECTORY int = syscall.O_DIRECTORY
O_RDONLY int = syscall.O_RDONLY
)
// revive:enable
fd, err := syscall.Open(cgroupV2DirPath, O_DIRECTORY|O_RDONLY, 0)
if fd < 0 {
return 0, fmt.Errorf("failed to open cgroupv2 directory path %s: %w", cgroupV2DirPath, err)
}
return fd, nil
}
// AttachCgroup attaches the BPFProg to a cgroup described by given fd.
func (p *BPFProg) AttachCgroup(cgroupV2DirPath string) (*BPFLink, error) {
cgroupDirFD, err := getCgroupDirFD(cgroupV2DirPath)
if err != nil {
return nil, err
}
defer syscall.Close(cgroupDirFD)
link, errno := C.bpf_program__attach_cgroup(p.prog, C.int(cgroupDirFD))
if link == nil {
return nil, fmt.Errorf("failed to attach cgroup on cgroupv2 %s to program %s: %w", cgroupV2DirPath, p.name, errno)
}
// dirName will be used in bpfLink.eventName. eventName follows a format
// convention and is used to better identify link types and what they are
// linked with in case of errors or similar needs. Having eventName as:
// cgroup-progName-/sys/fs/cgroup/unified/ would look weird so replace it
// to be cgroup-progName-sys-fs-cgroup-unified instead.
dirName := strings.ReplaceAll(cgroupV2DirPath[1:], "/", "-")
bpfLink := &BPFLink{
link: link,
prog: p,
linkType: Cgroup,
eventName: fmt.Sprintf("cgroup-%s-%s", p.name, dirName),
}
p.module.links = append(p.module.links, bpfLink)
return bpfLink, nil
}
// AttachCgroupLegacy attaches the BPFProg to a cgroup described by the given
// fd. It first tries to use the most recent attachment method and, if that does
// not work, instead of failing, it tries the legacy way: to attach the cgroup
// eBPF program without previously creating a link. This allows attaching cgroup
// eBPF ingress/egress in older kernels. Note: the first attempt error message
// is filtered out inside libbpf_print_fn() as it is actually a feature probe
// attempt as well.
//
// Related kernel commit: https://github.com/torvalds/linux/commit/af6eea57437a
func (p *BPFProg) AttachCgroupLegacy(cgroupV2DirPath string, attachType BPFAttachType) (*BPFLink, error) {
bpfLink, err := p.AttachCgroup(cgroupV2DirPath)
if err == nil {
return bpfLink, nil
}
// Try the legacy attachment method before fully failing
cgroupDirFD, err := getCgroupDirFD(cgroupV2DirPath)
if err != nil {
return nil, err
}
defer syscall.Close(cgroupDirFD)
progFD := C.bpf_program__fd(p.prog)
ret := C.cgo_bpf_prog_attach_cgroup_legacy(progFD, C.int(cgroupDirFD), C.int(attachType))
if ret < 0 {
return nil, fmt.Errorf("failed to attach (legacy) program %s to cgroupv2 %s", p.name, cgroupV2DirPath)
}
dirName := strings.ReplaceAll(cgroupV2DirPath[1:], "/", "-")
bpfLinkLegacy := &BPFLinkLegacy{
attachType: attachType,
cgroupDir: cgroupV2DirPath,
}
fakeBpfLink := &BPFLink{
link: nil, // detach/destroy made with progfd
prog: p,
eventName: fmt.Sprintf("cgroup-%s-%s", p.name, dirName),
// info bellow needed for detach (there isn't a real ebpf link)
linkType: CgroupLegacy,
legacy: bpfLinkLegacy,
}
return fakeBpfLink, nil
}
// DetachCgroupLegacy detaches the BPFProg from a cgroup described by the given
// fd. This is needed because in legacy attachment there is no BPFLink, just a
// fake one (kernel did not support it, nor libbpf). This function should be
// called by the (*BPFLink)->Destroy() function, since BPFLink is emulated (so
// users don´t need to distinguish between regular and legacy cgroup
// detachments).
func (p *BPFProg) DetachCgroupLegacy(cgroupV2DirPath string, attachType BPFAttachType) error {
cgroupDirFD, err := getCgroupDirFD(cgroupV2DirPath)
if err != nil {
return err
}
defer syscall.Close(cgroupDirFD)
progFD := C.bpf_program__fd(p.prog)
ret := C.cgo_bpf_prog_detach_cgroup_legacy(progFD, C.int(cgroupDirFD), C.int(attachType))
if ret < 0 {
return fmt.Errorf("failed to detach (legacy) program %s from cgroupv2 %s", p.name, cgroupV2DirPath)
}
return nil
}
func (p *BPFProg) AttachXDP(deviceName string) (*BPFLink, error) {
iface, err := net.InterfaceByName(deviceName)
if err != nil {
return nil, fmt.Errorf("failed to find device by name %s: %w", deviceName, err)
}
link, errno := C.bpf_program__attach_xdp(p.prog, C.int(iface.Index))
if link == nil {
return nil, fmt.Errorf("failed to attach xdp on device %s to program %s: %w", deviceName, p.name, errno)
}
bpfLink := &BPFLink{
link: link,
prog: p,
linkType: XDP,
eventName: fmt.Sprintf("xdp-%s-%s", p.name, deviceName),
}
p.module.links = append(p.module.links, bpfLink)
return bpfLink, nil
}
func (p *BPFProg) AttachTracepoint(category, name string) (*BPFLink, error) {
tpCategory := C.CString(category)
tpName := C.CString(name)
link, errno := C.bpf_program__attach_tracepoint(p.prog, tpCategory, tpName)
C.free(unsafe.Pointer(tpCategory))
C.free(unsafe.Pointer(tpName))
if link == nil {
return nil, fmt.Errorf("failed to attach tracepoint %s to program %s: %w", name, p.name, errno)
}
bpfLink := &BPFLink{
link: link,
prog: p,
linkType: Tracepoint,
eventName: name,
}
p.module.links = append(p.module.links, bpfLink)
return bpfLink, nil
}
func (p *BPFProg) AttachRawTracepoint(tpEvent string) (*BPFLink, error) {
cs := C.CString(tpEvent)
link, errno := C.bpf_program__attach_raw_tracepoint(p.prog, cs)
C.free(unsafe.Pointer(cs))
if link == nil {
return nil, fmt.Errorf("failed to attach raw tracepoint %s to program %s: %w", tpEvent, p.name, errno)
}
bpfLink := &BPFLink{
link: link,
prog: p,
linkType: RawTracepoint,
eventName: tpEvent,
}
p.module.links = append(p.module.links, bpfLink)
return bpfLink, nil
}
func (p *BPFProg) AttachLSM() (*BPFLink, error) {
link, errno := C.bpf_program__attach_lsm(p.prog)
if link == nil {
return nil, fmt.Errorf("failed to attach lsm to program %s: %w", p.name, errno)
}
bpfLink := &BPFLink{
link: link,
prog: p,
linkType: LSM,
}
p.module.links = append(p.module.links, bpfLink)
return bpfLink, nil
}