Debian Codegraph @

examples/kprobe/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 "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.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 value uint64
57 if err := objs.KprobeMap.Lookup(mapKey, &value); err != nil {
58 log.Fatalf("reading map: %v", err)
59 }
60 log.Printf("%s called %d times\n", fn, value)
61 }
62 }