Skip to content

API reference

gobpfgo has two packages. This page lists, for each job a tool does, the call in each package, and then the parts every call shares: the error type, the option structs, the build constraints and the types. The godocs hold the full contract of each call, its errnos included.

Package Import path What it is
The layer github.com/gobpfgo/gobpfgo/bpf Go types with methods: Object, Program, Map and Link, and the buffer readers RingBuffer, PerfBuffer and UserRingBuffer. Each method forwards one core call.
The core github.com/gobpfgo/gobpfgo/libbpf The port of libbpf’s C API: free functions over opaque handles, with libbpf’s names in Go form, so bpf_object__load is BpfObjectLoad, and libbpf’s behavior and errnos.

Use the layer for application code. Use the core for a call the layer does not forward, or when you need exact libbpf behavior, such as when you port a C loader line by line. The calls only the core has take no object, program, map, link or buffer, so a program written against the layer calls them directly; the layer does not give out the core handle inside its types, so an object opened with one package stays with that package. The two layers shows the same program on both.

The source of each package is on GitHub, in bpf/ and libbpf/. The module has no page on pkg.go.dev, so read the godocs locally with go doc, from the gobpfgo checkout or from a module that requires gobpfgo:

Terminal window
go doc github.com/gobpfgo/gobpfgo/bpf
go doc github.com/gobpfgo/gobpfgo/bpf Program.AttachKprobe
go doc github.com/gobpfgo/gobpfgo/libbpf BpfObjectOpenOpts
go doc -all github.com/gobpfgo/gobpfgo/libbpf

Most layer methods end their godoc with the core function they forward to, as in “See libbpf.BpfProgramAttachTracepoint”, and that function’s godoc describes the behavior in full.

The layer column names methods by their type, as Object.Load for obj.Load(). The core column drops the libbpf. prefix. A row marked core only has no layer method; call the core function from layer code.

Job bpf layer libbpf core Note
Open an object file bpf.OpenFile BpfObjectOpenFile Parses the ELF and BTF and makes no bpf() call. opts may be nil.
Open an object from memory bpf.OpenMem BpfObjectOpenMem The object is named mem unless ObjectName is set.
Prepare Object.Prepare BpfObjectPrepare Creates the maps and relocates the code, and loads no program.
Load Object.Load BpfObjectLoad Prepares, if Prepare did not, then loads every AUTO program. An object loads once.
Close Object.Close BpfObjectClose Closes the map, program and BTF descriptors. It does not detach links.
Name the object Object.Name BpfObjectName
Find a program Object.Program BpfObjectFindProgramByName nil when there is none.
List the programs Object.Programs BpfObjectNextProgram In ELF order, without subprograms.
Find a map Object.Map BpfObjectFindMapByName nil when there is none.
List the maps Object.Maps BpfObjectNextMap The .maps definitions, then the internal data, .kconfig and per-CPU maps, then the struct_ops maps.

Every attach returns a link that the caller owns; see Links. The oldest kernels are from Kernel support.

Job bpf layer libbpf core Note
Attach from the section name Program.Attach BpfProgramAttach For the tracing sections, such as kprobe/, ksyscall/, uprobe/, usdt/, tracepoint/, fentry/, lsm/, iter/, freplace/ and their multi forms, and through a custom handler’s attach callback. The godoc lists them.
Tracepoint Program.AttachTracepoint, Program.AttachTracepointOpts BpfProgramAttachTracepoint, BpfProgramAttachTracepointOpts BpfTracepointOpts carries a BPF cookie.
Raw tracepoint Program.AttachRawTracepoint, Program.AttachRawTracepointOpts BpfProgramAttachRawTracepoint, BpfProgramAttachRawTracepointOpts
kprobe, kretprobe Program.AttachKprobe, Program.AttachKprobeOpts BpfProgramAttachKprobe, BpfProgramAttachKprobeOpts BpfKprobeOpts sets the return probe, an offset, a cookie and the attach mode.
kprobe multi and session Program.AttachKprobeMulti BpfProgramAttachKprobeMulti A pattern, symbols or addresses in BpfKprobeMultiOpts. Linux 5.18 on amd64, 6.14 on arm64; sessions 6.10 and 6.14.
ksyscall Program.AttachKsyscall BpfProgramAttachKsyscall A kprobe on the system call’s kernel entry, such as getpid.
uprobe, uretprobe Program.AttachUprobe, Program.AttachUprobeOpts BpfProgramAttachUprobe, BpfProgramAttachUprobeOpts A pid of -1 selects every process. BpfUprobeOpts.FuncName resolves a symbol.
uprobe multi and session Program.AttachUprobeMulti BpfProgramAttachUprobeMulti Linux 6.6; sessions 6.13.
USDT Program.AttachUsdt BpfProgramAttachUsdt The BPF program includes libbpf’s usdt.bpf.h. The link has no descriptor.
fentry, fexit, fmod_ret, tp_btf Program.AttachTrace, Program.AttachTraceOpts BpfProgramAttachTrace, BpfProgramAttachTraceOpts The target is resolved at load. Linux 5.10 on amd64, 6.0 on arm64.
LSM Program.AttachLsm BpfProgramAttachLsm Needs bpf in the boot lsm= list.
Tracing multi Program.AttachTracingMulti BpfProgramAttachTracingMulti fentry.multi, fexit.multi and fsession.multi, by pattern or by BTF IDs. Linux 7.2.
freplace Program.AttachFreplace BpfProgramAttachFreplace Replaces a function of the loaded program targetFD.
iter Program.AttachIter BpfProgramAttachIter Then core only BpfIterCreate(link.FD()) returns a descriptor; reading it runs the iterator.
XDP Program.AttachXDP BpfProgramAttachXDP By interface index.
tcx Program.AttachTcx BpfProgramAttachTcx Linux 6.6. BpfTcxOpts places the program among others.
netkit Program.AttachNetkit BpfProgramAttachNetkit Linux 6.7.
netfilter Program.AttachNetfilter BpfProgramAttachNetfilter Linux 6.4. The hook is in BpfNetfilterOpts.
cgroup Program.AttachCgroup, Program.AttachCgroupOpts BpfProgramAttachCgroup, BpfProgramAttachCgroupOpts BpfCgroupOpts placement and revisions need Linux 6.17.
Network namespace Program.AttachNetns BpfProgramAttachNetns Such as a flow_dissector program.
sockmap Program.AttachSockmap BpfProgramAttachSockmap By map descriptor. Linux 6.10.
Perf event Program.AttachPerfEvent, Program.AttachPerfEventOpts BpfProgramAttachPerfEvent, BpfProgramAttachPerfEventOpts To a perf event you opened.
struct_ops map Map.AttachStructOps BpfMapAttachStructOps Registers the map; a map in .struct_ops.link gets a BPF link, from Linux 6.4.
struct_ops map on a cgroup Map.AttachCgroupOpts BpfMapAttachCgroupOpts Linux 7.4, for a struct_ops type such as bpf_tcp_ops.
Job bpf layer libbpf core Note
Detach and release Link.Destroy BpfLinkDestroy Idempotent. A pinned link stays on bpffs.
Detach now, release later Link.Detach BpfLinkDetach Detaches and closes the descriptors in one call; see Differences.
Release without detaching Link.Disconnect, then Link.Destroy BpfLinkDisconnect For an attachment that must outlive the link, such as a pinned one.
Pin, unpin Link.Pin, Link.Unpin BpfLinkPin, BpfLinkUnpin Only a BPF link, with a descriptor of its own, can be pinned.
Open a pinned link bpf.OpenLink BpfLinkOpen
Replace the program Link.UpdateProgram BpfLinkUpdateProgram
Replace a struct_ops link’s map Link.UpdateMap BpfLinkUpdateMap Linux 6.4.
Descriptor and pin path Link.FD, Link.PinPath BpfLinkFD, BpfLinkPinPath FD is -1 after Detach or Destroy.
Job bpf layer libbpf core Note
Skip a program at load Program.SetAutoload(false) BpfProgramSetAutoload Sets the DISABLED strategy, as a ? section prefix does.
Load a MANUAL program Program.SetLoadStrategy, then Program.Load BpfProgramSetLoadStrategy, BpfProgramLoad BPF_PROG_LOAD_STRATEGY_MANUAL, or a ! section prefix. Load works after Object.Prepare or Object.Load.
Clone Program.Clone BpfProgramClone Loads another kernel instance and returns its descriptor, which the caller closes with unix.Close.
Set the type or the attach type Program.SetType, Program.SetExpectedAttachType BpfProgramSetType, BpfProgramSetExpectedAttachType Before the load.
Set the load flags Program.SetFlags, Program.AddFlags, Program.ClearFlags BpfProgramSetFlags, BpfProgramAddFlags, BpfProgramClearFlags BPF_F_* flags, such as BPF_F_SLEEPABLE.
Set the attach target Program.SetAttachTarget BpfProgramSetAttachTarget A function of a loaded program, or of the kernel with descriptor 0.
Replace the instructions Program.SetInsns BpfProgramSetInsns Insns and InsnCnt read them.
Set the verifier log Program.SetLogLevel, Program.SetLogBuf BpfProgramSetLogLevel, BpfProgramSetLogBuf See Errors.
Read the attributes Name, SectionName, Type, ExpectedAttachType, Flags, FD, Autoload, LoadStrategy, LogLevel, LogBuf, Autoattach BpfProgramName, BpfProgramTypeOf and the other BpfProgram* getters FD is -1 before the load and after Object.Close.
Read the kernel’s information Program.Info BpfProgramInfo Returns a *libbpf.BpfProgInfo.
Look up line information core only BpfProgLineInfoNew, BpfProgLineInfoLfind, BpfProgLineInfoLfindAddrFunc, BpfProgLineInfoFree From the BpfProgInfo that Program.Info returns.
Job bpf layer libbpf core Note
Look up an element Map.Lookup BpfMapLookupElem The key and value slices must be KeySize and ValueSize bytes; a per-CPU value holds one slot per possible CPU. A missing key is ENOENT.
Update an element Map.Update BpfMapUpdateElem Flags BPF_ANY, BPF_NOEXIST, BPF_EXIST.
Delete an element Map.Delete BpfMapDeleteElem
Look up and delete Map.LookupAndDelete BpfMapLookupAndDeleteElem Pops a queue or stack map.
Walk the keys Map.NextKey BpfMapGetNextKey An empty current key gives the first key; ENOENT follows the last.
Read or set global data Map.InitialValue, Map.SetInitialValue BpfMapInitialValue, BpfMapSetInitialValue Fetch InitialValue again after the load: it then returns the live map.
Size and place a map before the load Map.SetMaxEntries, Map.SetNumaNode, Map.SetMapExtra BpfMapSetMaxEntries, BpfMapSetNumaNode, BpfMapSetMapExtra EBUSY once Prepare or Load has run.
Skip creating a map Map.SetAutocreate(false) BpfMapSetAutocreate
Use an existing kernel map Map.ReuseFD BpfMapReuseFD Before the load. The caller keeps the descriptor.
Inner maps Map.InnerMap, Map.SetInnerMapFD BpfMapInnerMap, BpfMapSetInnerMapFD The inner map’s definition can be changed until the load.
Mark a struct_ops map for attach Map.SetAutoattach BpfMapSetAutoattach
Read the attributes Name, Type, KeySize, ValueSize, MaxEntries, Flags, NumaNode, MapExtra, BtfKeyTypeID, BtfValueTypeID, IsInternal, FD, Autocreate, Autoattach BpfMapName, BpfMapTypeOf, BpfMapMapFlags and the other BpfMap* getters
Create a map outside an object core only BpfMapCreate Options from NewBpfMapCreateOpts. The caller closes the descriptor.
Job bpf layer libbpf core Note
Pin or unpin a map Map.Pin, Map.Unpin BpfMapPin, BpfMapUnpin A nil path uses the stored one, from Map.SetPinPath or LIBBPF_PIN_BY_NAME.
Read a map’s pin Map.PinPath, Map.IsPinned BpfMapPinPath, BpfMapIsPinned
Pin or unpin every map Object.PinMaps, Object.UnpinMaps BpfObjectPinMaps, BpfObjectUnpinMaps Under a directory, one pin per map, or with nil at each map’s stored path.
Pin or unpin a program Program.Pin, Program.Unpin BpfProgramPin, BpfProgramUnpin
Pin or unpin every program Object.PinPrograms, Object.UnpinPrograms BpfObjectPinPrograms, BpfObjectUnpinPrograms
Pin or unpin everything Object.Pin, Object.Unpin BpfObjectPin, BpfObjectUnpin Every map and program. Links pin one at a time.

The production chapter covers pin paths and reusing a pinned map.

Job bpf layer libbpf core Note
Read a ring buffer bpf.NewRingBuffer, then RingBuffer.Add, Poll, Consume, ConsumeN, EpollFD, Close RingBufferNew, RingBufferAdd, RingBufferPoll, RingBufferConsume, RingBufferConsumeN, RingBufferEpollFD, RingBufferFree One reader can serve several ring buffer maps.
Read a perf buffer bpf.NewPerfBuffer, then PerfBuffer.Poll, Consume, ConsumeBuffer, BufferCnt, BufferFD, Buffer, EpollFD, Close PerfBufferNew, PerfBufferPoll and the other PerfBuffer* functions, PerfBufferFree Close it before the object.
Write a user ring buffer bpf.NewUserRingBuffer, then UserRingBuffer.Reserve, ReserveBlocking, Submit, Discard, Close UserRingBufferNew, UserRingBufferReserve, UserRingBufferReserveBlocking, UserRingBufferSubmit, UserRingBufferDiscard, UserRingBufferFree Linux 6.1.

The layer’s callbacks take no ctx argument, which the core’s do: a Go closure carries the state instead. The core functions take the map descriptor, so a layer reader is made from a *bpf.Map.

Job bpf layer libbpf core Note
The object’s BTF Object.BTF BpfObjectBTF Borrowed from the object: do not free it or use it after Close.
Parse a BTF file core only BtfParse Raw BTF, such as /sys/kernel/btf/vmlinux, or an ELF object with a .BTF section. Release with BtfFree.
Parse BTF bytes core only BtfNew
Count the types core only BtfTypeCnt
Get the raw bytes core only BtfRawData The table’s own slice: do not modify it.
Deduplicate core only BtfDedup In place. BTF with a base is refused with EOPNOTSUPP.
Dump types as C core only BtfDumpNew, BtfDumpDumpType, BtfDumpEmitTypeDecl, BtfDumpFree Output goes through a printf-style callback.
Dump typed data core only BtfDumpDumpTypeData Formats a value’s bytes by its BTF type.
Job bpf layer libbpf core Note
Link BPF objects into one core only BpfLinkerNew or BpfLinkerNewFD, BpfLinkerAddFile, BpfLinkerAddBuf, BpfLinkerAddFD, BpfLinkerFinalize, BpfLinkerFree The output is an object bpf.OpenFile opens. Little-endian input only.
Job bpf layer libbpf core Note
Probe a program type core only LibbpfProbeBpfProgType Loads a minimal program; run it with the privileges of the real load.
Probe a map type core only LibbpfProbeBpfMapType Creates a small map.
Probe a helper core only LibbpfProbeBpfHelper EOPNOTSUPP for program types that need an attach target.
Section name to program type core only LibbpfProgTypeByName The program and expected attach types a section opens with; ESRCH when nothing matches.
Section name to attach type core only LibbpfAttachTypeByName For BPF_PROG_ATTACH, as libbpf’s legacy lookup.
Count the possible CPUs core only LibbpfNumPossibleCpus Per-CPU map values hold one slot per possible CPU.
Route library messages core only LibbpfSetPrint Process-wide; nil silences the library.
Register a custom section handler core only LibbpfRegisterProgHandler, LibbpfUnregisterProgHandler Matches section names before libbpf’s table, with setup, prepare-load and attach callbacks in LibbpfProgHandlerOpts.

Every failure of the core is a *libbpf.Error, and the layer returns it unchanged. The layer adds one error of its own, bpf.ErrClosed, for a method with an error result called after its Object was closed. The fields of libbpf.Error are:

Field Type Holds
Op string The operation that failed, named as libbpf names it, such as bpf_prog_load or bpf_program__attach_tracepoint.
Errno syscall.Errno The errno, from the kernel or as libbpf would return it.
Path string The file involved, when there is one, such as the object bpf.OpenFile could not read.
Log string The message libbpf would print with the failure, and for a program the verifier refused, the verifier’s log.

Error() joins the fields into one line, and Unwrap returns Errno, so errors.Is(err, unix.ENOENT) tests the errno with the constants of golang.org/x/sys/unix or syscall, and errors.As with a *libbpf.Error target gives the fields. The tracepoints chapter ends its map walk on errors.Is(err, unix.ENOENT). Common errnos are EPERM for missing privilege, EACCES for a program the verifier proved unsafe, EINVAL for an argument or program the kernel or loader cannot accept, and EOPNOTSUPP or ENOTSUPP (524) for a feature the running kernel lacks.

Where the verifier log is kept. By default a program load asks for no log, and when the kernel refuses the program the loader loads it again at level 1 into a buffer of its own, which starts at 16 MiB and doubles until the log fits; the log is then in the error’s Log. To keep the log of loads that succeed too, set a level and, if you want, a buffer:

  • BpfObjectOpenOpts.KernelLogLevel sets the level of the object’s BTF load and the starting level of every program; Program.SetLogLevel changes one program’s.
  • BpfObjectOpenOpts.KernelLogBuf and KernelLogSize give the kernel a buffer of yours for those loads, and Program.SetLogBuf gives one program its own, which Program.LogBuf returns. Each load overwrites the buffer. The kernel fails a load whose log does not fit a buffer of yours with ENOSPC, even for a program it accepted.

Messages where libbpf warns and carries on go to the print function that LibbpfSetPrint sets, and to standard error by default. The production chapter shows a verifier log in an error and a print function.

The layer uses the core’s option types as they are: bpf.OpenFile takes a *libbpf.BpfObjectOpenOpts, Program.AttachKprobeOpts a *libbpf.BpfKprobeOpts, and so on. Code written against the layer imports libbpf for these types, for constants such as libbpf.BPF_ANY and libbpf.BPF_MAP_TYPE_RINGBUF, and for *libbpf.Error. A nil options pointer means the defaults.

The options of bpf.OpenFile, bpf.OpenMem and their core functions. The zero value is the default, and libbpf.NewBpfObjectOpenOpts returns one with its layout size set.

Field Effect
PinRootPath The directory under which a map declared with LIBBPF_PIN_BY_NAME gets its pin path, <PinRootPath>/<map name>. /sys/fs/bpf when nil. The load reuses a map pinned there, or pins the one it creates.
Kconfig Extra kernel configuration text, in the /boot/config format, for the CONFIG_ externs of .kconfig. It is read before the system’s configuration, and an extern takes the first value it sees.
BtfCustomPath A BTF file, raw or an ELF object with .BTF, used as the target of the CO-RE relocations instead of the running kernel’s BTF. Attach targets, typed .ksyms and struct_ops types still resolve against the running kernel.
BtfModuleAllowlist The kernel modules whose BTF the load may read: nil allows every module, an empty slice that is not nil allows none, and a list allows the modules it names.
RelaxedMaps Ignore the members of a .maps definition the loader does not know. Without it the open refuses an unknown member with ENOTSUP.
KernelLogBuf, KernelLogSize A buffer for the kernel’s log of the BTF load and of the program loads, and how much of it the kernel may write. The slice is kept, not copied.
KernelLogLevel The log level of the BTF load and the starting log level of every program. 0 asks for a log only after a failure.
ObjectName The object’s name, instead of the file name up to its first dot.
BpfTokenPath A bpffs mount from which to derive a BPF token.

Program.Clone takes a *libbpf.BpfProgLoadOpts, also named libbpf.BpfProgramCloneOpts, whose nonzero fields replace the program’s own settings for the clone. A custom section handler’s prepare-load callback receives one filled with what the load is about to send. Its fields are AttachProgFD, ProgFlags, ProgIfindex, KernVersion, ExpectedAttachType, AttachBtfID, AttachBtfObjFD, FdArray, FdArrayCnt, and the log’s LogLevel, LogBuf and LogSize. It has no BPF token, program BTF or function and line records, unlike libbpf’s bpf_prog_load_opts; Differences from libbpf gives the reason.

Struct Used by Fields
BpfTracepointOpts AttachTracepointOpts BpfCookie
BpfRawTracepointOpts AttachRawTracepointOpts Cookie
BpfKprobeOpts AttachKprobeOpts Retprobe, Offset, BpfCookie, AttachMode
BpfKprobeMultiOpts AttachKprobeMulti Pattern, Symbols, Addrs, Cookies, Retprobe, Session, UniqueMatch
BpfKsyscallOpts AttachKsyscall BpfCookie, Retprobe
BpfUprobeOpts AttachUprobeOpts Retprobe, RefCtrOffset, FuncName, BpfCookie, AttachMode
BpfUprobeMultiOpts AttachUprobeMulti Syms, Offsets, RefCtrOffsets, Cookies, Retprobe, Session
BpfUsdtOpts AttachUsdt UsdtCookie
BpfTraceOpts AttachTraceOpts BpfCookie
BpfTracingMultiOpts AttachTracingMulti IDs, Cookies
BpfIterOpts AttachIter LinkInfo
BpfTcxOpts AttachTcx Flags, RelativeFD, RelativeID, ExpectedRevision
BpfNetkitOpts AttachNetkit Flags, RelativeFD, RelativeID, ExpectedRevision
BpfNetfilterOpts AttachNetfilter Pf, Hooknum, Priority, Flags
BpfCgroupOpts Program.AttachCgroupOpts, Map.AttachCgroupOpts Flags, RelativeFD, RelativeID, ExpectedRevision
BpfPerfEventOpts AttachPerfEventOpts BpfCookie, ForceIoctlAttach, DontEnable
PerfBufferOpts NewPerfBuffer SamplePeriod

AttachMode is a libbpf.ProbeAttachMode: ProbeAttachModeDefault, ProbeAttachModeLegacy, ProbeAttachModePerf or ProbeAttachModeLink, as the kprobes chapter describes. A BPF cookie needs a perf link, from Linux 5.15.

  • Linux on amd64 or arm64. The packages’ files carry //go:build linux && (amd64 || arm64). For another GOOS or GOARCH, the build fails with build constraints exclude all Go files.
  • Go 1.27 or newer, as the module’s go.mod requires.
  • No cgo. CGO_ENABLED=0 go build builds a static binary, and cross builds between amd64 and arm64 need no C toolchain. The only dependency is golang.org/x/sys.
  • No unsafe. No package of the module imports it, which CI checks. Memory the kernel shares, such as a ring buffer or a global data map, reaches Go as a byte slice from mmap(2).

The layer has four types and three buffer readers:

Type Made by Released by Owns
Object bpf.OpenFile, bpf.OpenMem Object.Close The core object and, through it, the map, program and BTF descriptors.
Program Object.Program, Object.Programs its Object Nothing: a view into the object.
Map Object.Map, Object.Maps, Map.InnerMap its Object Nothing: a view into the object.
Link the Program attach methods, Map.AttachStructOps, Map.AttachCgroupOpts, bpf.OpenLink Link.Destroy The core link. It is independent of the object: closing the object does not detach it.
RingBuffer bpf.NewRingBuffer RingBuffer.Close Its mappings of the rings and its epoll descriptor.
PerfBuffer bpf.NewPerfBuffer PerfBuffer.Close, before the object’s Close Its perf events, their mappings and its epoll descriptor.
UserRingBuffer bpf.NewUserRingBuffer UserRingBuffer.Close Its mapping of the ring and its epoll descriptor.

After Object.Close, the methods of its Program and Map values that return an error return bpf.ErrClosed, and their accessors return a zero value, -1 for a descriptor. An Object and its children are not safe for concurrent use. The layer has no locking, finalizers or hidden state.

The core’s handles are BpfObject, BpfProgram, BpfMap and BpfLink, the readers RingBuffer, PerfBuffer and UserRingBuffer, and, for the calls only the core has, Btf, BtfDump, BpfLinker and BpfProgLineInfo. They have the same owners as in libbpf: after BpfObjectClose, do not use the object’s program and map handles.