Debian Codegraph @

examples/kprobe_percpu/main.go

raw symbols SCIP
1 //go:build linux
2
3 // This program demonstrates attaching an eBPF program to a kernel symbol and
4 // using percpu map to collect data. The eBPF program will be attached to the
5 // start of the sys_execve kernel function and prints out the number of called
6 // times on each cpu every second.
7 package main
8
9 import (
10 "log"
11 "time"
12
13 "github.com/cilium/ebpf/link"
14 "github.com/cilium/ebpf/rlimit"
15 )
16
17 //go:generate go tool bpf2go -tags linux bpf kprobe_percpu.c -- -I../headers
18
19 const mapKey uint32 = 0
20
21 func main() {
22
23 // Name of the kernel function to trace.
24 fn := "sys_execve"
25
26 // Allow the current process to lock memory for eBPF resources.
27 if err := rlimit.RemoveMemlock(); err != nil {
28 log.Fatal(err)
29 }
30
31 // Load pre-compiled programs and maps into the kernel.
32 objs := bpfObjects{}
33 if err := loadBpfObjects(&objs, nil); err != nil {
34 log.Fatalf("loading objects: %v", err)
35 }
36 defer objs.Close()
37
38 // Open a Kprobe at the entry point of the kernel function and attach the
39 // pre-compiled program. Each time the kernel function enters, the program
40 // will increment the execution counter by 1. The read loop below polls this
41 // map value once per second.
42 kp, err := link.Kprobe(fn, objs.KprobeExecve, nil)
43 if err != nil {
44 log.Fatalf("opening kprobe: %s", err)
45 }
46 defer kp.Close()
47
48 // Read loop reporting the total amount of times the kernel
49 // function was entered, once per second.
50 ticker := time.NewTicker(1 * time.Second)
51 defer ticker.Stop()
52
53 log.Println("Waiting for events..")
54
55 for range ticker.C {
56 var all_cpu_value []uint64
57 if err := objs.KprobeMap.Lookup(mapKey, &all_cpu_value); err != nil {
58 log.Fatalf("reading map: %v", err)
59 }
60 for cpuid, cpuvalue := range all_cpu_value {
61 log.Printf("%s called %d times on CPU%v\n", fn, cpuvalue, cpuid)
62 }
63 log.Printf("\n")
64 }
65 }