File: tracepoint.go

package info (click to toggle)
golang-github-cilium-ebpf 0.17.3%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 4,684 kB
  • sloc: ansic: 1,259; makefile: 127; python: 113; awk: 29; sh: 24
file content (70 lines) | stat: -rw-r--r-- 1,921 bytes parent folder | download
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
package link

import (
	"fmt"

	"github.com/cilium/ebpf"
	"github.com/cilium/ebpf/internal/tracefs"
)

// TracepointOptions defines additional parameters that will be used
// when loading Tracepoints.
type TracepointOptions struct {
	// Arbitrary value that can be fetched from an eBPF program
	// via `bpf_get_attach_cookie()`.
	//
	// Needs kernel 5.15+.
	Cookie uint64
}

// Tracepoint attaches the given eBPF program to the tracepoint with the given
// group and name. See /sys/kernel/tracing/events to find available
// tracepoints. The top-level directory is the group, the event's subdirectory
// is the name. Example:
//
//	tp, err := Tracepoint("syscalls", "sys_enter_fork", prog, nil)
//
// Losing the reference to the resulting Link (tp) will close the Tracepoint
// and prevent further execution of prog. The Link must be Closed during
// program shutdown to avoid leaking system resources.
//
// Note that attaching eBPF programs to syscalls (sys_enter_*/sys_exit_*) is
// only possible as of kernel 4.14 (commit cf5f5ce).
//
// The returned Link may implement [PerfEvent].
func Tracepoint(group, name string, prog *ebpf.Program, opts *TracepointOptions) (Link, error) {
	if group == "" || name == "" {
		return nil, fmt.Errorf("group and name cannot be empty: %w", errInvalidInput)
	}
	if prog == nil {
		return nil, fmt.Errorf("prog cannot be nil: %w", errInvalidInput)
	}
	if prog.Type() != ebpf.TracePoint {
		return nil, fmt.Errorf("eBPF program type %s is not a Tracepoint: %w", prog.Type(), errInvalidInput)
	}

	tid, err := tracefs.EventID(group, name)
	if err != nil {
		return nil, err
	}

	fd, err := openTracepointPerfEvent(tid, perfAllThreads)
	if err != nil {
		return nil, err
	}

	var cookie uint64
	if opts != nil {
		cookie = opts.Cookie
	}

	pe := newPerfEvent(fd, nil)

	lnk, err := attachPerfEvent(pe, prog, cookie)
	if err != nil {
		pe.Close()
		return nil, err
	}

	return lnk, nil
}