Skip to content

Your first program

This chapter builds a small tool that counts openat(2) system calls. The BPF program attaches to the tracepoint syscalls/sys_enter_openat and adds one to a counter in a map each time the tracepoint fires. The Go program loads it, opens /etc/hostname five times, and prints the counter.

The code on this page is the code in the repository, embedded from the files below, which are built and run as part of the examples.

  • Directoryexamples/
    • Makefile builds every tutorial/*/*.bpf.c
    • go.mod the examples module
    • Directorytutorial/
      • Directorystep01/
        • open_count.bpf.c the BPF program
        • main.go the Go program
        • Directorycore/
          • main.go the same program on the libbpf core, for the next chapter
examples/tutorial/step01/open_count.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 <bpf_helpers.h>
// counts is an array map with one slot: key 0 holds the number of
// openat(2) calls seen since the program was attached.
struct {
__uint(type, BPF_MAP_TYPE_ARRAY);
__uint(max_entries, 1);
__type(key, __u32);
__type(value, __u64);
} counts SEC(".maps");
// The section name tells the loader the program type and the hook: a
// tracepoint program for the syscalls/sys_enter_openat tracepoint.
SEC("tracepoint/syscalls/sys_enter_openat")
int handle_open(void *ctx) {
__u32 key = 0;
__u64 *value;
// The helper returns a pointer into the map value, or NULL.
value = bpf_map_lookup_elem(&counts, &key);
if (value)
// Other CPUs may run the program at the same time, so the
// increment is atomic. With the result unused, clang emits the
// plain atomic add that every kernel from 5.10 accepts.
__atomic_fetch_add(value, 1, __ATOMIC_RELAXED);
return 0;
}
// The kernel lets only programs with a GPL-compatible license call
// GPL-only helpers, such as bpf_probe_read_kernel.
char LICENSE[] SEC("license") = "GPL";

The C file sits in the same directory as a Go package. The Go tool refuses .c files in a package that does not use cgo, so the //go:build ignore line excludes the file from Go builds. clang reads it as a comment.

linux/bpf.h defines the map types and other constants of the BPF interface, such as BPF_MAP_TYPE_ARRAY. libbpf’s bpf_helpers.h defines the SEC, __uint and __type macros and declares the helpers, such as bpf_map_lookup_elem.

The counts struct describes a map; it holds no data itself. Its members record the map’s attributes as types, which clang writes into the object’s BTF: the map type is BPF_MAP_TYPE_ARRAY, it has one entry, the key is a __u32 and the value a __u64. SEC(".maps") places the definition in the .maps section, where the loader looks for map definitions. At load, the loader reads this description and asks the kernel to create the map.

An array map has max_entries slots, with the keys 0 to max_entries - 1, and the kernel starts every value at zero. This one has a single slot, key 0.

SEC("tracepoint/syscalls/sys_enter_openat") places handle_open in an ELF section with that name. The loader reads the name: the tracepoint/ prefix makes it a tracepoint program, and the rest names the tracepoint. The Go program attaches it to the same tracepoint explicitly. The function name, handle_open, is how Go finds the program in the object.

The ctx argument points at the tracepoint’s record, laid out as described in /sys/kernel/tracing/events/syscalls/sys_enter_openat/format: the system call number, then the dfd, filename, flags and mode arguments. This program only counts calls, so it does not read the record. The tracepoints chapter does.

bpf_map_lookup_elem(&counts, &key) is a helper. It returns a pointer to the value stored for key in the map, or NULL when there is none. The program changes the value in place through that pointer, so no separate update is needed.

The verifier rejects a dereference of a pointer that may be NULL, so the program checks value first. On 5.10, a version without the check fails to load with R0 invalid mem access 'map_value_or_null'. Newer kernels can prove that an array lookup with a constant key in range never returns NULL and accept that version; keep the check, so the program loads on every kernel.

The tracepoint fires on every CPU, so two CPUs can run the program at the same time and update the same counter. __atomic_fetch_add(value, 1, __ATOMIC_RELAXED) makes the increment atomic. With its result unused, clang emits the plain atomic add instruction, which every kernel from 5.10 accepts. Many examples use __sync_fetch_and_add instead. clang 23, which the examples are tested with, compiles that to the fetching form of the instruction, which needs Linux 5.12; on 5.10 the load fails with BPF_STX uses reserved fields.

The license section holds the program’s license string, which the loader passes to the kernel with the program. The kernel lets only programs with a GPL-compatible license call GPL-only helpers. bpf_map_lookup_elem is not one, but most tracing programs soon use one, such as bpf_probe_read_kernel.

examples/tutorial/step01/main.go
// SPDX-License-Identifier: LGPL-2.1-only
// Command step01 attaches a tracepoint program to sys_enter_openat,
// opens /etc/hostname five times and prints how many openat calls the
// program counted. 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, "step01:", err)
os.Exit(1)
}
}
func run() error {
// Parse the ELF object. Nothing reaches the kernel yet.
obj, err := bpf.OpenFile("open_count.bpf.o", nil)
if err != nil {
return err
}
defer obj.Close()
// Create the counts map and load handle_open through the verifier.
if err := obj.Load(); err != nil {
return err
}
prog := obj.Program("handle_open")
if prog == nil {
return errors.New("no program named handle_open in the object")
}
// From here on the kernel runs handle_open on every openat(2) call,
// from any process, until the link is destroyed.
link, err := prog.AttachTracepoint("syscalls", "sys_enter_openat")
if err != nil {
return err
}
defer link.Destroy()
for range 5 {
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")
}
// The key is a __u32 and the value a __u64, in the host byte order.
key := make([]byte, 4)
value := make([]byte, 8)
if err := counts.Lookup(key, value, 0); err != nil {
return err
}
count := binary.NativeEndian.Uint64(value)
fmt.Printf("openat calls counted: %d\n", count)
return nil
}

The program follows the lifecycle from What is eBPF, one call per step.

  1. Open. bpf.OpenFile("open_count.bpf.o", nil) reads and parses the object: its sections, programs, map definitions and BTF. It makes no kernel call. The path is relative, so the program runs from the step01 directory. nil selects the default open options. The result is a *bpf.Object, and defer obj.Close() releases it when run returns.
  2. Load. obj.Load() asks the kernel to create the counts map, writes the map’s descriptor into handle_open’s instructions, and loads the program, which the kernel passes through the verifier and the JIT. An object loads only once.
  3. Find the program. obj.Program("handle_open") looks the program up by its C function name and returns nil when there is none. The returned *bpf.Program belongs to the object.
  4. Attach. prog.AttachTracepoint("syscalls", "sys_enter_openat") takes the tracepoint’s category and name, as they appear under /sys/kernel/tracing/events. From this call on, the kernel runs handle_open on every openat(2) call on the machine. The returned *bpf.Link belongs to the caller, not to the object, so the program destroys it with defer link.Destroy().
  5. Make events. On Linux, os.Open calls openat(2), so the loop fires the tracepoint five times from this process.
  6. Read the map. obj.Map("counts") finds the map by its C name. counts.Lookup(key, value, 0) copies the value stored for key into value. Both are byte slices of the map’s key and value sizes, 4 bytes for the __u32 key and 8 for the __u64 value; the zeroed key selects slot 0, and 0 is the flags argument. The kernel stores the value in the CPU’s byte order, which binary.NativeEndian decodes.
  7. Detach and close. Deferred calls run in reverse order, so link.Destroy() detaches the program first and obj.Close() then closes the map and program descriptors. A link stays attached after its object is closed until it is destroyed, so destroy every link you create.

Every error is returned to main, which prints it after step01: and exits with status 1. Errors from gobpfgo are *libbpf.Error values that keep the kernel’s errno, so errors.Is(err, unix.EPERM) works.

  1. Build the BPF object from the examples directory:

    Terminal window
    cd examples
    make
    clang -O2 -g -target bpf -D__TARGET_ARCH_x86 \
    -I../../libbpf/include/uapi -I../../libbpf/src \
    -c tutorial/step01/open_count.bpf.c -o tutorial/step01/open_count.bpf.o
  2. Run the Go program as root, from the example’s directory, where it finds open_count.bpf.o:

    Terminal window
    cd tutorial/step01
    sudo env PATH="$PATH" go run .

    sudo resets PATH; passing yours lets root find the go command. To compile as yourself and run only the binary as root, use go build -o /tmp/step01 . && sudo /tmp/step01 from the same directory.

The output is one line:

openat calls counted: 5

The number can be larger than five, and it is never smaller. The tracepoint fires for every openat(2) call on the machine, from every process, while the program is attached. Any other process that opens a file between the attach and the lookup, such as a shell, a daemon or an editor, adds to the count. The five opens in the loop always count: the program runs at the start of each call, in the thread that makes it, so each increment has happened before os.Open returns.

libbpf: Error loading .BTF into kernel: -EPERM. BTF is optional, ignoring.
step01: bpf_map_create: operation not permitted: counts

The program ran without privilege. The kernel refused the object’s BTF, which is optional, and then refused to create the map. Run it with sudo, or give the binary CAP_BPF and CAP_PERFMON. See the permission notes.

When the verifier rejects a program, Load returns an error that ends with the verifier’s log. For example, a version of handle_open that ends with return *(long *)(ctx + 16384);, a read far past the end of the tracepoint record, fails on 6.18 like this:

step01: bpf_prog_load: permission denied: handle_open: arg#0 reference type('UNKNOWN ') size cannot be determined: -22
0: R1=ctx() R10=fp0
; int handle_open(void *ctx) { @ open_count.bpf.c:23
0: (bf) r6 = r1 ; R1=ctx() R6=ctx()
; __u32 key = 0; @ open_count.bpf.c:24
1: (b4) w1 = 0 ; R1=0
2: (63) *(u32 *)(r10 -4) = r1 ; R1=0 R10=fp0 fp-8=0000????
3: (bf) r2 = r10 ; R2=fp0 R10=fp0
4: (07) r2 += -4 ; R2=fp-4
; value = bpf_map_lookup_elem(&counts, &key); @ open_count.bpf.c:28
5: (18) r1 = 0xffff88c245d1e400 ; R1=map_ptr(map=counts,ks=4,vs=8)
7: (85) call bpf_map_lookup_elem#1 ; R0=map_value(map=counts,ks=4,vs=8)
; if (value) @ open_count.bpf.c:29
8: (15) if r0 == 0x0 goto pc+2 ; R0=map_value(map=counts,ks=4,vs=8)
; __atomic_fetch_add(value, 1, __ATOMIC_RELAXED); @ open_count.bpf.c:33
9: (b7) r1 = 1 ; R1=1
10: (db) lock *(u64 *)(r0 +0) += r1 ; R0=map_value(map=counts,ks=4,vs=8) R1=1
; return *(long *)(ctx + 16384); @ open_count.bpf.c:35
11: (79) r0 = *(u64 *)(r6 +16384)
invalid bpf_context access off=16384 size=8
processed 11 insns (limit 1000000) max_states_per_insn 0 total_states 1 peak_states 1 mark_read 0

Read the log from the bottom up. The last instruction before the summary is the one the verifier refused, with the reason: invalid bpf_context access off=16384 size=8. Above it, each instruction appears with the source line it came from, which the -g flag makes possible, and the state of the registers the verifier tracked. The note on the first line, about the void * argument, is informational.

The verifier usually rejects a program with EACCES, whose text is “permission denied”. It is not a privilege problem: missing privilege is EPERM, “operation not permitted”. Malformed instructions fail with EINVAL, “invalid argument”, like the __sync_fetch_and_add build on 5.10.

step01: bpf_program__attach_tracepoint: no such file or directory

The attach could not find the tracepoint, here because its name was misspelled as sys_enter_opnat. Check the category and name with sudo ls /sys/kernel/tracing/events/syscalls/. The same error appears when tracefs is not mounted, or when the kernel was built without syscall tracepoints (CONFIG_FTRACE_SYSCALLS).

step01: bpf_object__open_file open_count.bpf.o: no such file or directory: open open_count.bpf.o: no such file or directory

The object is not in the current directory. Run make in examples, then run the program from examples/tutorial/step01.

The next chapter shows the same program written against the libbpf core, and when to use each package.