forked from aquasecurity/libbpfgo
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
link.go
124 lines (101 loc) · 1.97 KB
/
link.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
package libbpfgo
/*
#cgo LDFLAGS: -lelf -lz
#include "libbpfgo.h"
*/
import "C"
import (
"fmt"
"syscall"
"unsafe"
)
//
// LinkType
//
type LinkType int
const (
Tracepoint LinkType = iota
RawTracepoint
Kprobe
Kretprobe
LSM
PerfEvent
Uprobe
Uretprobe
Tracing
XDP
Cgroup
CgroupLegacy
Netns
Iter
)
//
// BPFLink
//
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 retC := C.bpf_link__destroy(l.link); retC < 0 {
return syscall.Errno(-retC)
}
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 {
pathC := C.CString(pinPath)
defer C.free(unsafe.Pointer(pathC))
retC := C.bpf_link__pin(l.link, pathC)
if retC < 0 {
return fmt.Errorf("failed to pin link %s to path %s: %w", l.eventName, pinPath, syscall.Errno(-retC))
}
return nil
}
func (l *BPFLink) Unpin() error {
retC := C.bpf_link__unpin(l.link)
if retC < 0 {
return fmt.Errorf("failed to unpin link %s: %w", l.eventName, syscall.Errno(-retC))
}
return nil
}
//
// BPF Link Reader (low-level)
//
func (l *BPFLink) Reader() (*BPFLinkReader, error) {
fdC := C.bpf_iter_create(C.int(l.FileDescriptor()))
if fdC < 0 {
return nil, fmt.Errorf("failed to create reader: %w", syscall.Errno(-fdC))
}
return &BPFLinkReader{
l: l,
fd: int(fdC),
}, nil
}