bpfload

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 10 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package bpfload loads Linux BPF programs and opens pinned BPF maps.

Programs are raw eight-byte BPF instructions, not ELF containers. Loading requires the privileges and kernel support appropriate to the program type. This package implements upstream Linux BPF commands; it does not implement vendor GPU execution extensions. Descriptors returned by this package must be closed by their owner.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrClosed = errors.New("bpf: closed descriptor")
View Source
var ErrUnsupported = errors.New("bpf: unsupported platform")

Functions

func OpenMap

func OpenMap(path string, readOnly bool) (*Object, MapInfo, error)

OpenMap opens a pinned map read-only when readOnly is true, and verifies that the object is a map before returning its owned descriptor.

Types

type BTF

type BTF struct {
	// contains filtered or unexported fields
}

BTF contains validated raw BTF type records. Discovery of a function or a structure is metadata only; upstream attachment admission remains separate.

func ParseBTF

func ParseBTF(data []byte) (*BTF, error)

ParseBTF parses a bounded raw BTF blob in either byte order. It validates record boundaries, string offsets and type references, and rejects kinds it does not understand. ELF containers must be extracted before calling it.

func (*BTF) Find

func (b *BTF) Find(name string, kind uint8) []BTFType

Find returns all types with an exact name and kind, preserving duplicates. Callers must reject ambiguity rather than selecting an arbitrary match.

func (*BTF) Type

func (b *BTF) Type(id uint32) (BTFType, bool)

Type returns the record with id, or false for void (0) or unknown IDs.

func (*BTF) Types

func (b *BTF) Types() []BTFType

Types returns copies of all type records, in ID order.

type BTFMember

type BTFMember struct {
	Name         string
	Type         uint32
	BitOffset    uint32
	BitfieldSize uint8
}

BTFMember describes a struct/union field, function parameter, or datasec entry. BitOffset and BitfieldSize apply only to struct/union members.

type BTFType

type BTFType struct {
	ArrayElement, ArrayIndex, ArrayCount uint32
	ID                                   uint32
	Name                                 string
	Kind                                 uint8
	KindFlag                             bool
	SizeOrType                           uint32
	Members                              []BTFMember
}

BTFType describes one raw BTF type. SizeOrType is interpreted according to Kind (the upstream BTF_KIND identifier). BTF names do not prove registration as struct_ops or kfuncs, and do not authorize calls from a BPF program.

type LoadError

type LoadError struct {
	Err error
	Log string
	// Attempts is the number of BPF_PROG_LOAD calls Load made, including
	// those retried after EAGAIN.
	Attempts int
}

LoadError retains the kernel verifier output when loading fails.

func (*LoadError) Error

func (e *LoadError) Error() string

func (*LoadError) Unwrap

func (e *LoadError) Unwrap() error

type MapInfo

type MapInfo struct {
	BTFID, BTFKeyTypeID, BTFValueTypeID, BTFVmlinuxValueTypeID uint32
	Type, ID, KeySize, ValueSize, MaxEntries, Flags            uint32
	Name                                                       string
}

MapInfo is the stable leading portion of Linux bpf_map_info.

func InspectMap

func InspectMap(fd int) (MapInfo, error)

InspectMap queries a borrowed map descriptor. The caller must keep the descriptor open until this call returns. It does not take ownership.

type MapSpec

type MapSpec struct {
	Type, KeySize, ValueSize, MaxEntries, Flags uint32
	Name                                        string
}

MapSpec describes an ordinary fixed-size Linux BPF map. Type must be hash (1), array (2), LRU hash (9), or LPM trie (11). Other layouts are refused.

type Object

type Object struct {
	// contains filtered or unexported fields
}

Object owns a kernel descriptor. Its zero value is closed. Close may be called repeatedly and is serialized with map operations and inspection.

func CreateMap

func CreateMap(s MapSpec) (*Object, error)

CreateMap creates a fixed-size map with an owned descriptor. Kernel size, flag, privilege, and resource-limit refusals are returned without retry.

func CreateRingMap

func CreateRingMap(capacity int) (*Object, error)

CreateRingMap creates a BPF ring-buffer map. capacity must be a power of two and a multiple of the system page size. The map has no keys or values.

func CreateStackMap

func CreateStackMap(capacity, depth int) (*Object, error)

CreateStackMap creates a bounded user-stack trace map. Capturing stack IDs must avoid BPF_F_REUSE_STACKID and BPF_F_FAST_STACK_CMP when stable frame ownership is required. Lookup returns depth uint64 addresses, padded by zero.

func CreateTaskStorage

func CreateTaskStorage() (object *Object, err error)

CreateTaskStorage creates a private PID-fd-keyed BPF_MAP_TYPE_TASK_STORAGE map with u64 values and mandatory local BTF. Entries follow task lifetime; MaxEntries is zero as required by Linux. Callers must bound insertions. Unsupported kernels and privilege refusals are returned without fallback.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/ebpfhost/bpfload"
)

func main() {
	// Creation requires kernel BPF privileges; entries must be bounded by the
	// owner. The function returns an owned map descriptor on supported kernels.
	create := bpfload.CreateTaskStorage
	fmt.Println(create != nil)
}
Output:
true

func Load

func Load(spec ProgramSpec) (*Object, string, error)

Load loads a program and returns its owned descriptor and verifier log. It does not attach the program. The verifier abandons a load with EAGAIN when a signal is pending, which Go's runtime preemption makes routine, so Load retries EAGAIN, up to 4 attempts in all; it returns the last EAGAIN after that. Every other refusal is returned without retry.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/ebpfhost/bpfload"
)

func main() {
	// Invalid programs are rejected before attempting a privileged syscall.
	_, _, err := bpfload.Load(bpfload.ProgramSpec{})
	fmt.Println(err)
}
Output:
bpf: missing program type

func LoadBTF

func LoadBTF(data []byte, logSize int) (*Object, string, error)

LoadBTF asks the kernel to validate and load a raw BTF blob. ELF extraction is the caller's responsibility. Successful loading is not GPU qualification.

func (*Object) Attempts

func (o *Object) Attempts() int

Attempts reports how many BPF_PROG_LOAD calls Load made to create o, including those retried after EAGAIN. It is zero for objects not created by Load, and stays valid after Close.

func (*Object) Close

func (o *Object) Close() error

func (*Object) Delete

func (o *Object) Delete(key []byte) error

Delete removes a key from an ordinary fixed-size map. Missing keys return an error wrapping syscall.ENOENT. It does not remove pinned objects.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/ebpfhost/bpfload"
)

func main() {
	// Map operations require a live descriptor on a supported platform.
	var object bpfload.Object
	fmt.Println(object.Delete(make([]byte, 8)) != nil)
}
Output:
true

func (*Object) DeleteTaskStorage

func (o *Object) DeleteTaskStorage(pidfd int) error

DeleteTaskStorage removes the task selected by pidfd. A dead task or absent entry returns an error wrapping syscall.ENOENT; ownership is unchanged.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/ebpfhost/bpfload"
)

func main() {
	var object bpfload.Object
	fmt.Println(object.DeleteTaskStorage(-1) != nil)
}
Output:
true

func (*Object) File

func (o *Object) File() (*os.File, error)

File duplicates the object's descriptor with close-on-exec set. The caller owns the returned file; closing either handle does not invalidate the other.

func (*Object) InsertTaskStorage

func (o *Object) InsertTaskStorage(pidfd int, cookie uint64) error

InsertTaskStorage inserts a nonzero cookie using a pidfd, never a numeric PID. The caller retains descriptor ownership. An existing task entry is refused with BPF_NOEXIST, including through another pidfd for the same task.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/ebpfhost/bpfload"
)

func main() {
	var object bpfload.Object
	fmt.Println(object.InsertTaskStorage(-1, 0) != nil)
}
Output:
true

func (*Object) Lookup

func (o *Object) Lookup(key, value []byte) error

Lookup reads a fixed-size map value. key and value must exactly match the kernel sizes. Per-CPU maps are refused because values require CPU padding.

func (*Object) LookupTaskStorage

func (o *Object) LookupTaskStorage(pidfd int) (uint64, error)

LookupTaskStorage reads the cookie for a live task selected by pidfd. It reads map authorization state only, not user process memory. Missing task storage or an exited task returns an error wrapping syscall.ENOENT. The caller retains descriptor ownership.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/ebpfhost/bpfload"
)

func main() {
	var object bpfload.Object
	_, err := object.LookupTaskStorage(-1)
	fmt.Println(err != nil)
}
Output:
true

func (*Object) MapInfo

func (o *Object) MapInfo() (MapInfo, error)

MapInfo queries the kernel for map metadata. The descriptor must refer to a map; kernel rejection is returned rather than inferred from a pin name.

func (*Object) NextKey

func (o *Object) NextKey(key, next []byte) error

NextKey copies the next key in kernel iteration order. A nil key starts iteration. The result is not a snapshot; concurrent changes can restart iteration. End of iteration returns an error wrapping syscall.ENOENT.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/ebpfhost/bpfload"
)

func main() {
	// A nil current key starts iteration on a live map descriptor.
	var object bpfload.Object
	next := make([]byte, 8)
	fmt.Println(object.NextKey(nil, next) != nil)
}
Output:
true

func (*Object) Pin

func (o *Object) Pin(path string) error

Pin gives the object a persistent bpffs path. It never replaces an existing pin. The caller owns removal of the path; Close only closes this descriptor.

func (*Object) Update

func (o *Object) Update(key, value []byte, flags uint64) error

Update writes a fixed-size map value. flags uses Linux BPF_ANY (0), BPF_NOEXIST (1), or BPF_EXIST (2).

type ProgramSpec

type ProgramSpec struct {
	Type               uint32
	ExpectedAttachType uint32
	Instructions       []byte
	License            string
	// LogSize is bounded to 16 MiB; zero requests 64 KiB.
	LogSize int
}

ProgramSpec describes a raw Linux BPF program. Type and ExpectedAttachType use the upstream linux/bpf.h numeric identifiers. Zero ExpectedAttachType leaves the attach type unspecified. License defaults to GPL.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL