Choosing a hook
The last two chapters attached to the same event, the start of an open,
through a tracepoint and through a kprobe. The kernel has many more hooks,
and the choice among them decides what the program receives, what it can do
with the event, and which kernels it runs on. This chapter starts from the
event you need and ends at a hook, runs an fentry program on
do_sys_openat2, and shows what four other kinds of program look like.
Start from the event
Section titled “Start from the event”Ask first what has to happen for the program to run: a system call or a function call, a packet or socket data, a security decision, an action by the processes of one cgroup, or a call into a kernel subsystem. Each answer leads to a family of hooks.
From the event to the hook family. A BTF badge marks the hooks that need a kernel built with BTF.
For a system call or a kernel function, prefer a tracepoint when one covers the event: its record is stable and needs nothing from the kernel build. When none does, use fentry or fexit if the kernel has BTF, and a kprobe if it does not, or if the function is missing from the kernel’s BTF. For a function in a user program or library, use a uprobe.
For a packet, XDP runs first, in the network driver, before the kernel has built its socket buffer, and is the place to drop or redirect traffic cheaply. tc and tcx run later, on the socket buffer, for traffic entering and leaving a device; netfilter runs at the same hooks as firewall rules; sockmap programs see the data of sockets held in a map.
For a security decision, an LSM program runs where the kernel asks its security modules whether an operation may go ahead, and can refuse it. For everything the processes of a cgroup do with sockets, sysctls and devices, a cgroup program applies to that group only. To change how a kernel subsystem behaves, such as TCP congestion control, a struct_ops map replaces an operations table with BPF programs.
The hooks side by side
Section titled “The hooks side by side”The table lists, for each hook, what fires it, what ctx points to, whether
it needs kernel BTF, and the oldest kernel where gobpfgo uses it, from
Kernel support, which has the details
and the kernel configuration.
| Hook | Fires when | Context | BTF | amd64 | arm64 |
|---|---|---|---|---|---|
| Tracepoint | the kernel reaches a tracepoint in its source | the record its format file describes | no | 5.10 | 5.10 |
| kprobe, kretprobe | a kernel function is entered or returns | struct pt_regs *, the saved registers |
no | 5.10 | 5.10 |
| uprobe, uretprobe | a function in a user program or library is entered or returns | struct pt_regs * |
no | 5.10 | 5.10 |
| fentry, fexit | a kernel function is entered or returns, through a trampoline | the function’s typed arguments, and for fexit its return value | yes | 5.10 | 6.0 |
| LSM | a security check runs, such as on a file open | the LSM hook’s typed arguments | yes | 5.10 | 6.0 |
| XDP | the driver receives a packet | struct xdp_md * |
no | 5.10 | 5.10 |
| tcx | a packet enters or leaves a device | struct __sk_buff * |
no | 6.6 | 6.6 |
| netfilter | a packet reaches a netfilter hook | struct bpf_nf_ctx * |
no | 6.4 | 6.4 |
| cgroup | a process in the cgroup uses a socket, a sysctl or a device | depends on the attach point, such as struct bpf_sock_addr * |
no | 5.10 | 5.10 |
| sockmap | data is sent or received on a socket in a sockmap | struct __sk_buff * or struct sk_msg_md * |
no | 6.10 | 6.10 |
| struct_ops | the kernel calls an operation the map implements | the operation’s typed arguments | yes | 5.10 | 6.0 |
A few rows need a note. On arm64, fentry, fexit, LSM and struct_ops programs
need BPF trampolines, which arrived in 6.0. LSM programs also need bpf in
the kernel’s list of active security modules, which
cat /sys/kernel/security/lsm prints. struct_ops links, and swapping the map
behind one, need 6.4. The sockmap row is for links. For tc,
gobpfgo attaches through tcx links only: it has no port of libbpf’s netlink
calls, such as bpf_tc_attach, which older kernels use.
fentry and fexit
Section titled “fentry and fexit”An fentry program runs at the entry of a kernel function, like a kprobe, and an fexit program runs when the function returns. Two kernel features make them different from kprobes.
BTF gives the kernel the function’s prototype. At load, the loader looks
the function up in the kernel’s BTF, at /sys/kernel/btf/vmlinux, and passes
its BTF ID to the kernel with the program. The verifier then knows the type
of every argument, so the program reads arguments by position as typed
values, not by reading registers, and a pointer argument keeps its type:
the program can read the fields of a kernel struct it receives directly.
A trampoline is a short piece of machine code the kernel generates when the program is attached. The kernel patches the function’s first instruction to call the trampoline, which saves the arguments, calls the fentry programs, and, when an fexit program is attached, calls the function itself and then the fexit programs with the arguments and the return value. A call through a trampoline costs less than a kprobe, and fexit sees the arguments and the result together, which a kretprobe cannot.
For a function with a known prototype, that makes fentry the safer choice: the kernel checks the target and its argument types when it loads the program, and the program’s code does not depend on the CPU’s calling convention. The price is the dependence on BTF: without it, the loader has nothing to look the function up in.
Directoryexamples/tutorial/step04-fentry/
- open_fentry.bpf.c the fentry program
- main.go the Go program
// 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 <bpf_helpers.h>#include <bpf_tracing.h>
// The program only passes the pointer on, so a declaration is enough.struct open_how;
// counts has one slot: key 0 counts the do_sys_openat2 calls seen.struct { __uint(type, BPF_MAP_TYPE_ARRAY); __uint(max_entries, 1); __type(key, __u32); __type(value, __u64);} counts SEC(".maps");
// The section names the kernel function. At load, the loader finds// do_sys_openat2 in the kernel's BTF and the kernel checks the program// against that prototype. BPF_PROG unpacks the arguments by position, so// the program receives them typed, with no register macros.SEC("fentry/do_sys_openat2")int BPF_PROG(fentry_openat2, int dfd, const char *filename, struct open_how *how) { __u32 key = 0; __u64 *count;
count = bpf_map_lookup_elem(&counts, &key); if (count) __atomic_fetch_add(count, 1, __ATOMIC_RELAXED); return 0;}
// As in step01, the license the loader passes to the kernel.char LICENSE[] SEC("license") = "GPL";SEC("fentry/do_sys_openat2") makes the function an fentry program and names
its target. The kernel passes an fentry program its arguments as an array of
64-bit values, one per argument. BPF_PROG, from bpf_tracing.h, writes
the function that receives that array and unpacks it into the parameters you
declare: dfd, filename and how are plain C variables in the body, with
no register macro and no architecture flag. The declared types match the
prototype in the kernel’s BTF; the verifier tracks each argument with the
kernel’s type for it.
The program needs only a declaration of struct open_how, since it does not
read the struct. The verifier knows how points to a kernel struct open_how and would let the program read its fields directly, given the
struct’s definition. filename is still a pointer into the calling process,
and reading the string still takes bpf_probe_read_user_str, as in the
kprobe chapter. The body counts calls in slot 0 of an array map.
// SPDX-License-Identifier: LGPL-2.1-only
// Command step04 attaches an fentry program to the kernel function// do_sys_openat2, opens /etc/hostname four times and prints how many calls// the program counted. It needs a kernel built with BTF. Run it as root// from this directory, after make in examples/.package main
import ( "encoding/binary" "errors" "fmt" "os"
"github.com/gobpfgo/gobpfgo/bpf")
func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, "step04:", err) os.Exit(1) }}
func run() error { obj, err := bpf.OpenFile("open_fentry.bpf.o", nil) if err != nil { return err } defer obj.Close()
// The load resolves fentry/do_sys_openat2 against the kernel's BTF. if err := obj.Load(); err != nil { return err }
prog := obj.Program("fentry_openat2") if prog == nil { return errors.New("no program named fentry_openat2 in the object") }
// AttachTrace takes no target: the load already resolved it from the // section name. link, err := prog.AttachTrace() if err != nil { return err } defer link.Destroy()
for range 4 { f, err := os.Open("/etc/hostname") if err != nil { return err } if err := f.Close(); err != nil { return err } }
counts := obj.Map("counts") if counts == nil { return errors.New("no map named counts in the object") } key := make([]byte, 4) value := make([]byte, 8) if err := counts.Lookup(key, value, 0); err != nil { return err } fmt.Printf("do_sys_openat2 calls counted: %d\n", binary.NativeEndian.Uint64(value)) return nil}The Go side follows the first program; the attach is the call that changes.
obj.Load() resolves the target: the loader finds do_sys_openat2 in the kernel’s BTF before it
loads the program. prog.AttachTrace() takes no target, because the load
already fixed it, and creates the trampoline link.
If the kernel has no function by that name, the load fails before the
kernel sees the program. Misspelled as do_sys_openat3:
step04: bpf_object__load: no such process: prog 'fentry_openat2': failed to find kernel BTF type ID of 'do_sys_openat3': no such processA kernel built without BTF fails the same load with the same errno, ESRCH.
Install shows how to check for
/sys/kernel/btf/vmlinux.
-
Build the BPF objects from the
examplesdirectory:Terminal window cd examplesmake -
Run the Go program as root, from the example’s directory:
Terminal window cd tutorial/step04-fentrysudo env PATH="$PATH" go run .
On 6.18 the output is:
do_sys_openat2 calls counted: 4As with the first program, opens by other processes while the program is attached raise the count, and it is never below 4. The example needs a kernel with BTF, and on arm64 a kernel from 6.0.
Sketches of other hooks
Section titled “Sketches of other hooks”An LSM program attaches to one LSM hook, named after lsm/, and receives
the hook’s arguments, typed from BTF. file_open runs when a file is opened,
with the struct file being opened. The
program’s return value is its verdict: 0 lets the operation go ahead, and a
negative errno refuses it, and the system call fails with that errno in the
calling process. BPF LSM programs also receive, as a last argument, the
verdict of the BPF LSM program that ran before them, or 0.
// Sketch: not built or run by this manual.SEC("lsm/file_open")int BPF_PROG(check_open, struct file *file, int ret){ if (ret != 0) return ret; // keep an earlier refusal return 0; // or -EPERM to refuse the open}The kernel loads LSM programs only with a GPL-compatible license. In Go,
prog.AttachLsm() attaches the program to the hook its section names.
An XDP program receives a struct xdp_md * with the packet’s bounds,
data and data_end, as 32-bit values the program converts to pointers.
Every read of packet bytes must be preceded by a check against data_end,
or the verifier refuses the program. The return value is the packet’s fate:
XDP_PASS hands it to the network stack, XDP_DROP drops it, XDP_TX sends
it back out of the same device, XDP_REDIRECT sends it to another device,
CPU or socket, and XDP_ABORTED drops it as an error.
// Sketch: not built or run by this manual.SEC("xdp")int xdp_pass(struct xdp_md *ctx){ void *data = (void *)(long)ctx->data; void *data_end = (void *)(long)ctx->data_end;
if (data + 14 > data_end) // shorter than an Ethernet header return XDP_DROP; return XDP_PASS;}In Go, prog.AttachXDP(ifindex) attaches it to the interface with that
index, the Index field of the net.Interface that net.InterfaceByName
returns.
tc and tcx
Section titled “tc and tcx”A tc program receives a struct __sk_buff *, the BPF view of the kernel’s
socket buffer, with fields such as len, protocol, ifindex and mark,
and the packet bytes between data and data_end. It runs as the packet
enters (tcx/ingress) or leaves (tcx/egress) a device. Several programs
can share a device; TCX_NEXT passes the packet to the next one, and
TCX_PASS, TCX_DROP and TCX_REDIRECT decide.
// Sketch: not built or run by this manual.SEC("tcx/ingress")int tcx_ingress(struct __sk_buff *skb){ // skb->len, skb->protocol, skb->ifindex, skb->mark ... return TCX_NEXT;}In Go, prog.AttachTcx(ifindex, nil) attaches it, from Linux 6.6.
cgroup
Section titled “cgroup”A cgroup program applies to the processes in one cgroup and its
descendants, and what it receives depends on its attach point. A
cgroup/connect4 program runs when one of them calls connect(2) on an
IPv4 socket, with a struct bpf_sock_addr * that holds the destination
address and port, which it may rewrite. It returns 1 to let the call go on;
0 makes the call fail with EPERM.
// Sketch: not built or run by this manual.SEC("cgroup/connect4")int connect4(struct bpf_sock_addr *ctx){ // ctx->user_ip4 and ctx->user_port, in network byte order return 1;}In Go, prog.AttachCgroup(cgroupFD) attaches it to the cgroup v2 directory
open on cgroupFD, such as a directory under /sys/fs/cgroup.
Where these are covered
Section titled “Where these are covered”No chapter of this guide covers LSM, XDP, tc or cgroup programs. Reading
kernel structs such as the struct file an LSM program receives is the
subject of CO-RE and BTF. The attach calls
are documented in the bpf package, which go doc github.com/gobpfgo/gobpfgo/bpf Program lists and the API
reference indexes, and the minimum kernels
are in the table above and on the support
page.
Every program so far kept its results in a map. The next chapter covers the map types, how to declare them, and how Go reads and writes them.
