...

Package btf

import "github.com/cilium/ebpf/btf"
Overview
Index
Examples

Overview ▾

Package btf handles data encoded according to the BPF Type Format.

The canonical documentation lives in the Linux kernel repository and is available at https://www.kernel.org/doc/html/latest/bpf/btf.html

Index ▾

Variables
func LoadSpecAndExtInfosFromReader(rd io.ReaderAt) (*Spec, *ExtInfos, error)
func MarshalExtInfos(insns asm.Instructions, typeID func(Type) (TypeID, error)) (funcInfos, lineInfos []byte, _ error)
func Sizeof(typ Type) (int, error)
type Array
    func (arr *Array) Format(fs fmt.State, verb rune)
    func (arr *Array) TypeName() string
type Bits
    func (b Bits) Bytes() uint32
type COREFixup
    func CORERelocate(local, target *Spec, relos []*CORERelocation) ([]COREFixup, error)
    func (f *COREFixup) Apply(ins *asm.Instruction) error
    func (f *COREFixup) String() string
type CORERelocation
    func CORERelocationMetadata(ins *asm.Instruction) *CORERelocation
type Const
    func (c *Const) Format(fs fmt.State, verb rune)
    func (c *Const) TypeName() string
type Datasec
    func (ds *Datasec) Format(fs fmt.State, verb rune)
    func (ds *Datasec) TypeName() string
type Enum
    func (e *Enum) Format(fs fmt.State, verb rune)
    func (e *Enum) TypeName() string
type EnumValue
type ExtInfos
    func (ei *ExtInfos) Assign(insns asm.Instructions, section string)
type Float
    func (f *Float) Format(fs fmt.State, verb rune)
    func (f *Float) TypeName() string
type Func
    func FuncMetadata(ins *asm.Instruction) *Func
    func (f *Func) Format(fs fmt.State, verb rune)
    func (f *Func) TypeName() string
type FuncLinkage
    func (i FuncLinkage) String() string
type FuncParam
type FuncProto
    func (fp *FuncProto) Format(fs fmt.State, verb rune)
    func (fp *FuncProto) TypeName() string
type Fwd
    func (f *Fwd) Format(fs fmt.State, verb rune)
    func (f *Fwd) TypeName() string
type FwdKind
    func (fk FwdKind) String() string
type GoFormatter
    func (gf *GoFormatter) TypeDeclaration(name string, typ Type) (string, error)
type Handle
    func NewHandle(spec *Spec) (*Handle, error)
    func NewHandleFromID(id ID) (*Handle, error)
    func (h *Handle) Close() error
    func (h *Handle) FD() int
    func (h *Handle) Info() (*HandleInfo, error)
    func (h *Handle) Spec(base *Spec) (*Spec, error)
type HandleInfo
    func (i *HandleInfo) IsModule() bool
    func (i *HandleInfo) IsVmlinux() bool
type HandleIterator
    func (it *HandleIterator) Err() error
    func (it *HandleIterator) Next(handle **Handle) bool
type ID
type Int
    func (i *Int) Format(fs fmt.State, verb rune)
    func (i *Int) TypeName() string
type IntEncoding
    func (ie IntEncoding) IsBool() bool
    func (ie IntEncoding) IsChar() bool
    func (ie IntEncoding) IsSigned() bool
    func (ie IntEncoding) String() string
type Line
    func (li *Line) FileName() string
    func (li *Line) Line() string
    func (li *Line) LineColumn() uint32
    func (li *Line) LineNumber() uint32
    func (li *Line) String() string
type Member
type Pointer
    func (p *Pointer) Format(fs fmt.State, verb rune)
    func (p *Pointer) TypeName() string
type Restrict
    func (r *Restrict) Format(fs fmt.State, verb rune)
    func (r *Restrict) TypeName() string
type Spec
    func LoadKernelSpec() (*Spec, error)
    func LoadSpec(file string) (*Spec, error)
    func LoadSpecFromReader(rd io.ReaderAt) (*Spec, error)
    func LoadSplitSpecFromReader(r io.ReaderAt, base *Spec) (*Spec, error)
    func (s *Spec) AnyTypeByName(name string) (Type, error)
    func (s *Spec) AnyTypesByName(name string) ([]Type, error)
    func (s *Spec) Copy() *Spec
    func (s *Spec) Iterate() *TypesIterator
    func (s *Spec) TypeByID(id TypeID) (Type, error)
    func (s *Spec) TypeByName(name string, typ interface{}) error
    func (s *Spec) TypeID(typ Type) (TypeID, error)
type Struct
    func (s *Struct) Format(fs fmt.State, verb rune)
    func (s *Struct) TypeName() string
type Transformer
type Type
    func Copy(typ Type, transform Transformer) Type
    func UnderlyingType(typ Type) Type
type TypeID
type Typedef
    func (td *Typedef) Format(fs fmt.State, verb rune)
    func (td *Typedef) TypeName() string
type TypesIterator
    func (iter *TypesIterator) Next() bool
type Union
    func (u *Union) Format(fs fmt.State, verb rune)
    func (u *Union) TypeName() string
type Var
    func (v *Var) Format(fs fmt.State, verb rune)
    func (v *Var) TypeName() string
type VarLinkage
    func (i VarLinkage) String() string
type VarSecinfo
type Void
    func (v *Void) Format(fs fmt.State, verb rune)
    func (v *Void) TypeName() string
type Volatile
    func (v *Volatile) Format(fs fmt.State, verb rune)
    func (v *Volatile) TypeName() string

Package files

btf.go btf_types.go btf_types_string.go core.go doc.go ext_info.go format.go handle.go strings.go types.go

Variables

Errors returned by BTF functions.

var (
    ErrNotSupported   = internal.ErrNotSupported
    ErrNotFound       = errors.New("not found")
    ErrNoExtendedInfo = errors.New("no extended info")
)

The size of a FuncInfo in BTF wire format.

var FuncInfoSize = uint32(binary.Size(bpfFuncInfo{}))
var LineInfoSize = uint32(binary.Size(bpfLineInfo{}))

func LoadSpecAndExtInfosFromReader

func LoadSpecAndExtInfosFromReader(rd io.ReaderAt) (*Spec, *ExtInfos, error)

LoadSpecAndExtInfosFromReader reads from an ELF.

ExtInfos may be nil if the ELF doesn't contain section metadta. Returns ErrNotFound if the ELF contains no BTF.

func MarshalExtInfos

func MarshalExtInfos(insns asm.Instructions, typeID func(Type) (TypeID, error)) (funcInfos, lineInfos []byte, _ error)

MarshalExtInfos encodes function and line info embedded in insns into kernel wire format.

func Sizeof

func Sizeof(typ Type) (int, error)

Sizeof returns the size of a type in bytes.

Returns an error if the size can't be computed.

type Array

Array is an array with a fixed number of elements.

type Array struct {
    Index  Type
    Type   Type
    Nelems uint32
}

func (*Array) Format

func (arr *Array) Format(fs fmt.State, verb rune)

func (*Array) TypeName

func (arr *Array) TypeName() string

type Bits

A value in bits.

type Bits uint32

func (Bits) Bytes

func (b Bits) Bytes() uint32

Bytes converts a bit value into bytes.

type COREFixup

COREFixup is the result of computing a CO-RE relocation for a target.

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

func CORERelocate

func CORERelocate(local, target *Spec, relos []*CORERelocation) ([]COREFixup, error)

CORERelocate calculates the difference in types between local and target.

Returns a list of fixups which can be applied to instructions to make them match the target type(s).

Fixups are returned in the order of relos, e.g. fixup[i] is the solution for relos[i].

func (*COREFixup) Apply

func (f *COREFixup) Apply(ins *asm.Instruction) error

func (*COREFixup) String

func (f *COREFixup) String() string

type CORERelocation

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

func CORERelocationMetadata

func CORERelocationMetadata(ins *asm.Instruction) *CORERelocation

type Const

Const is a qualifier.

type Const struct {
    Type Type
}

func (*Const) Format

func (c *Const) Format(fs fmt.State, verb rune)

func (*Const) TypeName

func (c *Const) TypeName() string

type Datasec

Datasec is a global program section containing data.

type Datasec struct {
    Name string
    Size uint32
    Vars []VarSecinfo
}

func (*Datasec) Format

func (ds *Datasec) Format(fs fmt.State, verb rune)

func (*Datasec) TypeName

func (ds *Datasec) TypeName() string

type Enum

Enum lists possible values.

type Enum struct {
    Name string
    // Size of the enum value in bytes.
    Size   uint32
    Values []EnumValue
}

func (*Enum) Format

func (e *Enum) Format(fs fmt.State, verb rune)

func (*Enum) TypeName

func (e *Enum) TypeName() string

type EnumValue

EnumValue is part of an Enum

Is is not a valid Type

type EnumValue struct {
    Name  string
    Value int32
}

type ExtInfos

ExtInfos contains ELF section metadata.

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

func (*ExtInfos) Assign

func (ei *ExtInfos) Assign(insns asm.Instructions, section string)

Assign per-section metadata from BTF to a section's instructions.

type Float

Float is a float of a given length.

type Float struct {
    Name string

    // The size of the float in bytes.
    Size uint32
}

func (*Float) Format

func (f *Float) Format(fs fmt.State, verb rune)

func (*Float) TypeName

func (f *Float) TypeName() string

type Func

Func is a function definition.

type Func struct {
    Name    string
    Type    Type
    Linkage FuncLinkage
}

func FuncMetadata

func FuncMetadata(ins *asm.Instruction) *Func

func (*Func) Format

func (f *Func) Format(fs fmt.State, verb rune)

func (*Func) TypeName

func (f *Func) TypeName() string

type FuncLinkage

FuncLinkage describes BTF function linkage metadata.

type FuncLinkage int

Equivalent of enum btf_func_linkage.

const (
    StaticFunc FuncLinkage = iota // static
    GlobalFunc                    // global
    ExternFunc                    // extern
)

func (FuncLinkage) String

func (i FuncLinkage) String() string

type FuncParam

type FuncParam struct {
    Name string
    Type Type
}

type FuncProto

FuncProto is a function declaration.

type FuncProto struct {
    Return Type
    Params []FuncParam
}

func (*FuncProto) Format

func (fp *FuncProto) Format(fs fmt.State, verb rune)

func (*FuncProto) TypeName

func (fp *FuncProto) TypeName() string

type Fwd

Fwd is a forward declaration of a Type.

type Fwd struct {
    Name string
    Kind FwdKind
}

func (*Fwd) Format

func (f *Fwd) Format(fs fmt.State, verb rune)

func (*Fwd) TypeName

func (f *Fwd) TypeName() string

type FwdKind

FwdKind is the type of forward declaration.

type FwdKind int

Valid types of forward declaration.

const (
    FwdStruct FwdKind = iota
    FwdUnion
)

func (FwdKind) String

func (fk FwdKind) String() string

type GoFormatter

GoFormatter converts a Type to Go syntax.

A zero GoFormatter is valid to use.

type GoFormatter struct {

    // Types present in this map are referred to using the given name if they
    // are encountered when outputting another type.
    Names map[Type]string

    // Identifier is called for each field of struct-like types. By default the
    // field name is used as is.
    Identifier func(string) string

    // EnumIdentifier is called for each element of an enum. By default the
    // name of the enum type is concatenated with Identifier(element).
    EnumIdentifier func(name, element string) string
    // contains filtered or unexported fields
}

func (*GoFormatter) TypeDeclaration

func (gf *GoFormatter) TypeDeclaration(name string, typ Type) (string, error)

TypeDeclaration generates a Go type declaration for a BTF type.

type Handle

Handle is a reference to BTF loaded into the kernel.

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

func NewHandle

func NewHandle(spec *Spec) (*Handle, error)

NewHandle loads BTF into the kernel.

Returns ErrNotSupported if BTF is not supported.

func NewHandleFromID

func NewHandleFromID(id ID) (*Handle, error)

NewHandleFromID returns the BTF handle for a given id.

Prefer calling [ebpf.Program.Handle] or [ebpf.Map.Handle] if possible.

Returns ErrNotExist, if there is no BTF with the given id.

Requires CAP_SYS_ADMIN.

func (*Handle) Close

func (h *Handle) Close() error

Close destroys the handle.

Subsequent calls to FD will return an invalid value.

func (*Handle) FD

func (h *Handle) FD() int

FD returns the file descriptor for the handle.

func (*Handle) Info

func (h *Handle) Info() (*HandleInfo, error)

Info returns metadata about the handle.

func (*Handle) Spec

func (h *Handle) Spec(base *Spec) (*Spec, error)

Spec parses the kernel BTF into Go types.

base is used to decode split BTF and may be nil.

type HandleInfo

HandleInfo describes a Handle.

type HandleInfo struct {
    // ID of this handle in the kernel. The ID is only valid as long as the
    // associated handle is kept alive.
    ID ID

    // Name is an identifying name for the BTF, currently only used by the
    // kernel.
    Name string

    // IsKernel is true if the BTF originated with the kernel and not
    // userspace.
    IsKernel bool
    // contains filtered or unexported fields
}

func (*HandleInfo) IsModule

func (i *HandleInfo) IsModule() bool

IsModule returns true if the BTF is for a kernel module.

func (*HandleInfo) IsVmlinux

func (i *HandleInfo) IsVmlinux() bool

IsModule returns true if the BTF is for the kernel itself.

type HandleIterator

HandleIterator allows enumerating BTF blobs loaded into the kernel.

type HandleIterator struct {
    // The ID of the last retrieved handle. Only valid after a call to Next.
    ID ID
    // contains filtered or unexported fields
}

Example

Code:

var handle *btf.Handle
// Ensure that handle is cleaned up. This is valid for nil handles as well.
defer handle.Close()

it := new(btf.HandleIterator)
for it.Next(&handle) {
    fmt.Printf("Found handle with ID %d\n", it.ID)
}
if err := it.Err(); err != nil {
    panic(err)
}

func (*HandleIterator) Err

func (it *HandleIterator) Err() error

Err returns an error if iteration failed for some reason.

func (*HandleIterator) Next

func (it *HandleIterator) Next(handle **Handle) bool

Next retrieves a handle for the next BTF blob.

Handle.Close is called if *handle is non-nil to avoid leaking fds.

Returns true if another BTF blob was found. Call HandleIterator.Err after the function returns false.

type ID

ID represents the unique ID of a BTF object.

type ID = sys.BTFID

type Int

Int is an integer of a given length.

See https://www.kernel.org/doc/html/latest/bpf/btf.html#btf-kind-int

type Int struct {
    Name string

    // The size of the integer in bytes.
    Size     uint32
    Encoding IntEncoding
}

func (*Int) Format

func (i *Int) Format(fs fmt.State, verb rune)

func (*Int) TypeName

func (i *Int) TypeName() string

type IntEncoding

type IntEncoding byte
const (
    Signed IntEncoding = 1 << iota
    Char
    Bool
)

func (IntEncoding) IsBool

func (ie IntEncoding) IsBool() bool

func (IntEncoding) IsChar

func (ie IntEncoding) IsChar() bool

func (IntEncoding) IsSigned

func (ie IntEncoding) IsSigned() bool

func (IntEncoding) String

func (ie IntEncoding) String() string

type Line

Line represents the location and contents of a single line of source code a BPF ELF was compiled from.

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

func (*Line) FileName

func (li *Line) FileName() string

func (*Line) Line

func (li *Line) Line() string

func (*Line) LineColumn

func (li *Line) LineColumn() uint32

func (*Line) LineNumber

func (li *Line) LineNumber() uint32

func (*Line) String

func (li *Line) String() string

type Member

Member is part of a Struct or Union.

It is not a valid Type.

type Member struct {
    Name         string
    Type         Type
    Offset       Bits
    BitfieldSize Bits
}

type Pointer

Pointer is a pointer to another type.

type Pointer struct {
    Target Type
}

func (*Pointer) Format

func (p *Pointer) Format(fs fmt.State, verb rune)

func (*Pointer) TypeName

func (p *Pointer) TypeName() string

type Restrict

Restrict is a qualifier.

type Restrict struct {
    Type Type
}

func (*Restrict) Format

func (r *Restrict) Format(fs fmt.State, verb rune)

func (*Restrict) TypeName

func (r *Restrict) TypeName() string

type Spec

Spec represents decoded BTF.

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

func LoadKernelSpec

func LoadKernelSpec() (*Spec, error)

LoadKernelSpec returns the current kernel's BTF information.

Defaults to /sys/kernel/btf/vmlinux and falls back to scanning the file system for vmlinux ELFs. Returns an error wrapping ErrNotSupported if BTF is not enabled.

func LoadSpec

func LoadSpec(file string) (*Spec, error)

LoadSpec opens file and calls LoadSpecFromReader on it.

func LoadSpecFromReader

func LoadSpecFromReader(rd io.ReaderAt) (*Spec, error)

LoadSpecFromReader reads from an ELF or a raw BTF blob.

Returns ErrNotFound if reading from an ELF which contains no BTF. ExtInfos may be nil.

func LoadSplitSpecFromReader

func LoadSplitSpecFromReader(r io.ReaderAt, base *Spec) (*Spec, error)

LoadSplitSpecFromReader loads split BTF from a reader.

Types from base are used to resolve references in the split BTF. The returned Spec only contains types from the split BTF, not from the base.

func (*Spec) AnyTypeByName

func (s *Spec) AnyTypeByName(name string) (Type, error)

AnyTypeByName returns a Type with the given name.

Returns an error if multiple types of that name exist.

func (*Spec) AnyTypesByName

func (s *Spec) AnyTypesByName(name string) ([]Type, error)

AnyTypesByName returns a list of BTF Types with the given name.

If the BTF blob describes multiple compilation units like vmlinux, multiple Types with the same name and kind can exist, but might not describe the same data structure.

Returns an error wrapping ErrNotFound if no matching Type exists in the Spec.

func (*Spec) Copy

func (s *Spec) Copy() *Spec

Copy creates a copy of Spec.

func (*Spec) Iterate

func (s *Spec) Iterate() *TypesIterator

Iterate returns the types iterator.

func (*Spec) TypeByID

func (s *Spec) TypeByID(id TypeID) (Type, error)

TypeByID returns the BTF Type with the given type ID.

Returns an error wrapping ErrNotFound if a Type with the given ID does not exist in the Spec.

func (*Spec) TypeByName

func (s *Spec) TypeByName(name string, typ interface{}) error

TypeByName searches for a Type with a specific name. Since multiple Types with the same name can exist, the parameter typ is taken to narrow down the search in case of a clash.

typ must be a non-nil pointer to an implementation of a Type. On success, the address of the found Type will be copied to typ.

Returns an error wrapping ErrNotFound if no matching Type exists in the Spec. If multiple candidates are found, an error is returned.

Example

Code:

// Acquire a Spec via one of its constructors.
spec := new(Spec)

// Declare a variable of the desired type
var foo *Struct

if err := spec.TypeByName("foo", &foo); err != nil {
    // There is no struct with name foo, or there
    // are multiple possibilities.
}

// We've found struct foo
fmt.Println(foo.Name)

func (*Spec) TypeID

func (s *Spec) TypeID(typ Type) (TypeID, error)

TypeID returns the ID for a given Type.

Returns an error wrapping ErrNoFound if the type isn't part of the Spec.

type Struct

Struct is a compound type of consecutive members.

type Struct struct {
    Name string
    // The size of the struct including padding, in bytes
    Size    uint32
    Members []Member
}

func (*Struct) Format

func (s *Struct) Format(fs fmt.State, verb rune)

func (*Struct) TypeName

func (s *Struct) TypeName() string

type Transformer

Transformer modifies a given Type and returns the result.

For example, UnderlyingType removes any qualifiers or typedefs from a type. See the example on Copy for how to use a transform.

type Transformer func(Type) Type

type Type

Type represents a type described by BTF.

type Type interface {
    // Type can be formatted using the %s and %v verbs. %s outputs only the
    // identity of the type, without any detail. %v outputs additional detail.
    //
    // Use the '+' flag to include the address of the type.
    //
    // Use the width to specify how many levels of detail to output, for example
    // %1v will output detail for the root type and a short description of its
    // children. %2v would output details of the root type and its children
    // as well as a short description of the grandchildren.
    fmt.Formatter

    // Name of the type, empty for anonymous types and types that cannot
    // carry a name, like Void and Pointer.
    TypeName() string
    // contains filtered or unexported methods
}

Example (ValidTypes)

The following are valid Types. There currently is no better way to document which types implement an interface.

Code:

var _ Type = &Void{}
var _ Type = &Int{}
var _ Type = &Pointer{}
var _ Type = &Array{}
var _ Type = &Struct{}
var _ Type = &Union{}
var _ Type = &Enum{}
var _ Type = &Fwd{}
var _ Type = &Typedef{}
var _ Type = &Volatile{}
var _ Type = &Const{}
var _ Type = &Restrict{}
var _ Type = &Func{}
var _ Type = &FuncProto{}
var _ Type = &Var{}
var _ Type = &Datasec{}

func Copy

func Copy(typ Type, transform Transformer) Type

Copy a Type recursively.

typ may form a cycle. If transform is not nil, it is called with the to be copied type, and the returned value is copied instead.

Example (StripQualifiers)

Copy can be used with UnderlyingType to strip qualifiers from a type graph.

Code:

a := &Volatile{Type: &Pointer{Target: &Typedef{Name: "foo", Type: &Int{Size: 2}}}}
b := Copy(a, UnderlyingType)
// b has Volatile and Typedef removed.
fmt.Printf("%3v\n", b)

Output:

Pointer[target=Int[unsigned size=16]]

func UnderlyingType

func UnderlyingType(typ Type) Type

UnderlyingType skips qualifiers and Typedefs.

type TypeID

TypeID identifies a type in a BTF section.

type TypeID uint32

type Typedef

Typedef is an alias of a Type.

type Typedef struct {
    Name string
    Type Type
}

func (*Typedef) Format

func (td *Typedef) Format(fs fmt.State, verb rune)

func (*Typedef) TypeName

func (td *Typedef) TypeName() string

type TypesIterator

TypesIterator iterates over types of a given spec.

type TypesIterator struct {

    // The last visited type in the spec.
    Type Type
    // contains filtered or unexported fields
}

func (*TypesIterator) Next

func (iter *TypesIterator) Next() bool

Next returns true as long as there are any remaining types.

type Union

Union is a compound type where members occupy the same memory.

type Union struct {
    Name string
    // The size of the union including padding, in bytes.
    Size    uint32
    Members []Member
}

func (*Union) Format

func (u *Union) Format(fs fmt.State, verb rune)

func (*Union) TypeName

func (u *Union) TypeName() string

type Var

Var is a global variable.

type Var struct {
    Name    string
    Type    Type
    Linkage VarLinkage
}

func (*Var) Format

func (v *Var) Format(fs fmt.State, verb rune)

func (*Var) TypeName

func (v *Var) TypeName() string

type VarLinkage

VarLinkage describes BTF variable linkage metadata.

type VarLinkage int
const (
    StaticVar VarLinkage = iota // static
    GlobalVar                   // global
    ExternVar                   // extern
)

func (VarLinkage) String

func (i VarLinkage) String() string

type VarSecinfo

VarSecinfo describes variable in a Datasec.

It is not a valid Type.

type VarSecinfo struct {
    Type   Type
    Offset uint32
    Size   uint32
}

type Void

Void is the unit type of BTF.

type Void struct{}

func (*Void) Format

func (v *Void) Format(fs fmt.State, verb rune)

func (*Void) TypeName

func (v *Void) TypeName() string

type Volatile

Volatile is a qualifier.

type Volatile struct {
    Type Type
}

func (*Volatile) Format

func (v *Volatile) Format(fs fmt.State, verb rune)

func (*Volatile) TypeName

func (v *Volatile) TypeName() string