CO-RE and BTF
The programs so far read records, registers and strings, but no kernel
struct. This chapter reads one, three pointers deep: the user ID of the task
that opens a file, task->cred->uid.val. Where cred sits inside
struct task_struct depends on the kernel’s version and configuration, so a
program that hard-codes the offset reads the wrong memory on another kernel.
CO-RE, Compile Once, Run Everywhere, fixes that: clang records the field
by name, and the loader finds its offset in the running kernel when it loads
the program. The example is an fentry program on do_sys_openat2 that counts
opens per user ID, and the same object file runs unchanged on 6.18 and 5.10.
Directoryexamples/
- Makefile generates vmlinux.h and builds the objects
- vmlinux.h generated by make, not checked in
Directorytutorial/step07-core/
- open_uid.bpf.c the fentry program
- main.go the Go program
BTF, the BPF Type Format, describes C types in a compact binary form: integers, pointers, arrays, structs and unions with each member’s name, type and offset, enums, typedefs, and functions with their prototypes. Each type has a number, its type ID, which is its position in the table, and refers to other types by ID; the names are in a string table next to it.
BTF lives in two places:
- In the object. When clang compiles with
-g, it writes the.BTFsection, with the types the program uses: its maps, its functions, its global variables, and the kernel structs it reads. It also writes.BTF.ext, with information about the instructions: which function each belongs to, which source line it comes from, and the CO-RE relocations this chapter is about. - In the kernel. A kernel built with
CONFIG_DEBUG_INFO_BTF=ypublishes the BTF of every type in the kernel image at/sys/kernel/btf/vmlinux. WithCONFIG_DEBUG_INFO_BTF_MODULES=y, each loaded module adds its own file under/sys/kernel/btf/, named after the module, which holds only the module’s types and refers to the kernel’s by ID. On the 6.18 machine this page was checked on, the directory holdsvmlinuxand 131 module files.
bpftool reads both. Its raw format prints each type with its ID, and each
member on a line of its own, with its offset in bits:
bpftool btf dump file /sys/kernel/btf/vmlinux format raw | grep -A277 "STRUCT 'task_struct'" | grep -E "STRUCT 'task_struct'|'cred'"[115] STRUCT 'task_struct' size=6016 vlen=277 'cred' type_id=580 bits_offset=26880On 6.18, struct task_struct is type 115, 6016 bytes with 277 members, and
its member cred starts at bit 26880, byte 3360. The same command, run on
the BTF file of the Debian 5.10 kernel the test suite uses, gives a struct of
9344 bytes with cred at byte 2720. bpftool also prints a note on its error output,
skipping /sys/kernel/btf/vmlinux (will be loaded as base), which does not
change what it dumps.
vmlinux.h
Section titled “vmlinux.h”A BPF program that reads kernel structs needs their definitions to compile.
The kernel UAPI headers the earlier programs used describe only the kernel’s
user-space interface, not internal types such as struct task_struct.
vmlinux.h is a header generated from the kernel’s BTF that declares
every one of its types in C:
bpftool btf dump file /sys/kernel/btf/vmlinux format c > vmlinux.hOn 6.18 the result is about 3.4 MB. It takes the place of <linux/bpf.h>
and the other kernel headers, since it already declares the types they
would, and including both makes clang fail with errors such as
typedef redefinition with different types. libbpf’s
bpf_helpers.h, bpf_tracing.h and bpf_core_read.h work with either.
The file opens with a pragma that applies to every struct and union it
declares, unless the program defines BPF_NO_PRESERVE_ACCESS_INDEX first:
#pragma clang attribute push (__attribute__((preserve_access_index)), apply_to = record)The next section explains what preserve_access_index does. At its end the
file also declares the kernel’s kfuncs, which the helpers
chapter covers.
The examples’ Makefile generates vmlinux.h in examples/:
# SPDX-License-Identifier: LGPL-2.1-only## Builds every tutorial/*/*.bpf.c into a .bpf.o next to it.## make build with the libbpf checkout at ../../libbpf# make LIBBPF=/src/libbpf build with another libbpf checkout# make VMLINUX_BTF=file generate vmlinux.h from another kernel's BTF,# when vmlinux.h is missing or older than file# make clean remove the built objects and vmlinux.h
CLANG ?= clangBPFTOOL ?= bpftoolLIBBPF ?= ../../libbpf
# The running kernel's BTF, from which vmlinux.h is generated.VMLINUX_BTF ?= /sys/kernel/btf/vmlinux
# The BPF target needs the architecture for the PT_REGS macros of# bpf_tracing.h: x86 on x86_64 hosts, arm64 on aarch64 hosts.ARCH := $(shell uname -m | sed -e 's/x86_64/x86/' -e 's/aarch64/arm64/')
BPF_SRCS := $(wildcard tutorial/*/*.bpf.c)BPF_OBJS := $(BPF_SRCS:.bpf.c=.bpf.o)
# The CO-RE programs include "vmlinux.h", which -I. finds in this# directory. They rebuild when it changes; the other programs do not need it.CORE_SRCS := $(shell grep -l 'include "vmlinux.h"' $(BPF_SRCS))CORE_OBJS := $(CORE_SRCS:.bpf.c=.bpf.o)
.PHONY: all clean
all: $(BPF_OBJS)
# vmlinux.h declares every type in the kernel's BTF as C. The kernel dates# the BTF file during the current boot, so after a reboot the file is newer# than the header and make generates it again for the running kernel.vmlinux.h: $(VMLINUX_BTF) $(BPFTOOL) btf dump file $< format c > $@.tmp mv $@.tmp $@
$(CORE_OBJS): vmlinux.h
%.bpf.o: %.bpf.c $(CLANG) -O2 -g -target bpf -D__TARGET_ARCH_$(ARCH) \ -I. -I$(LIBBPF)/include/uapi -I$(LIBBPF)/src \ -c $< -o $@
clean: rm -f $(BPF_OBJS) vmlinux.h vmlinux.h.tmpThe rule for vmlinux.h depends on the BTF file. The kernel dates that file
during the current boot, so after a reboot it is newer than a header
generated before, and make generates the header again from whichever
kernel is running. CORE_SRCS lists the programs that include "vmlinux.h",
and their objects depend on the header, so they rebuild when it changes; the
programs of the earlier chapters do not include it and do not depend on it.
-I. adds examples/, the directory make runs clang from, to the include
path, so #include "vmlinux.h" finds the header from every step.
make VMLINUX_BTF=file generates it from another kernel’s BTF file
instead, when vmlinux.h is missing or older than that file; run
make clean first to replace an existing one.
The header describes one kernel build and is large, so examples/.gitignore
keeps it out of the repository.
An object compiled against one kernel’s vmlinux.h still runs on other
kernels, because the offsets the header gives are only where clang starts.
How clang records a field access
Section titled “How clang records a field access”preserve_access_index is a clang attribute for struct and union types. An
access to a member of such a type, through . or ->, compiles with the
member’s offset from the declaration, as any access does, and clang also
writes a CO-RE relocation into .BTF.ext: a record that names the
instruction, the type, and the path of member names from the type to the
field. Without the attribute, the offset is a constant in the code and
nothing records where it came from.
The program reads the user ID with BPF_CORE_READ(task, cred, uid.val), a
macro from libbpf’s bpf_core_read.h. It expands to two reads: first the
pointer task->cred, then uid.val from the struct cred it points to.
Each read is a call to the helper bpf_probe_read_kernel, with the address
computed under __builtin_preserve_access_index, the builtin form of the
attribute. The disassembly with relocations, from
llvm-objdump -dr --no-show-raw-insn open_uid.bpf.o, starts:
0: call 0x23 1: r7 = 0x1 2: *(u64 *)(r10 - 0x8) = r7 3: r1 = 0xd20 0000000000000018: CO-RE <byte_off> [18] struct task_struct::cred (0:131) 4: r0 += r1 5: r1 = r10 6: r1 += -0x18 7: w2 = 0x8 8: r3 = r0 9: call 0x71 10: r1 = 0x8 0000000000000050: CO-RE <byte_off> [152] struct cred::uid.val (0:1:0) 11: r3 = *(u64 *)(r10 - 0x18) 12: r3 += r1Instruction 0 calls helper 35, bpf_get_current_task, which returns the
address of the current task’s struct task_struct in R0. Instruction 3 puts
0xd20, 3360, in R1: the offset of cred in the vmlinux.h the object was
compiled against. The relocation record under it says that the value at
instruction 3 is the byte offset, byte_off, of task_struct::cred. [18]
is the ID of struct task_struct in the object’s own BTF, and 0:131 is the
access path: element 0 behind the pointer, then member 131 of the
struct. Instruction 4 adds the offset to the task’s address, and instruction
9 calls helper 113, bpf_probe_read_kernel, to copy the 8-byte pointer into
the stack. The second record does the same for uid.val, member 1 of
struct cred, uid, then member 0 of its type, kuid_t, val, at offset
8.
How the loader patches the offset
Section titled “How the loader patches the offset”The relocation records stay in the object; the kernel never sees them. The
loader, gobpfgo in Object.Load, applies them before it sends any program
to the kernel, as libbpf does:
- It reads the program’s relocation records from
.BTF.ext. - It reads the target BTF, the running kernel’s types, from
/sys/kernel/btf/vmlinux. - For each record, it collects the candidates: the types in the target
BTF with the same kind and name as the local type, here every struct named
task_struct. It looks in the module BTFs only when vmlinux has no candidate. - In each candidate, it follows the access path by member name, not by
number:
cred, thenuidin the typecredpoints to, thenval, and checks that each step has a compatible kind, such as a struct where the local type has a struct. The position ofcredamong the members does not matter. - It computes the field’s byte offset in the target. If two candidates give different offsets, the relocation is ambiguous and the load fails.
- It writes the offset into the instruction: the immediate of
r1 = 0xd20here, or the offset field of a load instruction when the program reads a field directly.
A field access becomes a relocation that the loader resolves by name in the running kernel’s BTF. A field the kernel lacks leaves a poisoned instruction, which fails the load only if it can run.
On 6.18, the kernel this page was checked on, the offset is the one the
object already holds, and sudo bpftool prog dump xlated name count_uid,
run while the program was loaded, shows instruction 3 unchanged:
3: (b7) r1 = 3360 4: (0f) r0 += r1The same object, byte for byte, also loads and counts correctly on the
Debian 5.10 kernel. Read back from that kernel after the load, instruction 3
is r1 = 2720. The two kernels disagree on everything around the field:
| 6.18 | 5.10 | |
|---|---|---|
Size of struct task_struct |
6016 bytes | 9344 bytes |
Offset of cred |
3360 | 2720 |
Offset of uid in struct cred |
8 | 8 |
| Instruction 3 after the load | r1 = 3360 |
r1 = 2720 |
That is why CO-RE survives layout changes. The relocation names the field,
not its position, so members added, removed or moved around cred, and
kernel configuration options that grow or shrink the struct, do not matter:
the loader finds cred by name in whatever layout the running kernel has.
What it cannot survive is a field that is gone, renamed, or changed into a
different kind of type. That is a failed relocation, covered below.
The verifier’s role
Section titled “The verifier’s role”The loader patches the instructions in user space, and the kernel receives a program with plain offsets in it. The verifier checks it like any other program; it does not know an offset came from CO-RE, and it does not check that the loader picked the right one.
In this program, both reads go through bpf_probe_read_kernel. The task’s
address from bpf_get_current_task is a plain number to the verifier, not a
pointer it can follow, so the verifier checks only the helper’s arguments:
a stack buffer and its size. The helper copies from the address with the
kernel’s fault handling, so a wrong offset gives a wrong value, or an error
with the buffer filled with zeros, but does not crash the kernel. The
verifier cannot catch a wrong offset here; CO-RE is what keeps it right.
When the program holds a pointer whose type the verifier knows from the
kernel’s BTF, such as an fentry argument, it can read a field with a plain
load, which CO-RE relocates the same way. The verifier then checks the load
against the kernel’s type. In an fentry program on do_sys_openat2,
how->flags compiles to r1 = *(u64 *)(r1 + 0x0) with a relocation for
open_how::flags, and loads. A version that reads 8 bytes at offset 24 of
how, past the end of the 24-byte struct open_how, fails on 6.18 with
EACCES; an excerpt of the log:
func 'do_sys_openat2' arg2 has btf_id 12904 type STRUCT 'open_how'1: R1=ptr_open_how()1: (79) r1 = *(u64 *)(r1 +24)access beyond struct open_how at off 24 size 8When a field is missing
Section titled “When a field is missing”Kernel fields do get renamed. In Linux 5.14, task_struct’s state became
__state: the 5.10 kernel’s BTF has state at offset 16, and 6.18’s has
__state at offset 24 and no state. A program written for older kernels
reads state, which the 6.18 vmlinux.h does not declare, so it declares
the old layout itself:
// Before Linux 5.14, task_struct had a field named state.struct task_struct___old { long state;} __attribute__((preserve_access_index));
__u32 state = BPF_CORE_READ((struct task_struct___old *)task, state);The part of a type’s name from three underscores on, ___old, is a
flavor: the loader ignores it when it looks for candidates, so
task_struct___old matches the kernel’s task_struct. The local struct
declares only the fields the program reads: the loader matches fields by
name, and replaces the offsets that the local declaration gave.
On 6.18 the relocation finds task_struct but no member state. The loader
does not fail the load at once: it replaces the instruction with a call to a
helper ID that does not exist, 195896080, 0xbad2310 in hexadecimal, and
leaves the decision to the verifier. If the instruction can run, the
verifier rejects the program, and gobpfgo rewrites that line of the log, as
libbpf does, to name the relocation. The load fails with EINVAL, and the
log reads:
0: (85) call bpf_get_current_task#35 ; R0=scalar()1: <invalid CO-RE relocation>failed to resolve CO-RE relocation <byte_off> [18] struct task_struct___old.state (0:0 @ offset 0)The record names the local type, task_struct___old, its ID in the object,
18, the field, and the access path, as in the disassembly above.
If the instruction cannot run, the program loads. That is how one object
handles both layouts: bpf_core_field_exists is itself a relocation, which
the loader resolves to 1 or 0, and the verifier, seeing a constant, skips the
branch that cannot be taken, poisoned instruction included:
struct task_struct___old *old = (void *)task;__u32 state;
if (bpf_core_field_exists(old->state)) state = BPF_CORE_READ(old, state);else state = BPF_CORE_READ(task, __state);This version loads on 6.18, and also against the 5.10 BTF given as a file,
the subject of the next section. bpf_core_type_exists and
bpf_core_enum_value_exists test for a type or an enum value the same way.
A target kernel’s BTF as a file
Section titled “A target kernel’s BTF as a file”By default the loader reads the target BTF from the running kernel. On a
kernel built without BTF there is no /sys/kernel/btf/vmlinux, and a program
with CO-RE relocations fails to load. BpfObjectOpenOpts.BtfCustomPath
names a BTF file to use instead, raw BTF or an ELF file with a .BTF
section, such as one generated from the kernel’s debug information:
opts := libbpf.NewBpfObjectOpenOpts()btfPath := "/path/to/target-kernel.btf"opts.BtfCustomPath = &btfPathobj, err := bpf.OpenFile("open_uid.bpf.o", opts)The file replaces the running kernel’s BTF, modules included, for the CO-RE
relocations only. fentry targets, typed .ksyms and struct_ops maps still
resolve against the running kernel, so this chapter’s fentry program still
needs kernel BTF. The loader reads the file at load, and only when the object
has CO-RE relocations; a missing file then fails the load:
bpf_object__relocate_core: no such file or directory: failed to parse target BTF: btf__parse /tmp/missing.btf: no such file or directory: open /tmp/missing.btf: no such file or directoryThe file must describe the kernel the program runs on. Loaded on 6.18 with
the 5.10 kernel’s BTF as BtfCustomPath, this chapter’s object loads, and
bpftool shows instruction 3 as r1 = 2720, the 5.10 offset, so the program
would read the wrong field of every 6.18 task.
Inspecting the object’s types
Section titled “Inspecting the object’s types”bpftool btf dump file open_uid.bpf.o format c prints the object’s BTF as C.
From Go, Object.BTF, libbpf.BpfObjectBTF in the core, returns the
object’s parsed BTF, and the BtfDump functions print C declarations from
it. A snippet that prints every type in the object, as bpftool does:
btf := obj.BTF()d, err := libbpf.BtfDumpNew(btf, func(format string, args ...any) { fmt.Printf(format, args...)}, nil)if err != nil { return err}defer libbpf.BtfDumpFree(d)for id := 1; id < libbpf.BtfTypeCnt(btf); id++ { if err := libbpf.BtfDumpDumpType(d, uint32(id)); err != nil { return err }}BtfDumpDumpType prints a type and every type it depends on that it has not
printed yet. Type 0 is void and has no declaration. For this chapter’s
object, the output includes the whole struct task_struct and struct cred
as vmlinux.h declares them: the object’s BTF holds 424 types, because clang
writes every type the program reaches, with all its members.
BtfDumpDumpTypeData prints a value, such as a map value, as a C
initializer of its type.
Global data
Section titled “Global data”The maps chapter showed that global
variables become maps: one array map with a single element for each of the
.data, .bss and .rodata sections. A fourth section, .kconfig, holds
kconfig externs: extern variables declared with __kconfig, which
the loader fills at load, from the kernel’s configuration,
/boot/config-<release> or /proc/config.gz, and, for
LINUX_KERNEL_VERSION, from the kernel’s release. The map is read-only to
the program, so, as with .rodata, the verifier treats its values as
constants and drops the code they rule out. __weak makes an option the
configuration does not set read as 0 instead of failing the load.
extern unsigned int LINUX_KERNEL_VERSION __kconfig; // .kconfig, filled by the loaderextern bool CONFIG_BPF_LSM __kconfig __weak; // .kconfig, false when not setconst volatile __u32 min_uid = 0; // .rodata, set from Go before the load__u64 opens_seen = 0; // .bss, shared with Go after the loadFrom Go, obj.Map(".rodata") and obj.Map(".bss") find the maps by
section name. SetInitialValue replaces .rodata’s bytes before the load,
and after the load InitialValue returns .bss’s memory, which the program
updates while Go reads it:
// Before the load: min_uid is the only .rodata variable, at offset 0.rodata := obj.Map(".rodata")if err := rodata.SetInitialValue(binary.NativeEndian.AppendUint32(nil, 1000)); err != nil { return err}
// After the load and the attach: opens_seen is at offset 0 of .bss.bss := obj.Map(".bss").InitialValue()fmt.Println(binary.NativeEndian.Uint64(bss[0:8]))Checked on 6.18 with a variant of this chapter’s program that adds one to
opens_seen for each open by a user ID of at least min_uid, set to 1000,
and two opens as user 65534: opens_seen was 2, and the .kconfig map held
3f 12 06 00, the version code of 6.18.63, and 01 for CONFIG_BPF_LSM. With more than one variable in a section, each
one’s offset is in the section’s BTF, which bpftool btf dump file prints as
a DATASEC.
The example: opens per user ID
Section titled “The example: opens per user ID”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
// vmlinux.h is generated by make from the kernel's BTF and declares every// kernel type, so it replaces <linux/bpf.h> and the other kernel headers.// Its structs carry preserve_access_index, which makes clang record each// field access below as a CO-RE relocation.#include "vmlinux.h"#include <bpf_helpers.h>#include <bpf_core_read.h>#include <bpf_tracing.h>
// counts maps a user ID to the number of do_sys_openat2 calls made by// tasks running as that user.struct { __uint(type, BPF_MAP_TYPE_HASH); __uint(max_entries, 1024); __type(key, __u32); __type(value, __u64);} counts SEC(".maps");
SEC("fentry/do_sys_openat2")int BPF_PROG(count_uid, int dfd, const char *filename, struct open_how *how) { struct task_struct *task = (struct task_struct *)bpf_get_current_task(); __u64 one = 1; __u64 *count;
// task->cred->uid.val, read with bpf_probe_read_kernel at offsets the // loader takes from the running kernel's BTF. __u32 uid = BPF_CORE_READ(task, cred, uid.val);
count = bpf_map_lookup_elem(&counts, &uid); if (!count) { if (bpf_map_update_elem(&counts, &uid, &one, BPF_NOEXIST) == 0) return 0; count = bpf_map_lookup_elem(&counts, &uid); if (!count) return 0; } __atomic_fetch_add(count, 1, __ATOMIC_RELAXED); return 0;}
// bpf_get_current_task and bpf_probe_read_kernel, which BPF_CORE_READ// calls, are GPL-only helpers.char LICENSE[] SEC("license") = "GPL";The program includes vmlinux.h instead of <linux/bpf.h>, then libbpf’s
headers: bpf_helpers.h for SEC and the helpers, bpf_core_read.h for
BPF_CORE_READ, and bpf_tracing.h for BPF_PROG. With vmlinux.h, the
fentry arguments have their kernel types, including the full
struct open_how, which step04 only declared.
bpf_get_current_task() returns the current task’s address as a __u64,
which the program casts to struct task_struct *. The cast gives the
compiler a type, so BPF_CORE_READ can name cred and uid.val; to the
verifier the value stays a number, which is why the reads go through
bpf_probe_read_kernel.
cred is the task’s credentials: a struct cred with its user and
group IDs. uid is the real user ID, the one getuid(2) returns, as a
kuid_t, a struct that wraps the number in val. The program counts in a
hash map keyed by that __u32, with the insert and retry of the earlier
chapters.
The license is GPL, and it must be: bpf_get_current_task and
bpf_probe_read_kernel are GPL-only helpers.
The Go program
Section titled “The Go program”// SPDX-License-Identifier: LGPL-2.1-only
// Command step07 attaches an fentry program to do_sys_openat2 that reads// the calling task's user ID through CO-RE and counts opens per user ID. It// opens /etc/hostname three times as root and twice as user 65534, nobody,// and prints every user ID in the map with its count. 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" "syscall"
"github.com/gobpfgo/gobpfgo/bpf" "golang.org/x/sys/unix")
// nobody is the user ID of the unprivileged user nobody.const nobody = 65534
func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, "step07:", err) os.Exit(1) }}
func run() error { obj, err := bpf.OpenFile("open_uid.bpf.o", nil) if err != nil { return err } defer obj.Close()
// The load applies the CO-RE relocations against the running // kernel's BTF, then loads the program. if err := obj.Load(); err != nil { return err }
prog := obj.Program("count_uid") if prog == nil { return errors.New("no program named count_uid in the object") } link, err := prog.AttachTrace() if err != nil { return err } defer link.Destroy()
// Three opens as root, then two as user 65534, nobody. Setresuid // changes the user IDs of every thread in the process. The saved user // ID stays 0, so the process can switch back to root to read the map. if err := openHostname(3); err != nil { return err } if err := syscall.Setresuid(nobody, nobody, 0); err != nil { return err } if err := openHostname(2); err != nil { return err } if err := syscall.Setresuid(0, 0, 0); err != nil { return err }
counts := obj.Map("counts") if counts == nil { return errors.New("no map named counts in the object") }
fmt.Printf("%10s %6s\n", "UID", "OPENS") 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 } // Both the key, a __u32, and the value, a __u64, are in the // CPU's byte order. uid := binary.NativeEndian.Uint32(nextKey) fmt.Printf("%10d %6d\n", uid, binary.NativeEndian.Uint64(value)) curKey = append(curKey[:0], nextKey...) } return nil}
// openHostname opens and closes /etc/hostname n times.func openHostname(n int) error { for range n { f, err := os.Open("/etc/hostname") if err != nil { return err } if err := f.Close(); err != nil { return err } } return nil}The program opens, loads and attaches as step04 did. Object.Load applies
the CO-RE relocations, then loads the program, and prog.AttachTrace()
attaches it to the function its section names.
To give the map more than one user ID, the program opens /etc/hostname
three times as root, then changes its user IDs with
syscall.Setresuid(nobody, nobody, 0) and opens it twice as user 65534,
nobody. Setresuid sets the real, effective and saved user IDs, and Go’s
syscall applies it to every thread of the process, so the opens count as
user 65534 whichever thread makes them. The saved user ID stays 0, which
lets syscall.Setresuid(0, 0, 0) switch back to root, so the program can
read the map.
The walk is the one from the earlier chapters. Each key is 4 bytes,
binary.NativeEndian.Uint32(nextKey) turns it into the user ID, and the
program prints it as a number.
Build and run
Section titled “Build and run”-
Build the BPF objects from the
examplesdirectory. The first build generatesvmlinux.hfrom the running kernel’s BTF:Terminal window cd examplesmake -
Run the Go program as root, from the example’s directory:
Terminal window cd tutorial/step07-coresudo env PATH="$PATH" go run .
On 6.18 the output is:
UID OPENS 0 3 65534 2The 3 opens as root and the 2 as user 65534 are the Go program’s own. As in the earlier chapters, the program counts every process, so other users’ opens add lines and other root opens raise the first count; the lines come out in the hash table’s order. A user ID of 65534 also shows that the reads work: a read that failed would leave the key zeroed and count it as user 0.
The object built on 6.18, copied with a static build of the Go program to the Debian 5.10 kernel, prints the same counts there. The program needs a kernel with BTF, and on arm64 a kernel from 6.0, as fentry does.
The programs so far left their results in maps for Go to read at the end. The next chapter streams records to Go as they happen.
