How libbpfgo works: Core Concepts
mainlibbpfgo abstracts C technicalities into idiomatic Go patterns: it translates low-level return codes into Go error types, organizes functionality around Go structs, and uses Go channels for event consumption.
A typical workflow for using the library is:
- Compile: Compile your BPF program into an object file.
- Initialize Module: Create a
Modulestruct representing the unit of BPF functionality around your compiled object file. - Load Programs: Use the
BPFProgstruct to load BPF programs from the object file. - Attach: Attach
BPFProgto system facilities (e.g., "raw tracepoints" or "kprobes") using its associated functions. - Manage Maps: Use the
BPFMapstruct and its methods to instantiate and manipulate BPF Maps. - Handle Events: Use the
RingBufferstruct and its associated objects to communicate events from your BPF program to userspace via channels.
// initializing
import bpf "github.com/aquasecurity/libbpfgo"
...
bpfModule := bpf.NewModuleFromFile(bpfObjectPath)
bpfModule.BPFLoadObject()
// maps
mymap, _ := bpfModule.GetMap("mymap")
mymap.Update(key, value)
// ring buffer
rb, _ := bpfModule.InitRingBuffer("events", eventsChannel, buffSize)
rb.Poll(300)
e := <-eventsChannel