Skip to content

kprobes

A tracepoint exists only where a kernel developer put one. A kprobe attaches to the entry of almost any kernel function, chosen by name when the program is attached, and a kretprobe attaches to the point where that function returns. This chapter attaches both to do_sys_openat2, the kernel function that openat(2), open(2) and openat2(2) all call. The kprobe counts opens per file name, as the tracepoint program did; the kretprobe counts the opens that failed. The Go program opens one file that exists and one that does not, then prints both maps.

  • Directoryexamples/tutorial/step03-kprobe/
    • open_kprobe.bpf.c the kprobe and kretprobe programs
    • main.go the Go program

A tracepoint is part of the kernel’s source, with a record format the kernel publishes. Kernel developers change tracepoints far less often than functions, and the system call tracepoints mirror the system call interface, which does not change: the sys_enter_openat record has the same layout on every amd64 kernel checked, from 5.10 to 7.4-rc4.

A kprobe is placed at run time. When the loader attaches it, the kernel patches the first instructions of the named function so that each call runs the probe first. Nothing in the kernel source promises that the function exists, keeps its name or keeps its arguments. Functions are renamed, split, merged and removed between versions, and their signatures change: do_sys_openat2 returns a long on 5.10 and an int on 6.18, as each kernel’s BTF shows. A kprobe program is tied to the kernel it was written for in a way a tracepoint program is not.

Use a tracepoint when one covers the event, and a kprobe for what no tracepoint reaches: a function deep inside a subsystem, or arguments the tracepoint does not record. On a kernel built with BTF, an fentry program, covered in Choosing a hook, reaches the same functions with typed arguments.

The kernel can probe a function only if the function exists as a symbol in the running kernel. Two files list the candidates:

Terminal window
sudo grep -w do_sys_openat2 /sys/kernel/tracing/available_filter_functions
sudo grep -w do_sys_openat2 /proc/kallsyms
do_sys_openat2
ffffffff8557e8e0 t do_sys_openat2

/proc/kallsyms lists every kernel symbol with its address; the lowercase t marks a function that is local to its source file, which a kprobe can still reach. available_filter_functions lists the functions that ftrace, the kernel’s function tracer, can hook at their entry; other attach types, such as kprobe multi, accept only functions from that list. Read both as root: tracefs is usually readable only by root, and /proc/kallsyms shows zero addresses to other users.

A function can be missing even when the source defines it:

  • Inlining. When the compiler copies a small function into each of its callers, the function has no entry of its own to probe. If it was inlined into some callers only, a kprobe on the symbol fires only for the calls that were not inlined.
  • Renaming. Compiler optimizations can produce copies with suffixes, such as .isra.0 or .constprop.0, which are listed under those names.
  • Blocked functions. The kernel refuses kprobes on functions that the probing code itself uses, which it lists in /sys/kernel/debug/kprobes/blacklist.

When the function is not there, the attach fails with ENOENT. Misspelled as do_sys_openat3, the attach in this chapter’s program fails like this:

step03: bpf_program__attach_kprobe: no such file or directory

At a kprobe, the kernel saves the CPU’s registers into a struct pt_regs and runs the program with ctx pointing at it. The program finds the function’s arguments where the CPU’s calling convention put them: the rule each architecture’s compiler follows for passing arguments and return values. On x86-64 the first six integer or pointer arguments are in the registers rdi, rsi, rdx, rcx, r8 and r9, and the return value is in rax. On arm64 the first eight are in x0 to x7, and the return value is in x0.

An openat call enters do_sys_openat2. At its entry the kprobe fires, and the saved registers hold dfd in rdi or x0, filename in rsi or x1, and how in rdx or x2. kprobe_openat2 receives ctx, reads PT_REGS_PARM2(ctx) and counts the name in the counts hash map. When the function returns, the kretprobe fires, the saved registers hold the result, a file descriptor or a negative errno, in rax or x0, and kretprobe_openat2 reads PT_REGS_RC(ctx) and counts a negative value in the failures array map.

The kprobe sees the registers at the function’s entry and the kretprobe sees them at its return. Each register is named for x86-64 and arm64.

The register macros of libbpf’s bpf_tracing.h hide those names. PT_REGS_PARM2(ctx) reads the second argument’s register and PT_REGS_RC(ctx) the return value’s. Which field of the saved registers they read depends on the architecture the program will run on, but clang compiles for the BPF target, which has no host CPU, so the header cannot tell. The -D__TARGET_ARCH_x86 or -D__TARGET_ARCH_arm64 flag, which the examples’ Makefile sets from uname -m, tells it. Without the flag, every use of a macro stops the build:

open_kprobe.bpf.c:38:39: error: Must specify a BPF target arch via __TARGET_ARCH_xxx

An object built with __TARGET_ARCH_x86 reads x86-64 registers and gives wrong values on arm64, so build the object for the architecture it will run on.

The macros also need the definition of the saved registers. Without a generated vmlinux.h, the program includes <linux/ptrace.h> from the system’s kernel headers, which defines struct pt_regs on x86-64 and struct user_pt_regs on arm64. On Debian and Ubuntu that header lives in the per-architecture include directory that Install shows how to add.

A kretprobe sees the registers at the return, when the argument registers may already hold other values, so it cannot read the function’s arguments. To connect a return to its call, a program saves what it needs at the entry in a hash map keyed by the thread’s ID, and the kretprobe looks it up. fexit, which sees both the arguments and the return value, avoids that.

examples/tutorial/step03-kprobe/open_kprobe.bpf.c
// SPDX-License-Identifier: LGPL-2.1-only
// This constraint keeps the Go tool from treating the file as cgo
// source. clang reads it as a comment.
//go:build ignore
#include <linux/bpf.h>
#include <linux/ptrace.h>
#include <bpf_helpers.h>
#include <bpf_tracing.h>
#define NAME_LEN 32
// counts maps a file name, NUL-padded to 32 bytes, to the number of
// do_sys_openat2 calls that named it.
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 1024);
__type(key, char[NAME_LEN]);
__type(value, __u64);
} counts SEC(".maps");
// failures has one slot: key 0 counts the calls that returned an error.
struct {
__uint(type, BPF_MAP_TYPE_ARRAY);
__uint(max_entries, 1);
__type(key, __u32);
__type(value, __u64);
} failures SEC(".maps");
// The kernel runs this at the entry of do_sys_openat2(int dfd,
// const char __user *filename, struct open_how *how). ctx holds the CPU
// registers; the second argument is in the register PT_REGS_PARM2 names
// for the target architecture.
SEC("kprobe/do_sys_openat2")
int kprobe_openat2(struct pt_regs *ctx) {
const char *filename = (const char *)PT_REGS_PARM2(ctx);
char name[NAME_LEN] = {};
__u64 one = 1;
__u64 *count;
if (bpf_probe_read_user_str(name, sizeof(name), filename) < 0)
return 0;
count = bpf_map_lookup_elem(&counts, name);
if (!count) {
if (bpf_map_update_elem(&counts, name, &one, BPF_NOEXIST) == 0)
return 0;
count = bpf_map_lookup_elem(&counts, name);
if (!count)
return 0;
}
__atomic_fetch_add(count, 1, __ATOMIC_RELAXED);
return 0;
}
// The kernel runs this when do_sys_openat2 returns. The return value, a
// file descriptor or a negative errno, is in the register PT_REGS_RC names.
SEC("kretprobe/do_sys_openat2")
int kretprobe_openat2(struct pt_regs *ctx) {
// do_sys_openat2 returns a long on 5.10 and an int on 6.18. Casting
// the register to int keeps the low 32 bits, which hold the result
// in both cases.
int ret = (int)PT_REGS_RC(ctx);
__u32 key = 0;
__u64 *count;
if (ret >= 0)
return 0;
count = bpf_map_lookup_elem(&failures, &key);
if (count)
__atomic_fetch_add(count, 1, __ATOMIC_RELAXED);
return 0;
}
// bpf_probe_read_user_str is a GPL-only helper.
char LICENSE[] SEC("license") = "GPL";

SEC("kprobe/do_sys_openat2") and SEC("kretprobe/do_sys_openat2") make both functions programs of the kprobe type; the loader reads the type from the prefix. The function name after the slash is the target that Program.Attach, the attach from the section name, would use. The Go program names the function itself.

kprobe_openat2 reads the second argument of do_sys_openat2(int dfd, const char __user *filename, struct open_how *how), the file name. __user marks a pointer into the calling process’s memory, so the program copies the string with bpf_probe_read_user_str and counts it in a hash map, exactly as the tracepoint program did with the record’s filename field. The kprobe fires when the function is entered, before the kernel has looked for the file, so it counts the name of a file that does not exist too.

kretprobe_openat2 reads the return value: a new file descriptor, 0 or more, or a negative errno such as -ENOENT. It casts the register to int. On 6.18 the function returns an int, and the upper 32 bits of the register are not part of the result; on 5.10 it returns a long, and the low 32 bits still hold the same value. A negative result adds one to slot 0 of the failures array.

Each BPF program has a stack of 512 bytes, which holds its local variables. name takes 32 of them. A larger buffer catches longer paths, and 256 bytes builds and loads, but the stack also holds the program’s other locals and the values clang spills, so a buffer of 512 bytes cannot fit. clang 23 refuses it at compile time:

open_kprobe.bpf.c:37:5: error: Looks like the BPF stack limit is exceeded. Please move large on stack variables into BPF per-cpu array map. For non-kernel uses, the stack can be increased using -mllvm -bpf-stack-size.

The kernel enforces the same limit. Built anyway, with clang’s limit raised to 1024 bytes, the program fails to load on 6.18 with EACCES. The end of the verifier’s log shows the store of one that clang placed 520 bytes below the top of the stack, past the 512-byte limit:

; __u64 one = 1; @ open_kprobe.bpf.c:40
66: (b7) r1 = 1 ; R1=1
67: (7b) *(u64 *)(r10 -520) = r1
invalid write to stack R10 off=-520 size=8
processed 68 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0

For a buffer larger than the stack allows, the program uses a map value as scratch space: a per-CPU array with one entry gives each CPU its own buffer, which the program fills and uses as a key. The maps chapter covers per-CPU maps.

examples/tutorial/step03-kprobe/main.go
// SPDX-License-Identifier: LGPL-2.1-only
// Command step03 attaches a kprobe and a kretprobe to the kernel function
// do_sys_openat2, opens a file that exists and one that does not, and
// prints the opens counted per file name and the number of failed opens.
// Run it as root from this directory, after make in examples/.
package main
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"os"
"github.com/gobpfgo/gobpfgo/bpf"
"golang.org/x/sys/unix"
)
const (
existing = "/etc/hostname"
missing = "/etc/gobpfgo-missing"
)
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, "step03:", err)
os.Exit(1)
}
}
func run() error {
obj, err := bpf.OpenFile("open_kprobe.bpf.o", nil)
if err != nil {
return err
}
defer obj.Close()
if err := obj.Load(); err != nil {
return err
}
entry := obj.Program("kprobe_openat2")
exit := obj.Program("kretprobe_openat2")
if entry == nil || exit == nil {
return errors.New("the object lacks kprobe_openat2 or kretprobe_openat2")
}
// false attaches at the function's entry, true at its return.
entryLink, err := entry.AttachKprobe(false, "do_sys_openat2")
if err != nil {
return err
}
defer entryLink.Destroy()
exitLink, err := exit.AttachKprobe(true, "do_sys_openat2")
if err != nil {
return err
}
defer exitLink.Destroy()
f, err := os.Open(existing)
if err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
if _, err := os.Open(missing); !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("open %s: want ENOENT, got %v", missing, err)
}
counts := obj.Map("counts")
failures := obj.Map("failures")
if counts == nil || failures == nil {
return errors.New("the object lacks the counts or failures map")
}
var curKey []byte
nextKey := make([]byte, counts.KeySize())
value := make([]byte, counts.ValueSize())
for {
err := counts.NextKey(curKey, nextKey)
if errors.Is(err, unix.ENOENT) {
break
}
if err != nil {
return err
}
if err := counts.Lookup(nextKey, value, 0); err != nil {
return err
}
name, _, _ := bytes.Cut(nextKey, []byte{0})
fmt.Printf("%4d %s\n", binary.NativeEndian.Uint64(value), name)
curKey = append(curKey[:0], nextKey...)
}
key := make([]byte, 4)
if err := failures.Lookup(key, value, 0); err != nil {
return err
}
fmt.Printf("failed opens: %d\n", binary.NativeEndian.Uint64(value))
return nil
}

entry.AttachKprobe(false, "do_sys_openat2") attaches the kprobe at the function’s entry, and exit.AttachKprobe(true, "do_sys_openat2") the kretprobe at its return; the first argument selects the return. Each call returns a link that the program destroys when it returns. The opens follow: /etc/hostname succeeds, and /etc/gobpfgo-missing fails with ENOENT, which the program checks, since any other result means the test went wrong. The walk over counts is the one from the tracepoint chapter, and the failure count is slot 0 of failures, read as the first program read its counter.

The kernel offers two ways to create a kprobe, and the loader picks one. With the kprobe PMU, a perf event source for kprobes, the loader reads the PMU’s type number from /sys/bus/event_source/devices/kprobe/type and calls perf_event_open with the function’s name; for a kretprobe it also reads which bit marks a return probe, from /sys/bus/event_source/devices/kprobe/format/retprobe. In the older tracefs mode, it writes a probe definition into /sys/kernel/tracing/kprobe_events and opens the event that creates. Either way the program ends up attached to a perf event, through a BPF link from Linux 5.15.

AttachKprobe uses the default mode, which takes the PMU when the kernel has one, as kernels built with kprobe events do, and tracefs otherwise. The kprobe is removed when the link is destroyed, in either mode. You only need to choose when you have a reason to: AttachKprobeOpts takes libbpf.BpfKprobeOpts, whose AttachMode forces the PMU, the tracefs mode or a BPF link.

  1. Build the BPF objects from the examples directory:

    Terminal window
    cd examples
    make
  2. Run the Go program as root, from the example’s directory:

    Terminal window
    cd tutorial/step03-kprobe
    sudo env PATH="$PATH" go run .

On 6.18 the output is:

3 /sys/bus/event_source/devices/k
1 /etc/hostname
1 /etc/gobpfgo-missing
failed opens: 1

Both files appear once: the kprobe counted the name of the missing file at the function’s entry, and the kretprobe counted its failure at the return.

The first line is the Go program itself. Once the kprobe was attached, the second AttachKprobe call read /sys/bus/event_source/devices/kprobe/type twice and /sys/bus/event_source/devices/kprobe/format/retprobe once, to create the kretprobe through the PMU. Those paths are longer than 31 bytes and share their first 31, so the 32-byte key truncates all three to the same /sys/bus/event_source/devices/k, the case described in Names longer than the buffer.

As with the tracepoint, the probes fire for every process on the machine, so other opens and other failures can add lines and raise the counts, and the lines come out in the hash table’s order.

kprobes are one hook among many. The next chapter compares them, and runs an fentry program on the same function.