forked from aquasecurity/libbpfgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibbpfgo.go
1285 lines (1090 loc) · 30 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 <bpf/bpf.h>
#include <bpf/libbpf.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <asm-generic/unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/perf_event.h>
#include <linux/unistd.h>
#include <string.h>
#include <unistd.h>
#ifndef MAX_ERRNO
#define MAX_ERRNO 4095
#define IS_ERR_VALUE(x) ((x) >= (unsigned long)-MAX_ERRNO)
static inline bool IS_ERR(const void *ptr) {
return IS_ERR_VALUE((unsigned long)ptr);
}
static inline bool IS_ERR_OR_NULL(const void *ptr) {
return !ptr || IS_ERR_VALUE((unsigned long)ptr);
}
static inline long PTR_ERR(const void *ptr) {
return (long) ptr;
}
#endif
extern void perfCallback(void *ctx, int cpu, void *data, __u32 size);
extern void perfLostCallback(void *ctx, int cpu, __u64 cnt);
extern int ringbufferCallback(void *ctx, void *data, size_t size);
int libbpf_print_fn(enum libbpf_print_level level,
const char *format, va_list args)
{
if (level != LIBBPF_WARN)
return 0;
return vfprintf(stderr, format, args);
}
void set_print_fn() {
libbpf_set_print(libbpf_print_fn);
}
struct ring_buffer * init_ring_buf(int map_fd, uintptr_t ctx) {
struct ring_buffer *rb = NULL;
rb = ring_buffer__new(map_fd, ringbufferCallback, (void*)ctx, NULL);
if (!rb) {
fprintf(stderr, "Failed to initialize ring buffer\n");
return NULL;
}
return rb;
}
struct perf_buffer * init_perf_buf(int map_fd, int page_cnt, uintptr_t ctx) {
struct perf_buffer_opts pb_opts = {};
struct perf_buffer *pb = NULL;
pb_opts.sample_cb = perfCallback;
pb_opts.lost_cb = perfLostCallback;
pb_opts.ctx = (void*)ctx;
pb = perf_buffer__new(map_fd, page_cnt, &pb_opts);
if (libbpf_get_error(pb)) {
fprintf(stderr, "Failed to initialize perf buffer!\n");
return NULL;
}
return pb;
}
int poke_kprobe_events(bool add, const char* name, bool ret) {
char buf[256];
int fd, err;
char pr;
fd = open("/sys/kernel/debug/tracing/kprobe_events", O_WRONLY | O_APPEND, 0);
if (fd < 0) {
err = -errno;
fprintf(stderr, "failed to open kprobe_events file: %d\n", err);
return err;
}
pr = ret ? 'r' : 'p';
if (add)
snprintf(buf, sizeof(buf), "%c:kprobes/%c%s %s", pr, pr, name, name);
else
snprintf(buf, sizeof(buf), "-:kprobes/%c%s", pr, name);
err = write(fd, buf, strlen(buf));
if (err < 0) {
err = -errno;
fprintf(
stderr,
"failed to %s kprobe '%s': %d\n",
add ? "add" : "remove",
buf,
err);
}
close(fd);
return err >= 0 ? 0 : err;
}
int add_kprobe_event(const char* func_name, bool is_kretprobe) {
return poke_kprobe_events(true, func_name, is_kretprobe);
}
int remove_kprobe_event(const char* func_name, bool is_kretprobe) {
return poke_kprobe_events(false, func_name, is_kretprobe);
}
struct bpf_link* attach_kprobe_legacy(
struct bpf_program* prog,
const char* func_name,
bool is_kretprobe) {
char fname[256];
struct perf_event_attr attr;
struct bpf_link* link;
int fd = -1, err, id;
FILE* f = NULL;
char pr;
err = add_kprobe_event(func_name, is_kretprobe);
if (err) {
fprintf(stderr, "failed to create kprobe event: %d\n", err);
return NULL;
}
pr = is_kretprobe ? 'r' : 'p';
snprintf(
fname,
sizeof(fname),
"/sys/kernel/debug/tracing/events/kprobes/%c%s/id",
pr, func_name);
f = fopen(fname, "r");
if (!f) {
fprintf(stderr, "failed to open kprobe id file '%s': %d\n", fname, -errno);
goto err_out;
}
if (fscanf(f, "%d\n", &id) != 1) {
fprintf(stderr, "failed to read kprobe id from '%s': %d\n", fname, -errno);
goto err_out;
}
fclose(f);
f = NULL;
memset(&attr, 0, sizeof(attr));
attr.size = sizeof(attr);
attr.config = id;
attr.type = PERF_TYPE_TRACEPOINT;
attr.sample_period = 1;
attr.wakeup_events = 1;
fd = syscall(__NR_perf_event_open, &attr, -1, 0, -1, PERF_FLAG_FD_CLOEXEC);
if (fd < 0) {
fprintf(
stderr,
"failed to create perf event for kprobe ID %d: %d\n",
id,
-errno);
goto err_out;
}
link = bpf_program__attach_perf_event(prog, fd);
err = libbpf_get_error(link);
if (err) {
fprintf(stderr, "failed to attach to perf event FD %d: %d\n", fd, err);
goto err_out;
}
return link;
err_out:
if (f)
fclose(f);
if (fd >= 0)
close(fd);
remove_kprobe_event(func_name, is_kretprobe);
return NULL;
}
*/
import "C"
import (
"fmt"
"net"
"path/filepath"
"sync"
"syscall"
"unsafe"
"github.com/aquasecurity/libbpfgo/helpers"
)
const (
// Maximum number of channels (RingBuffers + PerfBuffers) supported
maxEventChannels = 512
)
type Module struct {
obj *C.struct_bpf_object
links []*BPFLink
perfBufs []*PerfBuffer
ringBufs []*RingBuffer
}
type BPFMap struct {
name string
bpfMap *C.struct_bpf_map
fd C.int
module *Module
}
type BPFProg struct {
name string
prog *C.struct_bpf_program
module *Module
}
type LinkType int
const (
Tracepoint LinkType = iota
RawTracepoint
Kprobe
Kretprobe
KprobeLegacy
KretprobeLegacy
LSM
PerfEvent
Uprobe
Uretprobe
)
type BPFLink struct {
link *C.struct_bpf_link
prog *BPFProg
linkType LinkType
eventName string
}
func (l *BPFLink) Destroy() error {
ret := C.bpf_link__destroy(l.link)
if ret < 0 {
return syscall.Errno(-ret)
}
return nil
}
func (l *BPFLink) GetFd() int {
return int(C.bpf_link__fd(l.link))
}
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
}
// BPF is using locked memory for BPF maps and various other things.
// By default, this limit is very low - increase to avoid failures
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 errptrError(ptr unsafe.Pointer, format string, args ...interface{}) error {
negErrno := C.PTR_ERR(ptr)
errno := syscall.Errno(-int64(negErrno))
if errno == 0 {
return fmt.Errorf(format, args...)
}
args = append(args, errno.Error())
return fmt.Errorf(format+": %v", args...)
}
type NewModuleArgs struct {
KConfigFilePath string
BTFObjPath string
BPFObjName string
BPFObjPath string
BPFObjBuff []byte
}
func NewModuleFromFile(bpfObjPath string) (*Module, error) {
return NewModuleFromFileArgs(NewModuleArgs{
BPFObjPath: bpfObjPath,
})
}
func NewModuleFromFileArgs(args NewModuleArgs) (*Module, error) {
C.set_print_fn()
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 := C.bpf_object__open_file(bpfFile, &opts)
if C.IS_ERR_OR_NULL(unsafe.Pointer(obj)) {
return nil, errptrError(unsafe.Pointer(obj), "failed to open BPF object %s", args.BPFObjPath)
}
return &Module{
obj: obj,
}, nil
}
func NewModuleFromBuffer(bpfObjBuff []byte, bpfObjName string) (*Module, error) {
return NewModuleFromBufferArgs(NewModuleArgs{
BPFObjBuff: bpfObjBuff,
BPFObjName: bpfObjName,
})
}
func NewModuleFromBufferArgs(args NewModuleArgs) (*Module, error) {
C.set_print_fn()
if err := bumpMemlockRlimit(); err != nil {
return nil, err
}
if args.BTFObjPath == "" {
args.BTFObjPath = "/sys/kernel/btf/vmlinux"
}
btfFile := C.CString(args.BTFObjPath)
bpfName := C.CString(args.BPFObjName)
bpfBuff := unsafe.Pointer(C.CBytes(args.BPFObjBuff))
bpfBuffSize := C.size_t(len(args.BPFObjBuff))
opts := C.struct_bpf_object_open_opts{}
opts.object_name = bpfName
opts.sz = C.sizeof_struct_bpf_object_open_opts
opts.btf_custom_path = btfFile // instruct libbpf to use user provided kernel BTF file
if len(args.KConfigFilePath) > 2 {
kConfigFile := C.CString(args.KConfigFilePath)
opts.kconfig = kConfigFile // instruct libbpf to use user provided KConfigFile
defer C.free(unsafe.Pointer(kConfigFile))
}
obj := C.bpf_object__open_mem(bpfBuff, bpfBuffSize, &opts)
if C.IS_ERR_OR_NULL(unsafe.Pointer(obj)) {
return nil, errptrError(unsafe.Pointer(obj), "failed to open BPF object %s: %v", args.BPFObjName, args.BPFObjBuff[:20])
}
C.free(bpfBuff)
C.free(unsafe.Pointer(bpfName))
C.free(unsafe.Pointer(btfFile))
return &Module{
obj: obj,
}, nil
}
func (m *Module) Close() {
for _, pb := range m.perfBufs {
pb.Close()
}
for _, rb := range m.ringBufs {
rb.Close()
}
for _, link := range m.links {
C.bpf_link__destroy(link.link) // this call will remove non-legacy kprobes
if link.linkType == KprobeLegacy {
cs := C.CString(link.eventName)
C.remove_kprobe_event(cs, false)
C.free(unsafe.Pointer(cs))
}
if link.linkType == KretprobeLegacy {
cs := C.CString(link.eventName)
C.remove_kprobe_event(cs, true)
C.free(unsafe.Pointer(cs))
}
}
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")
}
return nil
}
func (m *Module) GetMap(mapName string) (*BPFMap, error) {
cs := C.CString(mapName)
bpfMap := C.bpf_object__find_map_by_name(m.obj, cs)
C.free(unsafe.Pointer(cs))
if bpfMap == nil {
return nil, fmt.Errorf("failed to find BPF map %s", mapName)
}
return &BPFMap{
bpfMap: bpfMap,
name: mapName,
fd: C.bpf_map__fd(bpfMap),
module: m,
}, nil
}
func (b *BPFMap) Pin(pinPath string) error {
path := C.CString(pinPath)
errC := C.bpf_map__pin(b.bpfMap, path)
C.free(unsafe.Pointer(path))
if errC != 0 {
return fmt.Errorf("failed to pin map %s to path %s", b.name, pinPath)
}
return nil
}
func (b *BPFMap) Unpin(pinPath string) error {
path := C.CString(pinPath)
errC := C.bpf_map__unpin(b.bpfMap, path)
C.free(unsafe.Pointer(path))
if errC != 0 {
return fmt.Errorf("failed to unpin map %s from path %s", b.name, pinPath)
}
return nil
}
func (b *BPFMap) SetPinPath(pinPath string) error {
path := C.CString(pinPath)
errC := C.bpf_map__set_pin_path(b.bpfMap, path)
C.free(unsafe.Pointer(path))
if errC != 0 {
return fmt.Errorf("failed to set pin for map %s to path %s", b.name, pinPath)
}
return nil
}
// Resize changes the map's capacity to maxEntries.
// It should be called after the module was initialized but
// prior to it being loaded with BPFLoadObject.
// Note: for ring buffer and perf buffer, maxEntries is the
// capacity in bytes.
func (b *BPFMap) Resize(maxEntries uint32) error {
errC := C.bpf_map__set_max_entries(b.bpfMap, C.uint(maxEntries))
if errC != 0 {
return fmt.Errorf("failed to resize map %s to %v", b.name, maxEntries)
}
return nil
}
// GetMaxEntries returns the map's capacity.
// Note: for ring buffer and perf buffer, maxEntries is the
// capacity in bytes.
func (b *BPFMap) GetMaxEntries() uint32 {
maxEntries := C.bpf_map__max_entries(b.bpfMap)
return uint32(maxEntries)
}
func (b *BPFMap) GetFd() int {
return int(b.fd)
}
func (b *BPFMap) GetName() string {
return b.name
}
func (b *BPFMap) GetModule() *Module {
return b.module
}
func (b *BPFMap) GetPinPath() string {
pinPathGo := C.GoString(C.bpf_map__get_pin_path(b.bpfMap))
return pinPathGo
}
func (b *BPFMap) IsPinned() bool {
isPinned := C.bpf_map__is_pinned(b.bpfMap)
if isPinned == C.bool(true) {
return true
}
return false
}
func GetUnsafePointer(data interface{}) (unsafe.Pointer, error) {
var dataPtr unsafe.Pointer
switch k := data.(type) {
case int8:
dataPtr = unsafe.Pointer(&k)
case uint8:
dataPtr = unsafe.Pointer(&k)
case int32:
dataPtr = unsafe.Pointer(&k)
case uint32:
dataPtr = unsafe.Pointer(&k)
case int64:
dataPtr = unsafe.Pointer(&k)
case uint64:
dataPtr = unsafe.Pointer(&k)
case []byte:
dataPtr = unsafe.Pointer(&k[0])
default:
return nil, fmt.Errorf("unknown data type %T", data)
}
return dataPtr, nil
}
func (b *BPFMap) KeySize() int {
return int(C.bpf_map__key_size(b.bpfMap))
}
func (b *BPFMap) ValueSize() int {
return int(C.bpf_map__value_size(b.bpfMap))
}
// GetValue takes a pointer to the key which is stored in the map.
// It returns the associated value as a slice of bytes.
// All basic types, and structs are supported as keys.
//
// NOTE: Slices and arrays are also supported but special care
// should be taken as to take a reference to the first element
// in the slice or array instead of the slice/array itself, as to
// avoid undefined behavior.
func (b *BPFMap) GetValue(key unsafe.Pointer) ([]byte, error) {
value := make([]byte, b.ValueSize())
valuePtr := unsafe.Pointer(&value[0])
errC := C.bpf_map_lookup_elem(b.fd, key, valuePtr)
if errC != 0 {
return nil, fmt.Errorf("failed to lookup value %v in map %s", key, b.name)
}
return value, nil
}
// DeleteKey takes a pointer to the key which is stored in the map.
// It removes the key and associated value from the BPFMap.
// All basic types, and structs are supported as keys.
//
// NOTE: Slices and arrays are also supported but special care
// should be taken as to take a reference to the first element
// in the slice or array instead of the slice/array itself, as to
// avoid undefined behavior.
func (b *BPFMap) DeleteKey(key unsafe.Pointer) error {
errC := C.bpf_map_delete_elem(b.fd, key)
if errC != 0 {
return fmt.Errorf("failed to get lookup key %d from map %s", key, b.name)
}
return nil
}
// Update takes a pointer to a key and a value to associate it with in
// the BPFMap. The unsafe.Pointer should be taken on a reference to the
// underlying datatype. All basic types, and structs are supported
//
// NOTE: Slices and arrays are supported but references should be passed
// to the first element in the slice or array.
//
// For example:
//
// key := 1
// value := []byte{'a', 'b', 'c'}
// keyPtr := unsafe.Pointer(&key)
// valuePtr := unsafe.Pointer(&value[0])
// bpfmap.Update(keyPtr, valuePtr)
//
func (b *BPFMap) Update(key, value unsafe.Pointer) error {
errC := C.bpf_map_update_elem(b.fd, key, value, C.BPF_ANY)
if errC != 0 {
return fmt.Errorf("failed to update map %s", b.name)
}
return nil
}
type BPFMapIterator struct {
b *BPFMap
err error
prev []byte
next []byte
}
func (b *BPFMap) Iterator() *BPFMapIterator {
return &BPFMapIterator{
b: b,
prev: nil,
next: nil,
}
}
func (it *BPFMapIterator) Next() bool {
if it.err != nil {
return false
}
prevPtr := unsafe.Pointer(nil)
if it.next != nil {
prevPtr = unsafe.Pointer(&it.next[0])
}
next := make([]byte, it.b.KeySize())
nextPtr := unsafe.Pointer(&next[0])
errC, err := C.bpf_map_get_next_key(it.b.fd, prevPtr, nextPtr)
if errno, ok := err.(syscall.Errno); errC == -1 && ok && errno == C.ENOENT {
return false
}
if err != nil {
it.err = err
return false
}
it.prev = it.next
it.next = next
return true
}
// Key returns the current key value of the iterator, if the most recent call to Next returned true.
// The slice is valid only until the next call to Next.
func (it *BPFMapIterator) Key() []byte {
return it.next
}
// Err returns the last error that ocurred while table.Iter or iter.Next
func (it *BPFMapIterator) Err() error {
return it.err
}
func (m *Module) GetProgram(progName string) (*BPFProg, error) {
cs := C.CString(progName)
prog := 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", progName)
}
return &BPFProg{
name: progName,
prog: prog,
module: m,
}, nil
}
func (p *BPFProg) GetFd() int {
return int(C.bpf_program__fd(p.prog))
}
func (p *BPFProg) GetModule() *Module {
return p.module
}
func (p *BPFProg) GetName() string {
return p.name
}
// BPFProgType is an enum as defined in https://elixir.bootlin.com/linux/latest/source/include/uapi/linux/bpf.h
type BPFProgType uint32
const (
BPFProgTypeUnspec uint32 = 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
)
func (p *BPFProg) GetType() uint32 {
return C.bpf_program__get_type(p.prog)
}
func (p *BPFProg) SetAutoload(autoload bool) error {
cbool := C.bool(autoload)
err := C.bpf_program__set_autoload(p.prog, cbool)
if err != 0 {
return fmt.Errorf("failed to set bpf program autoload")
}
return nil
}
func (p *BPFProg) SetTracepoint() error {
err := C.bpf_program__set_tracepoint(p.prog)
if err != 0 {
return fmt.Errorf("failed to set bpf program as tracepoint")
}
return nil
}
func (p *BPFProg) AttachTracepoint(category, name string) (*BPFLink, error) {
tpCategory := C.CString(category)
tpName := C.CString(name)
link := C.bpf_program__attach_tracepoint(p.prog, tpCategory, tpName)
C.free(unsafe.Pointer(tpCategory))
C.free(unsafe.Pointer(tpName))
if C.IS_ERR_OR_NULL(unsafe.Pointer(link)) {
return nil, errptrError(unsafe.Pointer(link), "failed to attach tracepoint %s to program %s", name, p.name)
}
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 := C.bpf_program__attach_raw_tracepoint(p.prog, cs)
C.free(unsafe.Pointer(cs))
if C.IS_ERR_OR_NULL(unsafe.Pointer(link)) {
return nil, errptrError(unsafe.Pointer(link), "failed to attach raw tracepoint %s to program %s", tpEvent, p.name)
}
bpfLink := &BPFLink{
link: link,
prog: p,
linkType: RawTracepoint,
eventName: tpEvent,
}
p.module.links = append(p.module.links, bpfLink)
return bpfLink, nil
}
func (p *BPFProg) AttachPerfEvent(fd int) (*BPFLink, error) {
link := C.bpf_program__attach_perf_event(p.prog, C.int(fd))
if link == nil {
return nil, fmt.Errorf("failed to attach perf event to program %s", p.name)
}
bpfLink := &BPFLink{
link: link,
prog: p,
linkType: PerfEvent,
}
p.module.links = append(p.module.links, bpfLink)
return bpfLink, nil
}
// this API should be used for kernels > 4.17
func (p *BPFProg) AttachKprobe(kp string) (*BPFLink, error) {
return doAttachKprobe(p, kp, false)
}
// this API should be used for kernels > 4.17
func (p *BPFProg) AttachKretprobe(kp string) (*BPFLink, error) {
return doAttachKprobe(p, kp, true)
}
func (p *BPFProg) AttachLSM() (*BPFLink, error) {
link := C.bpf_program__attach_lsm(p.prog)
if C.IS_ERR_OR_NULL(unsafe.Pointer(link)) {
return nil, errptrError(unsafe.Pointer(link), "failed to attach lsm to program %s", p.name)
}
bpfLink := &BPFLink{
link: link,
prog: p,
linkType: LSM,
}
p.module.links = append(p.module.links, bpfLink)
return bpfLink, nil
}
func doAttachKprobe(prog *BPFProg, kp string, isKretprobe bool) (*BPFLink, error) {
cs := C.CString(kp)
cbool := C.bool(isKretprobe)
link := C.bpf_program__attach_kprobe(prog.prog, cbool, cs)
C.free(unsafe.Pointer(cs))
if C.IS_ERR_OR_NULL(unsafe.Pointer(link)) {
return nil, errptrError(unsafe.Pointer(link), "failed to attach %s k(ret)probe to program %s", kp, prog.name)
}
kpType := Kprobe
if isKretprobe {
kpType = Kretprobe
}
bpfLink := &BPFLink{
link: link,
prog: prog,
linkType: kpType,
eventName: kp,
}
prog.module.links = append(prog.module.links, bpfLink)
return bpfLink, nil
}
// AttachUprobe attaches the BPFProgram to entry of the symbol in the library or binary at 'path'
// which can be relative or absolute. A pid can be provided to attach to, or -1 can be specified
// to attach to all processes
func (p *BPFProg) AttachUprobe(pid int, path string, offset uint32) (*BPFLink, error) {
absPath, err := filepath.Abs(path)
if err != nil {
return nil, err
}
return doAttachUprobe(p, false, pid, absPath, offset)
}
// AttachURetprobe attaches the BPFProgram to exit of the symbol in the library or binary at 'path'
// which can be relative or absolute. A pid can be provided to attach to, or -1 can be specified
// to attach to all processes
func (p *BPFProg) AttachURetprobe(pid int, path string, offset uint32) (*BPFLink, error) {
absPath, err := filepath.Abs(path)
if err != nil {
return nil, err
}
return doAttachUprobe(p, true, pid, absPath, offset)
}
func doAttachUprobe(prog *BPFProg, isUretprobe bool, pid int, path string, offset uint32) (*BPFLink, error) {
retCBool := C.bool(isUretprobe)
pidCint := C.int(pid)
pathCString := C.CString(path)
offsetCsizet := C.size_t(offset)
link := C.bpf_program__attach_uprobe(prog.prog, retCBool, pidCint, pathCString, offsetCsizet)
C.free(unsafe.Pointer(pathCString))
if C.IS_ERR_OR_NULL(unsafe.Pointer(link)) {
return nil, errptrError(unsafe.Pointer(link), "failed to attach u(ret)probe to program %s:%d with pid %d, ", path, offset, pid)
}
upType := Uprobe
if isUretprobe {
upType = Uretprobe
}
bpfLink := &BPFLink{
link: link,
prog: prog,
linkType: upType,
eventName: fmt.Sprintf("%s:%d:%d", path, pid, offset),
}
return bpfLink, nil
}
func (p *BPFProg) AttachKprobeLegacy(kp string) (*BPFLink, error) {
return doAttachKprobeLegacy(p, kp, false)
}
func (p *BPFProg) AttachKretprobeLegacy(kp string) (*BPFLink, error) {
return doAttachKprobeLegacy(p, kp, true)
}
func doAttachKprobeLegacy(prog *BPFProg, kp string, isKretprobe bool) (*BPFLink, error) {
cs := C.CString(kp)
cbool := C.bool(isKretprobe)
link := C.attach_kprobe_legacy(prog.prog, cs, cbool)
C.free(unsafe.Pointer(cs))
if C.IS_ERR_OR_NULL(unsafe.Pointer(link)) {
return nil, errptrError(unsafe.Pointer(link), "failed to attach %s k(ret)probe using legacy debugfs API", kp)
}
kpType := KprobeLegacy
if isKretprobe {
kpType = KretprobeLegacy
}
bpfLink := &BPFLink{
link: link,
prog: prog,
linkType: kpType,
eventName: kp,
}
prog.module.links = append(prog.module.links, bpfLink)
return bpfLink, nil
}
var eventChannels = helpers.NewRWArray(maxEventChannels)
func (m *Module) InitRingBuf(mapName string, eventsChan chan []byte) (*RingBuffer, error) {
bpfMap, err := m.GetMap(mapName)
if err != nil {
return nil, err
}
if eventsChan == nil {
return nil, fmt.Errorf("events channel can not be nil")
}
slot := eventChannels.Put(eventsChan)
if slot == -1 {
return nil, fmt.Errorf("max ring buffers reached")
}
rb := C.init_ring_buf(bpfMap.fd, C.uintptr_t(slot))
if rb == nil {
return nil, fmt.Errorf("failed to initialize ring buffer")
}
ringBuf := &RingBuffer{
rb: rb,
bpfMap: bpfMap,
slot: uint(slot),
}
m.ringBufs = append(m.ringBufs, ringBuf)
return ringBuf, nil
}
func (rb *RingBuffer) Start() {
rb.stop = make(chan struct{})
rb.wg.Add(1)
go rb.poll()
}
func (rb *RingBuffer) Stop() {
if rb.stop != nil {
// Tell the poll goroutine that it's time to exit
close(rb.stop)
// The event channel should be drained here since the consumer
// may have stopped at this point. Failure to drain it will
// result in a deadlock: the channel will fill up and the poll
// goroutine will block in the callback.
eventChan := eventChannels.Get(rb.slot).(chan []byte)
go func() {
for range eventChan {
}
}()
// Wait for the poll goroutine to exit
rb.wg.Wait()
// Close the channel -- this is useful for the consumer but
// also to terminate the drain goroutine above.