Tracepoints
The first program counted openat(2) calls without looking at them. This
chapter reads what each call passes. The BPF program attaches to the same
tracepoint, syscalls/sys_enter_openat, takes the file name from the
tracepoint’s record, and counts opens per file name in a hash map. The Go
program opens /etc/hostname three times and /etc/hosts twice, then walks
the map and prints every name with its count.
Directoryexamples/tutorial/step02-tracepoint/
- open_names.bpf.c the BPF program
- main.go the Go program
What a tracepoint gives the program
Section titled “What a tracepoint gives the program”A tracepoint is a point that kernel developers placed in the kernel
source, with a category, a name and a record format. When the kernel reaches
it, the tracing code fills a record with the event’s fields, and the
kernel runs every program attached to the tracepoint with a pointer to that
record as its context, ctx. The program reads the record; it does not see
the kernel function around the tracepoint.
The record’s layout is published by the kernel in the tracepoint’s format
file, under /sys/kernel/tracing/events/<category>/<name>/format. On
6.18, the one for sys_enter_openat reads:
sudo cat /sys/kernel/tracing/events/syscalls/sys_enter_openat/formatname: sys_enter_openatID: 751format: field:unsigned short common_type; offset:0; size:2; signed:0; field:unsigned char common_flags; offset:2; size:1; signed:0; field:unsigned char common_preempt_count; offset:3; size:1; signed:0; field:int common_pid; offset:4; size:4; signed:1;
field:int __syscall_nr; offset:8; size:4; signed:1; field:int dfd; offset:16; size:8; signed:0; field:const char * filename; offset:24; size:8; signed:0; field:int flags; offset:32; size:8; signed:0; field:umode_t mode; offset:40; size:8; signed:0;
print fmt: "dfd: 0x%08lx, filename: 0x%08lx, flags: 0x%08lx, mode: 0x%08lx", ((unsigned long)(REC->dfd)), ((unsigned long)(REC->filename)), ((unsigned long)(REC->flags)), ((unsigned long)(REC->mode))Each field line gives a field’s C type, its byte offset from the start of
the record, its size, and whether it is signed. The ID and the print fmt
line are for the kernel’s text tracing output; a BPF program needs only the
fields.
The first group is the common header: common_type, common_flags,
common_preempt_count and common_pid, 8 bytes in all. The tracing code
writes these four fields at the start of every tracepoint record, for every
event, so the event’s own fields always come after them. For a system call
tracepoint, the event’s fields start with the system call number,
__syscall_nr, a 4-byte int at offset 8, which leaves 4 bytes of padding
before the first argument. Then come the system call’s arguments, dfd,
filename, flags and mode, at offsets 16, 24, 32 and 40.
Every argument takes 8 bytes, even dfd and flags, whose type the file
gives as int: the system call tracepoints store each argument as an
unsigned long, the size of a register, and name the type the system call
declares. The layout is the same on the four amd64 kernels this was checked
on: 5.10, 6.18, 7.3.6 and 7.4-rc4.
The record the tracepoint passes as ctx, and the path from its
filename field to a key in the counts map.
The BPF program
Section titled “The BPF 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>
#define NAME_LEN 32
// openat_args mirrors the record of the syscalls/sys_enter_openat// tracepoint, as /sys/kernel/tracing/events/syscalls/sys_enter_openat/format// describes it: the 8-byte common header, the system call number, then// one 8-byte slot per system call argument.struct openat_args { unsigned short common_type; // offset 0 unsigned char common_flags; // offset 2 unsigned char common_preempt_count; // offset 3 int common_pid; // offset 4 int syscall_nr; // offset 8, then 4 bytes of padding long dfd; // offset 16 const char *filename; // offset 24, a user-space pointer long flags; // offset 32 long mode; // offset 40};
// If the struct does not match the format file, the build stops here._Static_assert(__builtin_offsetof(struct openat_args, filename) == 24, "filename must be at offset 24, as in the format file");
// counts maps a file name, NUL-padded to 32 bytes, to the number of// openat(2) 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");
SEC("tracepoint/syscalls/sys_enter_openat")int handle_openat(struct openat_args *ctx) { // The key buffer starts zeroed, so every byte after the copied name // is 0 and two opens of the same name build the same 32-byte key. char name[NAME_LEN] = {}; __u64 one = 1; __u64 *count;
// filename points into the calling process's memory. Copy the // string, at most NAME_LEN bytes with its terminating NUL. if (bpf_probe_read_user_str(name, sizeof(name), ctx->filename) < 0) return 0; // The helper already NUL-terminates; this keeps the last byte 0 for // any reader, whatever the helper returned. name[NAME_LEN - 1] = '\0';
count = bpf_map_lookup_elem(&counts, name); if (!count) { // First open of this name: insert a count of 1. BPF_NOEXIST // fails if another CPU inserted the name in between, and the // insert also fails when the map is full. 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;}
// bpf_probe_read_user_str is a GPL-only helper.char LICENSE[] SEC("license") = "GPL";The record struct
Section titled “The record struct”struct openat_args copies the format file field by field, so the compiler
places each member at the offset the kernel uses. The common header is the
four common_ fields, syscall_nr sits at offset 8, and the compiler adds
the 4 bytes of padding by itself, because the next member, a long, must
start on an 8-byte boundary. The arguments are declared long, 8 bytes on
the BPF target, so that each one fills its slot; filename keeps the
pointer type.
The program takes the record as struct openat_args *ctx, and
ctx->filename compiles to an 8-byte load at offset 24 of the context. The
verifier accepts aligned loads from a tracepoint context and records the
highest offset the program reads. At attach, the kernel compares that offset
with the size of this tracepoint’s record, 48 bytes here, and refuses
a program that reads past the end: on 6.18, a version that also reads a
field at offset 48 loads, and its attach fails with EACCES, “permission
denied”.
A mistake inside the record goes unnoticed: neither the verifier nor the
attach knows which field you meant to read. The _Static_assert makes clang
check the one offset this program depends on. Without the syscall_nr line,
filename would land at offset 16, where dfd is, and the build stops:
open_names.bpf.c:29:16: error: static assertion failed due to requirement '__builtin_offsetof(struct openat_args, filename) == 24': filename must be at offset 24, as in the format fileA pointer into the calling process
Section titled “A pointer into the calling process”The filename field does not hold the file name. It holds the pointer the
process passed to openat(2), an address in that process’s memory, the
memory the program sees as user space. The string is still in the
process when the tracepoint fires, at the start of the system call, before
the kernel has read it.
The program may not dereference that pointer. The verifier knows ctx points
at the record, but it knows nothing about the address stored in it, and user
memory can be unmapped, or mapped but not loaded, at any moment. So the
program asks the kernel to copy the string with a helper.
bpf_probe_read_user_str(name, sizeof(name), ctx->filename) copies bytes
from the user address into name until it has copied a NUL byte or filled
the buffer, and it always ends the copy with a NUL. It returns the number of
bytes copied, NUL included, or a negative error when the address cannot be
read, for example because the page is not in memory: the program runs in a
context that cannot sleep, so the helper does not wait for the page to be
loaded. On an error the program skips the event.
bpf_probe_read_user_str is a GPL-only helper, so the license section
matters here. With a license string that is not GPL-compatible, the load
fails with EINVAL, and the verifier’s log says
cannot call GPL-restricted function from non-GPL compatible program.
The 32-byte key
Section titled “The 32-byte key”The map’s key type is char[NAME_LEN], an array of 32 bytes, so the map’s
key size is 32 and every key is exactly 32 bytes. The kernel hashes and
compares all 32 of them. That is why name starts zeroed with = {}: the
bytes after the copied name and its NUL stay 0, and two opens of the same
name build the same key. Without the initializer, the bytes after the NUL
would be whatever the stack held before, and the same name could produce
different keys.
The helper already ends the copy with a NUL. The line
name[NAME_LEN - 1] = '\0' keeps the last byte 0 whatever happened, so a
reader of the key always finds a terminator within the 32 bytes.
Look up, then add or insert
Section titled “Look up, then add or insert”bpf_map_lookup_elem(&counts, name) returns a pointer to the count stored
for the name, or NULL when the name is not in the map yet. When it is there,
the program adds one with __atomic_fetch_add, as the first program did.
When it is not, the program inserts a count of 1 with
bpf_map_update_elem(&counts, name, &one, BPF_NOEXIST). BPF_NOEXIST makes
the insert fail if the key exists. That matters because the tracepoint runs
on every CPU at once: between this program’s lookup and its insert, the same
program on another CPU can insert the same name. With BPF_NOEXIST, the
second insert fails instead of overwriting the other CPU’s count, and the
program looks the name up again and adds one to it. The insert also fails
when the map holds max_entries names already; then the second lookup
returns NULL, and the open is not counted.
Why a hash map
Section titled “Why a hash map”An array map is indexed by a number from 0 to max_entries - 1, and all its
slots exist, zeroed, from the moment the kernel creates it. File names are
not small numbers, so they cannot index an array. A hash map,
BPF_MAP_TYPE_HASH, takes any fixed-size key, here 32 bytes, and holds up to
max_entries elements, which exist only once something inserts them. This
one holds up to 1024 names; once it is full, the opens of a name that is not
already in it are not counted. The maps chapter covers
the other map types, including one that evicts old entries when it is full.
Names longer than the buffer
Section titled “Names longer than the buffer”bpf_probe_read_user_str copies at most sizeof(name) bytes, NUL included.
For a path of 32 bytes or more it copies the first 31 bytes, adds the NUL,
and returns 32, the buffer size. This is not an error: the program counts the
open under the first 31 bytes of the path. Two long paths that share their
first 31 bytes share one key and one count. The next chapter’s run shows a
real case, three paths under /sys/bus/event_source/devices/kprobe/ counted
as /sys/bus/event_source/devices/k. A larger buffer moves the limit; the
kprobes chapter shows how far
the BPF stack allows.
The Go program
Section titled “The Go program”// SPDX-License-Identifier: LGPL-2.1-only
// Command step02 attaches a tracepoint program to sys_enter_openat that// counts openat calls per file name, opens /etc/hostname three times and// /etc/hosts twice, and prints every name in the map with its count. 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")
func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, "step02:", err) os.Exit(1) }}
func run() error { obj, err := bpf.OpenFile("open_names.bpf.o", nil) if err != nil { return err } defer obj.Close()
if err := obj.Load(); err != nil { return err }
prog := obj.Program("handle_openat") if prog == nil { return errors.New("no program named handle_openat in the object") } link, err := prog.AttachTracepoint("syscalls", "sys_enter_openat") if err != nil { return err } defer link.Destroy()
for _, opens := range []struct { path string times int }{{"/etc/hostname", 3}, {"/etc/hosts", 2}} { for range opens.times { f, err := os.Open(opens.path) 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") }
// Walk the hash map: an empty curKey asks for the first key, and each // key found is the curKey of the next call, until ENOENT. 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 }
// The key is the name padded with NUL bytes to 32 bytes. name, _, _ := bytes.Cut(nextKey, []byte{0}) fmt.Printf("%4d %s\n", binary.NativeEndian.Uint64(value), name)
curKey = append(curKey[:0], nextKey...) } return nil}The program opens, loads and attaches as the first program did, and opens
the two files. Each os.Open makes one openat(2) call, so the tracepoint
fires three times with /etc/hostname and twice with /etc/hosts.
A hash map has no slot numbers to loop over, so the program asks the kernel
for the keys one at a time. counts.NextKey(curKey, nextKey) sends
BPF_MAP_GET_NEXT_KEY: the kernel finds curKey in the map and copies the
key that follows it into nextKey. An empty curKey, the nil slice on the
first call, asks for the first key. After the last key, the call returns an
error that wraps ENOENT, which errors.Is(err, unix.ENOENT) detects, and
the loop ends. Any other error is a real failure.
For each key, counts.Lookup(nextKey, value, 0) reads the count, an 8-byte
__u64 in the CPU’s byte order. The key comes back as the same 32 bytes the
program built: the name, its NUL and zeros. bytes.Cut(nextKey, []byte{0})
keeps the bytes before the first NUL, which are the name. The program then
copies the key into curKey for the next call, since the next call
overwrites nextKey.
The keys come out in the hash table’s order, not in the order the names were
inserted. The program is still attached during the walk, so other processes
can add names while it runs. A name added during the walk may or may not be
listed, and the walk restarts from the first key if curKey disappears from
the map, which never happens here because nothing deletes from it.
Build and run
Section titled “Build and run”-
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/step02-tracepointsudo env PATH="$PATH" go run .
On 6.18, with nothing else opening files during the run, the output is:
3 /etc/hostname 2 /etc/hostsThe program counts every openat(2) call on the machine while it is
attached, from every process. A file another process opens between the
attach and the walk appears as an extra line, and if another process opens
/etc/hostname or /etc/hosts in that window, their counts are higher. They
are never lower than 3 and 2: each open in the loop fires the tracepoint in
the Go program’s own thread, before os.Open returns. The lines can come out
in either order.
The tracepoint gives a fixed record for one event. A kprobe reaches almost any kernel function, and reads its arguments from the CPU registers instead.
