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, sobpf_object__loadisBpfObjectLoad, 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,MapandLink, and the buffer readersRingBuffer,PerfBufferandUserRingBuffer. Each method calls one core function.
Each layer call forwards to one core call, which makes the system calls.
The same program on both
Section titled “The same program on both”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.
// 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}// SPDX-License-Identifier: LGPL-2.1-only
// Command core is step01 written against the libbpf core package// instead of the bpf layer. Run it as root from the step01 directory// with go run ./core.package main
import ( "encoding/binary" "errors" "fmt" "os"
"github.com/gobpfgo/gobpfgo/libbpf")
func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, "core:", err) os.Exit(1) }}
func run() error { obj, err := libbpf.BpfObjectOpenFile("open_count.bpf.o", nil) if err != nil { return err } defer libbpf.BpfObjectClose(obj)
if err := libbpf.BpfObjectLoad(obj); err != nil { return err }
prog := libbpf.BpfObjectFindProgramByName(obj, "handle_open") if prog == nil { return errors.New("no program named handle_open in the object") }
link, err := libbpf.BpfProgramAttachTracepoint(prog, "syscalls", "sys_enter_openat") if err != nil { return err } defer libbpf.BpfLinkDestroy(link)
for range 5 { f, err := os.Open("/etc/hostname") if err != nil { return err } if err := f.Close(); err != nil { return err } }
counts := libbpf.BpfObjectFindMapByName(obj, "counts") if counts == nil { return errors.New("no map named counts in the object") }
key := make([]byte, 4) value := make([]byte, 8) if err := libbpf.BpfMapLookupElem(counts, 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 common calls
Section titled “The common calls”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.
What the layer adds, and what it does not
Section titled “What the layer adds, and what it does not”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*andBtfDump*, and line information lookups,BpfProgLineInfo*; - the feature probes and name lookups, such as
LibbpfProbeBpfProgTypeandLibbpfProgTypeByName; - the print callback,
LibbpfSetPrint, and custom section handlers,LibbpfRegisterProgHandler; BpfMapCreate, which creates a map outside any object, andBpfIterCreate, which takes a link descriptor fromLink.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.
Ownership
Section titled “Ownership”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.
Which one to use
Section titled “Which one to use”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.
