Helpers
Every program so far called functions it did not define:
bpf_map_lookup_elem, bpf_probe_read_user_str,
bpf_get_current_pid_tgid. These are helpers, the functions the kernel
offers to BPF programs. This chapter explains what a helper is, what the
verifier checks when a program calls one, how to find out which helpers a
program may call, and how helpers differ from kfuncs, the newer way for
the kernel to offer functions to BPF. The example calls two more helpers: it
records, for each process name, how many files the process opened and the
time between its first and its last open.
Directoryexamples/tutorial/step06-helpers/
- comm_stats.bpf.c the tracepoint program
- main.go the Go program
What a helper is
Section titled “What a helper is”A helper is a function in the kernel that BPF programs may call, known by
a number, its helper ID. The IDs are part of the kernel’s user-space
interface, the UAPI header linux/bpf.h, which lists them in
enum bpf_func_id: ID 1 is bpf_map_lookup_elem, ID 5 is
bpf_ktime_get_ns, ID 16 is bpf_get_current_comm. An ID never changes
meaning, and a helper, once added, is not removed, so a program that calls
helper 16 calls the same function on every kernel that has it.
A program calls a helper with the BPF call instruction, which holds the ID,
and follows the BPF calling convention: the arguments go in registers R1
to R5, so a helper takes at most five, and the result comes back in R0. The
call may change R1 to R5; R6 to R9 keep their values across it, and R10, the
frame pointer, is read-only.
In C, the helpers are declared in libbpf’s bpf_helper_defs.h, which
bpf_helpers.h includes. The file is generated from the documentation
comments in the kernel’s linux/bpf.h, and repeats them above each
declaration. A helper is declared as a constant function pointer whose value
is its ID:
static long (* const bpf_get_current_comm)(void *buf, __u32 size_of_buf) = (void *) 16;No function lives at address 16. clang compiles a call through this pointer
into a call instruction with 16 as its operand. In the disassembly of this
chapter’s object, from llvm-objdump -d --no-show-raw-insn comm_stats.bpf.o,
the calls of the two helpers are call 0x10 and call 0x5:
5: w2 = 0x10 6: call 0x10 7: if r0 s< 0x0 goto +0x20 <L1> 8: call 0x5 9: r6 = r0Instruction 5 puts the buffer’s size, 16, in R2, and R1 already holds the buffer’s address on the stack; instruction 9 saves the clock’s value from R0 in R6, which the following calls leave alone.
What the verifier checks
Section titled “What the verifier checks”The object holds only IDs, and the loader passes the instructions to the
kernel as they are. The checks happen in the kernel, at load. Each program
type defines the set of helpers it allows, and for each one the helper’s
prototype: what each argument must be, what the helper returns, and
whether it is GPL-only. For each call, the verifier looks the ID up in the
program type’s set and checks the call against the prototype:
-
The ID is in the program type’s set. Tracepoint programs may read the current task’s name, but they have no socket buffer, so the helpers for socket buffers are not in their set. A tracepoint program that calls
bpf_skb_load_bytesfails to load withEINVAL, and on 6.18 the verifier’s log ends with:4: (85) call bpf_skb_load_bytes#26program of this type cannot use helper bpf_skb_load_bytes#26 -
The license allows it. Some helpers are GPL-only: the kernel lets only programs with a GPL-compatible license string, such as
GPL,Dual BSD/GPLorDual MIT/GPL, call them.bpf_probe_read_user_str,bpf_probe_read_kernelandbpf_get_current_taskare GPL-only. A program that callsbpf_get_current_taskunder the licenseProprietaryfails to load withEINVAL:0: (85) call bpf_get_current_task#35cannot call GPL-restricted function from non-GPL compatible programThe helpers this chapter’s program calls are not GPL-only: built with the license
Proprietary, it loads on 6.18. The examples keepGPLanyway. -
The arguments match. The prototype gives each argument a kind: a map, a pointer to a key, a pointer to memory the helper writes, a size. For
bpf_get_current_comm, R1 must point to memory the program may write, such as a stack buffer, and R2 must be a size the verifier can bound, which it checks against that buffer. -
The result is used safely. The prototype also gives the kind of the result.
bpf_map_lookup_elemreturns a pointer to a map value or NULL, and the verifier refuses a dereference before the NULL check, as the first program showed.
A helper is called by a fixed ID that the verifier checks against the program type. A kfunc is called by name, which the loader resolves to a BTF ID in the running kernel.
Once the program passes, the kernel rewrites each call: the operand stops
being the ID and becomes the helper function’s distance from a fixed base
address in the kernel, so the JIT compiler can emit a direct call. For some
helpers it goes further. On 6.18, sudo bpftool prog dump xlated name handle_openat, run while this chapter’s program was loaded, shows the
helper calls with their names, and the hash map lookup replaced by a call to
the hash table’s own lookup function, followed by an addition that moves R0
from the element to its value. An excerpt, with instructions 9 to 11 left
out:
; if (bpf_get_current_comm(comm, sizeof(comm)) < 0) 5: (b4) w2 = 16 6: (85) call bpf_get_current_comm#273632; if (bpf_get_current_comm(comm, sizeof(comm)) < 0) 7: (c5) if r0 s< 0x0 goto pc+36; now = bpf_ktime_get_ns(); 8: (85) call bpf_ktime_get_ns#273280...; s = bpf_map_lookup_elem(&stats, comm); 12: (18) r1 = map[id:56910] 14: (85) call __htab_map_lookup_elem#334304 15: (15) if r0 == 0x0 goto pc+1 16: (07) r0 += 64The numbers after # depend on the kernel build, and the map ID changes on
every load.
Which helpers a program may call
Section titled “Which helpers a program may call”bpftool feature probe kernel tries each helper with each program type on
the running kernel, by loading a small program that calls it, and lists the
helpers that loaded:
sudo bpftool feature probe kernel | grep -A5 'program type tracepoint:'eBPF helpers supported for program type tracepoint: - bpf_map_lookup_elem - bpf_map_update_elem - bpf_map_delete_elem - bpf_probe_read - bpf_ktime_get_nsOn 6.18 the full list has 79 helpers for tracepoint programs and 102 for XDP
programs. For tracing, LSM, struct_ops and extension programs it prints
Could not determine which helpers are available: those programs load only
with an attach target, which the probe does not give. The sets grow with the
kernel, so a helper a program needs can be missing on an older kernel. The
load then fails with EINVAL and a log line that names the helper: the
cannot use helper line above on 6.18, and on 5.10
unknown func bpf_skb_load_bytes#26 for the same program.
What each helper does is in man 7 bpf-helpers, where the distribution
ships it, and in the comment above each declaration in bpf_helper_defs.h.
The list ends at ID 211, bpf_cgrp_storage_delete, added in Linux 6.2; the
kernel developers add new functions for BPF as kfuncs instead.
Why not any kernel function
Section titled “Why not any kernel function”A BPF program cannot call an arbitrary kernel function, such as
do_sys_openat2 or kmalloc. The call instruction holds an ID, not an
address, so there is no way to name one. More to the point, the verifier
proves a program safe before it runs, and it can do that only for a call
whose contract it knows: which arguments must be valid pointers and how
large the memory behind them is, whether the result can be NULL, whether the
function may sleep, take a lock or hold a reference the program must give
back. A helper’s prototype states that contract, and the helper is written
to accept any arguments that satisfy it. A kernel function in general
assumes its callers obey rules no one has written down for the verifier, and
calling one with the wrong arguments could crash the kernel.
kfuncs
Section titled “kfuncs”A kfunc is a kernel function that the kernel registers for use by BPF programs. It differs from a helper in four ways:
- It is found through BTF, not by an ID. A kfunc has no number in
linux/bpf.h. The program declares it by name, and the loader looks the name up in the kernel’s BTF, the type information the kernel publishes at/sys/kernel/btf/vmlinux. clang emits the call with a mark that makes it a kfunc call and a relocation against the name, and the loader writes the function’s BTF ID, its index among the kernel’s types, into the instruction. BTF IDs differ from one kernel build to the next, so the loader resolves the name again at every load. The verifier checks the arguments against the function’s prototype in that BTF. - A module can provide it. A kernel module registers kfuncs too, in its
own BTF under
/sys/kernel/btf/<module>. The loader then also passes the module’s BTF to the kernel, and the instruction carries an index that names it. - It has no stability promise. Helpers are part of the UAPI; kfuncs are an interface inside the kernel, and kernel developers may change or remove one between versions, as they may any internal function.
- Flags describe its contract. When the kernel registers a kfunc, it
gives it
KF_flags that the verifier enforces.KF_ACQUIREmeans the function returns a reference the program must give back,KF_RELEASEthat it gives one back,KF_RET_NULLthat it may return NULL, andKF_SLEEPABLEthat only sleepable programs may call it. The registration also lists the program types allowed to call it.
In C, a kfunc is an extern declaration with the __ksym attribute, which
places it in the object’s .ksyms section. A vmlinux.h generated by a
recent bpftool, which the CO-RE and BTF
chapter introduces, already declares the kernel’s kfuncs: generated by
bpftool 7.8 on 6.18, it declares 250 of them, as __weak externs.
At load, gobpfgo resolves each typed .ksyms extern as libbpf does: a kernel
variable or a kernel function call is looked up by name in the vmlinux BTF
first and then in the module BTFs, and its type must be compatible with the
declaration. BpfObjectOpenOpts.BtfModuleAllowlist limits which modules
it reads. A name found nowhere fails the load before the kernel sees the
program; on 6.18, a call to a kfunc that does not exist fails with:
bpf_object__resolve_externs: invalid argument: extern (func ksym) 'bpf_task_from_pid_v2': not found in kernel or module BTFs: no such processDeclared __weak, the missing kfunc no longer fails the resolution: its
call is replaced by an invalid one, and the program loads only if that call
is never reached. bpf_ksym_exists(name), from bpf_helpers.h, is false
for an unresolved weak extern, so the program can test it and take another
path; without the test, the verifier stops at the call with
kfunc 'bpf_task_from_pid_v2' is referenced but wasn't resolved.
// Sketch: not in examples/. Needs vmlinux.h for the kernel types.extern struct task_struct *bpf_task_from_pid(s32 pid) __ksym;extern void bpf_task_release(struct task_struct *p) __ksym;
__u32 init_tgid;
SEC("fentry/do_sys_openat2")int BPF_PROG(find_init, int dfd, const char *filename, struct open_how *how){ struct task_struct *init = bpf_task_from_pid(1); // KF_ACQUIRE | KF_RET_NULL
if (!init) return 0; init_tgid = init->tgid; bpf_task_release(init); // KF_RELEASE return 0;}bpf_task_from_pid takes a reference on the task with process ID 1 and
returns it, or NULL. Because of KF_RET_NULL, the verifier refuses to read
init->tgid before the NULL check. Because of KF_ACQUIRE, it tracks the
reference until a KF_RELEASE function gives it back. Without the
bpf_task_release call, the load fails with EINVAL, and the log ends with:
Unreleased reference id=2 alloc_insn=1BPF_EXIT instruction in main prog would lead to reference leakThe example: opens per process name
Section titled “The example: opens per process name”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>
// The kernel's TASK_COMM_LEN: a task name is at most 15 bytes and a NUL.#define COMM_LEN 16
// comm_stats is the value stored for each process name: how many opens it// made, and the times of its first and last open, in nanoseconds since// boot. Three __u64, 24 bytes, with no padding.struct comm_stats { __u64 count; __u64 first_ns; __u64 last_ns;};
// stats maps a process name, NUL-padded to 16 bytes, to its comm_stats.struct { __uint(type, BPF_MAP_TYPE_HASH); __uint(max_entries, 1024); __type(key, char[COMM_LEN]); __type(value, struct comm_stats);} stats SEC(".maps");
// The program reads nothing from the tracepoint's record, so ctx stays// untyped: everything it needs comes from helpers.SEC("tracepoint/syscalls/sys_enter_openat")int handle_openat(void *ctx) { char comm[COMM_LEN] = {}; struct comm_stats *s; __u64 now;
// Helper 16 copies the calling task's name and NUL-terminates it. if (bpf_get_current_comm(comm, sizeof(comm)) < 0) return 0; // Helper 5 reads the monotonic clock: nanoseconds since boot, without // the time the system spent suspended. now = bpf_ktime_get_ns();
s = bpf_map_lookup_elem(&stats, comm); if (!s) { // First open by this name: store a count of 1 and both times. struct comm_stats first = { .count = 1, .first_ns = now, .last_ns = now, };
// BPF_NOEXIST fails if another CPU inserted the name in // between; then the second lookup finds that CPU's element. if (bpf_map_update_elem(&stats, comm, &first, BPF_NOEXIST) == 0) return 0; s = bpf_map_lookup_elem(&stats, comm); if (!s) return 0; } __atomic_fetch_add(&s->count, 1, __ATOMIC_RELAXED); // A plain store: another CPU may have stored a later time since this // one read the clock, so keep the later of the two. if (now > s->last_ns) s->last_ns = now; return 0;}
// The helpers here are not GPL-only, but the examples keep one license.char LICENSE[] SEC("license") = "GPL";The program attaches to the sys_enter_openat tracepoint, as in the
tracepoints chapter, but it reads nothing from
the record: everything it needs comes from helpers, so ctx stays void *.
The key. bpf_get_current_comm(comm, sizeof(comm)) copies the name of
the task that is running, its comm, into comm. The kernel sets a
task’s comm to the file name of the program it executes, cut to 15 bytes, in
a field of 16 bytes, TASK_COMM_LEN; a task can rename itself with
prctl(PR_SET_NAME), and /proc/<pid>/comm shows the name. The helper
always ends the copy with a NUL. As in the tracepoint program, comm starts
zeroed, so the bytes after the NUL are 0 and the same name always builds the
same 16-byte key. The helper returns a negative error on failure, and the
program skips the event.
The time. bpf_ktime_get_ns() returns the monotonic clock, the time
since boot in nanoseconds, not counting time the system spent suspended,
which is what clock_gettime(CLOCK_MONOTONIC) returns in user space. Only
differences between two readings mean something, which is how the program
uses it. bpf_ktime_get_boot_ns counts the suspended time too.
The value. The map’s value type is a struct of three __u64, so the
map’s value size is 24 bytes. The map stores the bytes; the struct’s layout
is a contract between the C program and the Go program that reads them.
Insert or update. The program looks the name up. The first open by a
name finds nothing, and the program inserts a value with a count of 1 and
both times set to now, with BPF_NOEXIST, as in the earlier chapters: if
another CPU inserted the same name between the lookup and the insert, the
insert fails, and the program looks the name up again and updates the value
that CPU inserted. When the map is full, the second lookup finds nothing and
the open is not counted.
A later open adds one to count atomically, with __atomic_fetch_add, and
stores the time in last_ns. That store is plain, not atomic, and two CPUs
can race on it: a CPU that read the clock first can store after one that
read it later. if (now > s->last_ns) keeps the later time in the common
case, including the insert race above, where the second lookup can find a
last_ns later than this CPU’s reading. Two CPUs can still pass the test
together and store in the wrong order, so under contention last_ns can be
a little early, which does not matter for a span printed in microseconds.
The Go program
Section titled “The Go program”// SPDX-License-Identifier: LGPL-2.1-only
// Command step06 attaches a tracepoint program to sys_enter_openat that// records, per process name, how many opens it made and when the first and// the last happened. It opens /etc/hostname and /etc/hosts three times, 100// milliseconds apart, and prints every name in the map with its count and// the time between its first and last open. Run it as root from this// directory, after make in examples/.package main
import ( "bytes" "encoding/binary" "errors" "fmt" "os" "time"
"github.com/gobpfgo/gobpfgo/bpf" "golang.org/x/sys/unix")
// commStats mirrors struct comm_stats in comm_stats.bpf.c: three uint64// fields in the same order, 24 bytes with no padding.type commStats struct { Count uint64 FirstNs uint64 LastNs uint64}
func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, "step06:", err) os.Exit(1) }}
func run() error { obj, err := bpf.OpenFile("comm_stats.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()
// Three rounds 100 ms apart, so this process's first and last opens // are about 200 ms apart. for round := range 3 { if round > 0 { time.Sleep(100 * time.Millisecond) } for _, path := range []string{"/etc/hostname", "/etc/hosts"} { f, err := os.Open(path) if err != nil { return err } if err := f.Close(); err != nil { return err } } }
stats := obj.Map("stats") if stats == nil { return errors.New("no map named stats in the object") } if want := binary.Size(commStats{}); int(stats.ValueSize()) != want { return fmt.Errorf("stats values are %d bytes, commStats is %d", stats.ValueSize(), want) }
fmt.Printf("%-16s %5s %12s\n", "COMM", "OPENS", "SPAN (us)") var curKey []byte nextKey := make([]byte, stats.KeySize()) value := make([]byte, stats.ValueSize()) for { err := stats.NextKey(curKey, nextKey) if errors.Is(err, unix.ENOENT) { break } if err != nil { return err } if err := stats.Lookup(nextKey, value, 0); err != nil { return err }
// The value is the C struct's bytes in the CPU's byte order. var s commStats if _, err := binary.Decode(value, binary.NativeEndian, &s); err != nil { return err } // The key is the name padded with NUL bytes to 16 bytes. comm, _, _ := bytes.Cut(nextKey, []byte{0}) span := (s.LastNs - s.FirstNs) / 1000 fmt.Printf("%-16s %5d %12d\n", comm, s.Count, span)
curKey = append(curKey[:0], nextKey...) } return nil}The program opens, loads and attaches as in the tracepoints chapter. It
opens /etc/hostname and /etc/hosts in three rounds, 100 milliseconds
apart, so its own entry has 6 opens over about 200 milliseconds.
commStats is the Go side of the contract: three uint64 fields in the same
order as the C struct’s three __u64. Neither struct has padding, so the
fields sit at offsets 0, 8 and 16 in both. Before decoding anything, the
program compares binary.Size(commStats{}), 24, with the map’s value size,
so a struct changed on one side alone stops the run instead of decoding the
wrong bytes. binary.Decode(value, binary.NativeEndian, &s) fills the struct from
the value’s bytes, in the CPU’s byte order, the order the BPF program wrote
them in. Its fields are exported because encoding/binary sets fields
through reflection, which can set only exported ones.
The walk with NextKey is the one from the tracepoints chapter. Each key is
the 16-byte name, cut at its first NUL with bytes.Cut. The duration is
LastNs - FirstNs, divided by 1000 to print microseconds.
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/step06-helperssudo env PATH="$PATH" go run .
On 6.18 the output is:
COMM OPENS SPAN (us)Thread-2 (_loop 32 86337Bun Pool 2 1 0basalt 24 100396step06-helpers 6 200749step06-helpers is the Go program: go run builds a binary named after the
directory and runs it, and the kernel takes the comm from the binary’s name.
Its 6 opens span 200749 microseconds, the two 100-millisecond sleeps and the
time the opens took. Go does not rename its threads, so the opens from every
thread of the Go program land in this one entry.
The other lines are tasks that opened files on the same machine while the
program was attached. The comm belongs to each thread, not to the process:
Thread-2 (_loop is a thread that gave itself a longer name, cut to 15
bytes. A task that opened one file has a span of 0. The names, counts and
number of lines change from run to run, and the lines come out in the hash
table’s order. Tasks that share a name, such as several shells, share one
entry.
Helpers like bpf_get_current_task return a pointer to a kernel struct.
Reading its fields on any kernel takes BTF and CO-RE.
