Skip to content

The two layers

gobpfgo has two packages, and every program can be written with either:

  • libbpf, the core, is the port of libbpf’s C API. Each C function has a Go function with the same name in Go form, so bpf_object__load is BpfObjectLoad, and the same arguments, behavior and errnos. Objects, programs, maps and links are opaque handles passed to free functions.
  • bpf, the layer, wraps the same handles in Go types with methods: Object, Program, Map and Link, and the buffer readers RingBuffer, PerfBuffer and UserRingBuffer. Each method calls one core function.
Three stacked levels. The bpf package calls bpf.OpenFile, Object.Load, Program.AttachTracepoint, Map.Lookup and Object.Close. Each forwards to the libbpf package: BpfObjectOpenFile, BpfObjectLoad, BpfProgramAttachTracepoint, BpfMapLookupElem and BpfObjectClose. These reach the kernel as no bpf() call for the open, BPF_BTF_LOAD, BPF_MAP_CREATE and BPF_PROG_LOAD for the load, perf_event_open and BPF_LINK_CREATE for the attach, BPF_MAP_LOOKUP_ELEM for the lookup, and closing each descriptor for the close.

Each layer call forwards to one core call, which makes the system calls.

The first program has a second version in core/main.go, written against the core. It does the same steps in the same order and prints the same line. Both are built and run with the examples; from examples/tutorial/step01, run the core version with sudo env PATH="$PATH" go run ./core.

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
}

Side by side, the run functions differ only in how each step is spelled:

Step bpf layer libbpf core
Open bpf.OpenFile(path, nil) libbpf.BpfObjectOpenFile(path, nil)
Load obj.Load() libbpf.BpfObjectLoad(obj)
Find the program obj.Program("handle_open") libbpf.BpfObjectFindProgramByName(obj, "handle_open")
Attach prog.AttachTracepoint("syscalls", "sys_enter_openat") libbpf.BpfProgramAttachTracepoint(prog, "syscalls", "sys_enter_openat")
Find the map obj.Map("counts") libbpf.BpfObjectFindMapByName(obj, "counts")
Read the map counts.Lookup(key, value, 0) libbpf.BpfMapLookupElem(counts, key, value, 0)
Detach link.Destroy() libbpf.BpfLinkDestroy(link)
Close obj.Close() libbpf.BpfObjectClose(obj)

The errors are the same values too. The layer returns the core’s *libbpf.Error unchanged, with the kernel’s errno and, for a verifier rejection, the log.

The core follows libbpf’s C names, so the table also gives the C function each call ports. The C map calls take explicit key and value sizes; the Go calls take byte slices, which carry their length.

Operation bpf layer libbpf core libbpf in C
Open a file bpf.OpenFile BpfObjectOpenFile bpf_object__open_file
Open from memory bpf.OpenMem BpfObjectOpenMem bpf_object__open_mem
Load Object.Load BpfObjectLoad bpf_object__load
Find a program Object.Program BpfObjectFindProgramByName bpf_object__find_program_by_name
Find a map Object.Map BpfObjectFindMapByName bpf_object__find_map_by_name
Attach to a tracepoint Program.AttachTracepoint BpfProgramAttachTracepoint bpf_program__attach_tracepoint
Attach from the section name Program.Attach BpfProgramAttach bpf_program__attach
Look up an element Map.Lookup BpfMapLookupElem bpf_map__lookup_elem
Update an element Map.Update BpfMapUpdateElem bpf_map__update_elem
Read a ring buffer bpf.NewRingBuffer RingBufferNew ring_buffer__new
Detach and release a link Link.Destroy BpfLinkDestroy bpf_link__destroy
Close Object.Close BpfObjectClose bpf_object__close

Most layer methods name their core function in their godoc, as in “See libbpf.BpfProgramAttachTracepoint”, and the core function’s godoc describes the behavior in full.

The layer only forwards. Each method calls one core function and adds the Go name, a check that returns bpf.ErrClosed when the object was closed, and, for the buffer callbacks, drops the ctx argument that a Go closure replaces. It uses the core’s option types as they are, returns the core’s errors unchanged, and has no locking, finalizers or hidden state. A layer method behaves as the core function it forwards to, so when the behavior of a layer call is in question, the core function’s documentation answers it.

The layer forwards every core call that takes an object, program, map, link or buffer. The calls it does not forward take none of these, so you can call them from the core in code that otherwise uses the layer:

  • the static linker, BpfLinker*;
  • BTF parsing, dedup and dumps, Btf* and BtfDump*, and line information lookups, BpfProgLineInfo*;
  • the feature probes and name lookups, such as LibbpfProbeBpfProgType and LibbpfProgTypeByName;
  • the print callback, LibbpfSetPrint, and custom section handlers, LibbpfRegisterProgHandler;
  • BpfMapCreate, which creates a map outside any object, and BpfIterCreate, which takes a link descriptor from Link.FD.

The layer does not give out the core handle inside an Object, Program or Map, so an object opened with one package is used with that package throughout. Descriptors, from the FD methods, and the object’s BTF, from Object.BTF, are where the two meet.

An Object owns the core object and, through it, every map and program descriptor it creates; its Program and Map values are views that own nothing and stop working when the object is closed, when their methods with an error result return bpf.ErrClosed. A Link is owned by the caller: closing the object neither detaches nor destroys it, and the kernel keeps the program attached until you call Destroy. A RingBuffer, PerfBuffer or UserRingBuffer is owned by the caller in the same way: it owns its memory mappings and epoll descriptor, while the map stays the object’s, and since a PerfBuffer’s Close removes its entries from the map, close it before the object. An Object and its children are not safe for concurrent use. The core has the same owners, without the closed check: after BpfObjectClose, do not use the object’s program and map handles, as in libbpf.

Use the bpf layer for application code. It reads as Go, keeps the lifetimes visible, and adds one function call and a closed check per operation.

Use the libbpf core when you need a call the layer does not forward, or exact libbpf semantics: when you port a C loader line by line, compare behavior with libbpf, or depend on libbpf’s handle-based API. The calls the layer does not forward work next to layer code, so needing one of them does not by itself mean writing the whole program against the core.

The rest of this guide uses the layer and names the core call where it helps.