Debian Codegraph @

examples/kprobepin/main.go

raw symbols SCIP
1 //go:build linux
2
3 // This program demonstrates attaching an eBPF program to a kernel symbol.
4 // The eBPF program will be attached to the start of the sys_execve
5 // kernel function and prints out the number of times it has been called
6 // every second.
7 package main
8
9 import (
10 "log"
11 "os"
12 "path"
13 "time"
14
15 "github.com/cilium/ebpf"
16 "github.com/cilium/ebpf/link"
17 "github.com/cilium/ebpf/rlimit"
18 )
19
20 //go:generate go tool bpf2go -tags linux bpf kprobe_pin.c -- -I../headers
21
22 const (
23 mapKey uint32 = 0
24 bpfFSPath = "/sys/fs/bpf"
25 )
26
27 func main() {
28
29 // Name of the kernel function to trace.
30 fn := "sys_execve"
31
32 // Allow the current process to lock memory for eBPF resources.
33 if err := rlimit.RemoveMemlock(); err != nil {
34 log.Fatal(err)
35 }
36
37 pinPath := path.Join(bpfFSPath, fn)
38 if err := os.MkdirAll(pinPath, os.ModePerm); err != nil {
39 log.Fatalf("failed to create bpf fs subpath: %+v", err)
40 }
41
42 var objs bpfObjects
43 if err := loadBpfObjects(&objs, &ebpf.CollectionOptions{
44 Maps: ebpf.MapOptions{
45 // Pin the map to the BPF filesystem and configure the
46 // library to automatically re-write it in the BPF
47 // program so it can be re-used if it already exists or
48 // create it if not
49 PinPath: pinPath,
50 },
51 }); err != nil {
52 log.Fatalf("loading objects: %v", err)
53 }
54 defer objs.Close()
55
56 // Open a Kprobe at the entry point of the kernel function and attach the
57 // pre-compiled program. Each time the kernel function enters, the program
58 // will increment the execution counter by 1. The read loop below polls this
59 // map value once per second.
60 kp, err := link.Kprobe(fn, objs.KprobeExecve, nil)
61 if err != nil {
62 log.Fatalf("opening kprobe: %s", err)
63 }
64 defer kp.Close()
65
66 // Read loop reporting the total amount of times the kernel
67 // function was entered, once per second.
68 ticker := time.NewTicker(1 * time.Second)
69 defer ticker.Stop()
70
71 log.Println("Waiting for events..")
72
73 for range ticker.C {
74 var value uint64
75 if err := objs.KprobeMap.Lookup(mapKey, &value); err != nil {
76 log.Fatalf("reading map: %v", err)
77 }
78 log.Printf("%s called %d times\n", fn, value)
79 }
80 }