libbpfgo

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Aug 5, 2023 License: Apache-2.0 Imports: 13 Imported by: 0

README

libbpfgo

GitHub release (latest by date) Go Report Card License


libbpfgo is a Go library for Linux's eBPF project. It was created for Tracker, our open source Runtime Security, and eBPF tracing tool, written in Go. If you are interested in eBPF and its applications, check out Tracker at Github: https://github.com/khulnasoft-labs/tracker.

libbpfgo is built around libbpf - the standard library for interacting with eBPF programs from userspace - which is a C library maintained in Linux upstream. We have created libbpfgo as a thin Go wrapper around the libbpf project.

Installing

libbpfgo uses CGO to interop with libbpf and will expect to be linked with libbpf at run or link time. Simply importing libbpfgo is not enough to get started, and you will need to fulfill the required dependency in one of the following ways:

  1. Install libbpf as a shared object in the system. Libbpf may already be packaged for your distribution and, if not, you can build and install from source. More info here.
  2. Embed libbpf into your Go project as a vendored dependency. This means that the libbpf code is statically linked into the resulting binary, and there are no runtime dependencies. Tracker takes this approach.

Building

Currently you will find the following GNU Makefile rules:

Makefile Rule Description
all builds libbpfgo (dynamic)
clean cleans entire tree
selftest builds all selftests (static)
selftest-run runs all selftests (static)
helpers-test-run runs all helpers tests (static)
  • libbpf dynamically linked (libbpf from OS)
Makefile Rule Description
libbpfgo-dynamic builds dynamic libbpfgo (libbpf)
libbpfgo-dynamic-test 'go test' with dynamic libbpfgo
selftest-dynamic build tests with dynamic libbpfgo
selftest-dynamic-run run tests using dynamic libbpfgo
helpers-test-dynamic-run run helpers package unit tests using dynamic libbpfgo
  • statically compiled (libbpf submodule)
Makefile Rule Description
libbpfgo-static builds static libbpfgo (libbpf)
libbpfgo-static-test 'go test' with static libbpfgo
selftest-static build tests with static libbpfgo
selftest-static-run run tests using static libbpfgo
helpers-test-static-run run helpers package unit tests using static libbpfgo
  • examples
$ make libbpfgo-static => libbpfgo statically linked with libbpf
$ make -C selftest/perfbuffers => single selftest build (static libbpf)
$ make -C selftest/perfbuffers run-dynamic => single selftest run (dynamic libbpf)
$ make selftest-static-run => will build & run all static selftests

Note 01: dynamic builds need your OS to have a recent enough libbpf package (and its headers) installed. Sometimes, recent features might require the use of backported OS packages in order for your OS to contain latest libbpf features (sometimes required by libbpfgo). Note 02: static builds need git submodule init first. Make sure to sync the libbpf git submodule before trying to statically compile or test the libbpfgo repository.

Concepts

libbpfgo tries to make it natural for Go developers to use, by abstracting away C technicalities. For example, it will translate low level return codes into Go error, it will organize functionality around Go struct, and it will use channel as to let you consume events.

In a high level, this is a typical workflow for working with the library:

  1. Compile your bpf program into an object file.
  2. Initialize a Module struct - that is a unit of BPF functionality around your compiled object file.
  3. Load bpf programs from the object file using the BPFProg struct.
  4. Attach BPFProg to system facilities, for example to "raw tracepoints" or "kprobes" using the BPFProg's associated functions.
  5. Instantiate and manipulate BPF Maps via the BPFMap struct and it's associated methods.
  6. Instantiate and manipulate Perf Buffer for communicating events from your BPF program to the driving userspace program, using the RingBuffer struct and it's associated objects.

Example

// initializing
import bpf "github.com/khulnasoft-labs/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

Releases

libbpfgo does not yet have a regular schedule for cutting releases. There has not yet been a major release but API backwards compatibility will be maintained for all releases with the same major release number. Milestones are created when preparing for release.

  • Major releases are cut when backwards compatibility is broken or major milestones are completed, such as reaching parity with libbpf's API.
  • Minor releases are cut to incorporate new support for libbpf APIs.
  • Patch releases are cut to incorporate important individual or groupings of bug fixes.
  • libbpf support numbering indicates the minimum required libbpf version that must be linked in order to ensure libbpfgo compatibility. For example, v0.2.1-libbpf-0.4.0 means that version 0.2.1 of libbpfgo requires v0.4.0 or newer of libbpf.

Note: some distributions might have local changes to their libbpf package and their version might include backports and/or fixes differently than upstream versions. In those cases we recommend that libbpfgo is used statically compiled.

Contributing

To better receive you, libbpfgo makes available GNU Makefile rules for vagrant machines (amd64/arm64) that can be used to compile and test on Linux and Darwin hosts:

Makefile Rule Description
vagrant-up starts and provisions the vagrant environment
vagrant-ssh connects to machine via SSH
vagrant-halt stops the vagrant machine
vagrant-destroy stops and deletes all traces of the vagrant machine

Once connected to the vagrant box you are ready to build libbpfgo (e.g. make libbpfgo-static).

For further information, check Vagrantfile.md.

Learn more

Please check our github milestones for an idea of the project roadmap. The general goal is to fully implement/expose libbpf's API in Go as seamlessly as possible.

Documentation

Index

Constants

View Source
const (
	// libbpf print levels
	LibbpfWarnLevel  = int(C.LIBBPF_WARN)
	LibbpfInfoLevel  = int(C.LIBBPF_INFO)
	LibbpfDebugLevel = int(C.LIBBPF_DEBUG)
)

Variables

This section is empty.

Functions

func BPFMapTypeIsSupported

func BPFMapTypeIsSupported(mapType MapType) (bool, error)

func BPFProgramTypeIsSupported

func BPFProgramTypeIsSupported(progType BPFProgType) (bool, error)

func LibbpfVersionString

func LibbpfVersionString() string

LibbpfVersionString returns the string representation of the libbpf version which libbpfgo is linked against

func MajorVersion

func MajorVersion() int

MajorVersion returns the major semver version of libbpf.

func MinorVersion

func MinorVersion() int

MinorVersion returns the minor semver version of libbpf.

func NumPossibleCPUs

func NumPossibleCPUs() (int, error)

func SetLoggerCbs

func SetLoggerCbs(cbs Callbacks)

SetLoggerCbs receives Callbacks type to be used to log libbpf outputs and to filter out those outputs

func SetStrictMode

func SetStrictMode(mode LibbpfStrictMode)

Types

type AttachFlag

type AttachFlag uint32
const (
	BPFFNone          AttachFlag = 0
	BPFFAllowOverride AttachFlag = C.BPF_F_ALLOW_OVERRIDE
	BPFFAllowMulti    AttachFlag = C.BPF_F_ALLOW_MULTI
	BPFFReplace       AttachFlag = C.BPF_F_REPLACE
)

type BPFAttachType

type BPFAttachType uint32
const (
	BPFAttachTypeCgroupInetIngress BPFAttachType = iota
	BPFAttachTypeCgroupInetEgress
	BPFAttachTypeCgroupInetSockCreate
	BPFAttachTypeCgroupSockOps
	BPFAttachTypeSKSKBStreamParser
	BPFAttachTypeSKSKBStreamVerdict
	BPFAttachTypeCgroupDevice
	BPFAttachTypeSKMSGVerdict
	BPFAttachTypeCgroupInet4Bind
	BPFAttachTypeCgroupInet6Bind
	BPFAttachTypeCgroupInet4Connect
	BPFAttachTypeCgroupInet6Connect
	BPFAttachTypeCgroupInet4PostBind
	BPFAttachTypeCgroupInet6PostBind
	BPFAttachTypeCgroupUDP4SendMsg
	BPFAttachTypeCgroupUDP6SendMsg
	BPFAttachTypeLircMode2
	BPFAttachTypeFlowDissector
	BPFAttachTypeCgroupSysctl
	BPFAttachTypeCgroupUDP4RecvMsg
	BPFAttachTypeCgroupUDP6RecvMsg
	BPFAttachTypeCgroupGetSockOpt
	BPFAttachTypeCgroupSetSockOpt
	BPFAttachTypeTraceRawTP
	BPFAttachTypeTraceFentry
	BPFAttachTypeTraceFexit
	BPFAttachTypeModifyReturn
	BPFAttachTypeLSMMac
	BPFAttachTypeTraceIter
	BPFAttachTypeCgroupInet4GetPeerName
	BPFAttachTypeCgroupInet6GetPeerName
	BPFAttachTypeCgroupInet4GetSockName
	BPFAttachTypeCgroupInet6GetSockName
	BPFAttachTypeXDPDevMap
	BPFAttachTypeCgroupInetSockRelease
	BPFAttachTypeXDPCPUMap
	BPFAttachTypeSKLookup
	BPFAttachTypeXDP
	BPFAttachTypeSKSKBVerdict
	BPFAttachTypeSKReusePortSelect
	BPFAttachTypeSKReusePortSelectorMigrate
	BPFAttachTypePerfEvent
	BPFAttachTypeTraceKprobeMulti
)

type BPFCgroupIterOrder

type BPFCgroupIterOrder uint32
const (
	BPFIterOrderUnspec BPFCgroupIterOrder = iota
	BPFIterSelfOnly
	BPFIterDescendantsPre
	BPFIterDescendantsPost
	BPFIterAncestorsUp
)
type BPFLink struct {
	// contains filtered or unexported fields
}

func (*BPFLink) Destroy

func (l *BPFLink) Destroy() error

func (*BPFLink) DestroyLegacy

func (l *BPFLink) DestroyLegacy(linkType LinkType) error

func (*BPFLink) FileDescriptor

func (l *BPFLink) FileDescriptor() int

func (*BPFLink) GetFd deprecated

func (l *BPFLink) GetFd() int

Deprecated: use BPFLink.FileDescriptor() instead.

func (*BPFLink) Pin

func (l *BPFLink) Pin(pinPath string) error

func (*BPFLink) Reader

func (l *BPFLink) Reader() (*BPFLinkReader, error)

func (*BPFLink) Unpin

func (l *BPFLink) Unpin(pinPath string) error

type BPFLinkLegacy

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

type BPFLinkReader

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

BPFLinkReader read data from a BPF link

func (*BPFLinkReader) Close

func (i *BPFLinkReader) Close() error

func (*BPFLinkReader) Read

func (i *BPFLinkReader) Read(p []byte) (n int, err error)

type BPFMap

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

func CreateMap

func CreateMap(mapType MapType, mapName string, keySize, valueSize, maxEntries int, opts *BPFMapCreateOpts) (*BPFMap, error)

CreateMap creates a BPF map from userspace. This can be used for populating BPF array of maps or hash of maps. However, this function uses a low-level libbpf API; maps created in this way do not conform to libbpf map formats, and therefore do not have access to libbpf high level bpf_map__* APIS which causes different behavior from maps created in the kernel side code

See usage of `bpf_map_create()` in kernel selftests for more info

func (*BPFMap) DeleteKey

func (b *BPFMap) DeleteKey(key unsafe.Pointer) error

DeleteKey takes a pointer to the key which is stored in the map. It removes the key and associated value from the BPFMap. All basic types, and structs are supported as keys.

NOTE: Slices and arrays are also supported but special care should be taken as to take a reference to the first element in the slice or array instead of the slice/array itself, as to avoid undefined behavior.

func (*BPFMap) DeleteKeyBatch

func (b *BPFMap) DeleteKeyBatch(keys unsafe.Pointer, count uint32) error

DeleteKeyBatch allows for batch deletion of multiple elements in the map.

`count` number of keys will be deleted from the map. Passing an argument that greater than the number of keys in the map will cause the function to delete fewer keys than requested. See the inline comment in `GetValueAndDeleteBatch` for more context.

func (*BPFMap) FileDescriptor

func (b *BPFMap) FileDescriptor() int

func (*BPFMap) GetFd deprecated

func (b *BPFMap) GetFd() int

Deprecated: use BPFMap.FileDescriptor() instead.

func (*BPFMap) GetMaxEntries

func (b *BPFMap) GetMaxEntries() uint32

GetMaxEntries returns the map's capacity. Note: for ring buffer and perf buffer, maxEntries is the capacity in bytes.

func (*BPFMap) GetModule

func (b *BPFMap) GetModule() *Module

func (*BPFMap) GetName deprecated

func (b *BPFMap) GetName() string

Deprecated: use BPFMap.Name() instead.

func (*BPFMap) GetPinPath deprecated

func (b *BPFMap) GetPinPath() string

Deprecated: use BPFMap.PinPath() instead.

func (*BPFMap) GetValue

func (b *BPFMap) GetValue(key unsafe.Pointer) ([]byte, error)

GetValue takes a pointer to the key which is stored in the map. It returns the associated value as a slice of bytes. All basic types, and structs are supported as keys.

NOTE: Slices and arrays are also supported but special care should be taken as to take a reference to the first element in the slice or array instead of the slice/array itself, as to avoid undefined behavior.

func (*BPFMap) GetValueAndDeleteBatch

func (b *BPFMap) GetValueAndDeleteBatch(keys, startKey, nextKey unsafe.Pointer, count uint32) ([][]byte, error)

GetValueAndDeleteBatch allows for batch lookup and deletion of elements where each element is deleted after being retrieved from the map.

The first argument, keys, is a pointer to an array or slice of keys which will be populated with the keys returned from this operation. It returns the associated values as a slice of slices of bytes.

This API allows for batch lookups and deletion of multiple keys, potentially in steps over multiple iterations. For example, you provide the last key seen (or nil) for the startKey, and the first key to start the next iteration with in nextKey. Once the first iteration is complete you can provide the last key seen in the previous iteration as the startKey for the next iteration and repeat until nextKey is nil.

The last argument, count, is the number of keys to lookup and delete. The kernel will update it with the count of the elements that were retrieved and deleted.

The API can return partial results even though an -1 is returned. In this case, errno will be set to `ENOENT` and the values slice and count will be filled in with the elements that were read. See the comment below for more context.

func (*BPFMap) GetValueBatch

func (b *BPFMap) GetValueBatch(keys unsafe.Pointer, startKey, nextKey unsafe.Pointer, count uint32) ([][]byte, error)

GetValueBatch allows for batch lookups of multiple keys from the map.

The first argument, keys, is a pointer to an array or slice of keys which will be populated with the keys returned from this operation. It returns the associated values as a slice of slices of bytes.

This API allows for batch lookups of multiple keys, potentially in steps over multiple iterations. For example, you provide the last key seen (or nil) for the startKey, and the first key to start the next iteration with in nextKey. Once the first iteration is complete you can provide the last key seen in the previous iteration as the startKey for the next iteration and repeat until nextKey is nil.

The last argument, count, is the number of keys to lookup. The kernel will update it with the count of the elements that were retrieved.

The API can return partial results even though an -1 is returned. In this case, errno will be set to `ENOENT` and the values slice and count will be filled in with the elements that were read. See the inline comment in `GetValueAndDeleteBatch` for more context.

func (*BPFMap) GetValueFlags

func (b *BPFMap) GetValueFlags(key unsafe.Pointer, flags MapFlag) ([]byte, error)

func (*BPFMap) GetValueReadInto

func (b *BPFMap) GetValueReadInto(key unsafe.Pointer, value *[]byte) error

GetValueReadInto is like GetValue, except it allows the caller to pass in a pointer to the slice of bytes that the value would be read into from the map. This is useful for reading from maps with variable sizes, especially per-cpu arrays and hash maps where the size of each value depends on the number of CPUs

func (*BPFMap) IsPinned

func (b *BPFMap) IsPinned() bool

func (*BPFMap) Iterator

func (b *BPFMap) Iterator() *BPFMapIterator

func (*BPFMap) KeySize

func (b *BPFMap) KeySize() int

func (*BPFMap) Name

func (b *BPFMap) Name() string

func (*BPFMap) Pin

func (b *BPFMap) Pin(pinPath string) error

func (*BPFMap) PinPath

func (b *BPFMap) PinPath() string

func (*BPFMap) Resize

func (b *BPFMap) Resize(maxEntries uint32) error

Resize changes the map's capacity to maxEntries. It should be called after the module was initialized but prior to it being loaded with BPFLoadObject. Note: for ring buffer and perf buffer, maxEntries is the capacity in bytes.

func (*BPFMap) SetPinPath

func (b *BPFMap) SetPinPath(pinPath string) error

func (*BPFMap) SetType

func (b *BPFMap) SetType(mapType MapType) error

SetType is used to set the type of a bpf map that isn't associated with a file descriptor already. If the map is already associated with a file descriptor the libbpf API will return error code EBUSY

func (*BPFMap) SetValueSize

func (b *BPFMap) SetValueSize(size uint32) error

func (*BPFMap) Type

func (b *BPFMap) Type() MapType

func (*BPFMap) Unpin

func (b *BPFMap) Unpin(pinPath string) error

func (*BPFMap) Update

func (b *BPFMap) Update(key, value unsafe.Pointer) error

Update takes a pointer to a key and a value to associate it with in the BPFMap. The unsafe.Pointer should be taken on a reference to the underlying datatype. All basic types, and structs are supported

NOTE: Slices and arrays are supported but references should be passed to the first element in the slice or array.

For example:

key := 1 value := []byte{'a', 'b', 'c'} keyPtr := unsafe.Pointer(&key) valuePtr := unsafe.Pointer(&value[0]) bpfmap.Update(keyPtr, valuePtr)

func (*BPFMap) UpdateBatch

func (b *BPFMap) UpdateBatch(keys, values unsafe.Pointer, count uint32) error

UpdateBatch updates multiple elements in the map by specified keys and their corresponding values.

The first argument, keys, is a pointer to an array or slice of keys which will be updated using the second argument, values. It returns the associated error if any occurred.

The last argument, count, is the number of keys to update. Passing an argument that greater than the number of keys in the map will cause the function to return a syscall.EPERM as an error.

func (*BPFMap) UpdateValueFlags

func (b *BPFMap) UpdateValueFlags(key, value unsafe.Pointer, flags MapFlag) error

func (*BPFMap) ValueSize

func (b *BPFMap) ValueSize() int

type BPFMapBatchOpts

type BPFMapBatchOpts struct {
	Sz        uint64
	ElemFlags uint64
	Flags     uint64
}

BPFMapBatchOpts mirrors the C structure bpf_map_batch_opts.

type BPFMapCreateOpts

type BPFMapCreateOpts struct {
	Size                  uint64
	BtfFD                 uint32
	BtfKeyTypeID          uint32
	BtfValueTypeID        uint32
	BtfVmlinuxValueTypeID uint32
	InnerMapFD            uint32
	MapFlags              uint32
	MapExtra              uint64
	NumaNode              uint32
	MapIfIndex            uint32
}

BPFMapCreateOpts mirrors the C structure bpf_map_create_opts

type BPFMapIterator

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

BPFMapIterator iterates over keys in a BPF map

func (*BPFMapIterator) Err

func (it *BPFMapIterator) Err() error

Err returns the last error that ocurred while table.Iter or iter.Next

func (*BPFMapIterator) Key

func (it *BPFMapIterator) Key() []byte

Key returns the current key value of the iterator, if the most recent call to Next returned true. The slice is valid only until the next call to Next.

func (*BPFMapIterator) Next

func (it *BPFMapIterator) Next() bool

type BPFObjectIterator

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

BPFObjectProgramIterator iterates over maps in a BPF object

func (*BPFObjectIterator) NextMap

func (it *BPFObjectIterator) NextMap() *BPFMap

func (*BPFObjectIterator) NextProgram

func (it *BPFObjectIterator) NextProgram() *BPFProg

type BPFProg

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

func (*BPFProg) AttachCgroup

func (p *BPFProg) AttachCgroup(cgroupV2DirPath string) (*BPFLink, error)

AttachCgroup attaches the BPFProg to a cgroup described by given fd.

func (*BPFProg) AttachCgroupLegacy

func (p *BPFProg) AttachCgroupLegacy(cgroupV2DirPath string, attachType BPFAttachType) (*BPFLink, error)

AttachCgroupLegacy attaches the BPFProg to a cgroup described by the given fd. It first tries to use the most recent attachment method and, if that does not work, instead of failing, it tries the legacy way: to attach the cgroup eBPF program without previously creating a link. This allows attaching cgroup eBPF ingress/egress in older kernels. Note: the first attempt error message is filtered out inside libbpf_print_fn() as it is actually a feature probe attempt as well.

Related kernel commit: https://github.com/torvalds/linux/commit/af6eea57437a

func (*BPFProg) AttachGeneric

func (p *BPFProg) AttachGeneric() (*BPFLink, error)

AttachGeneric is used to attach the BPF program using autodetection for the attach target. You can specify the destination in BPF code via the SEC() such as `SEC("fentry/some_kernel_func")`

func (*BPFProg) AttachGenericFD

func (p *BPFProg) AttachGenericFD(targetFd int, attachType BPFAttachType, flags AttachFlag) error

AttachGenericFD attaches the BPFProgram to a targetFd at the specified attachType hook.

func (*BPFProg) AttachIter

func (p *BPFProg) AttachIter(opts IterOpts) (*BPFLink, error)

func (*BPFProg) AttachKprobe

func (p *BPFProg) AttachKprobe(kp string) (*BPFLink, error)

this API should be used for kernels > 4.17

func (*BPFProg) AttachKretprobe

func (p *BPFProg) AttachKretprobe(kp string) (*BPFLink, error)

this API should be used for kernels > 4.17

func (*BPFProg) AttachLSM

func (p *BPFProg) AttachLSM() (*BPFLink, error)

func (*BPFProg) AttachNetns

func (p *BPFProg) AttachNetns(networkNamespacePath string) (*BPFLink, error)

func (*BPFProg) AttachPerfEvent

func (p *BPFProg) AttachPerfEvent(fd int) (*BPFLink, error)

func (*BPFProg) AttachRawTracepoint

func (p *BPFProg) AttachRawTracepoint(tpEvent string) (*BPFLink, error)

func (*BPFProg) AttachTracepoint

func (p *BPFProg) AttachTracepoint(category, name string) (*BPFLink, error)

func (*BPFProg) AttachURetprobe

func (p *BPFProg) AttachURetprobe(pid int, path string, offset uint32) (*BPFLink, error)

AttachURetprobe attaches the BPFProgram to exit of the symbol in the library or binary at 'path' which can be relative or absolute. A pid can be provided to attach to, or -1 can be specified to attach to all processes

func (*BPFProg) AttachUprobe

func (p *BPFProg) AttachUprobe(pid int, path string, offset uint32) (*BPFLink, error)

AttachUprobe attaches the BPFProgram to entry of the symbol in the library or binary at 'path' which can be relative or absolute. A pid can be provided to attach to, or -1 can be specified to attach to all processes

func (*BPFProg) AttachXDP

func (p *BPFProg) AttachXDP(deviceName string) (*BPFLink, error)

func (*BPFProg) DetachCgroupLegacy

func (p *BPFProg) DetachCgroupLegacy(cgroupV2DirPath string, attachType BPFAttachType) error

DetachCgroupLegacy detaches the BPFProg from a cgroup described by the given fd. This is needed because in legacy attachment there is no BPFLink, just a fake one (kernel did not support it, nor libbpf). This function should be called by the (*BPFLink)->Destroy() function, since BPFLink is emulated (so users don´t need to distinguish between regular and legacy cgroup detachments).

func (*BPFProg) DetachGenericFD

func (p *BPFProg) DetachGenericFD(targetFd int, attachType BPFAttachType) error

DetachGenericFD detaches the BPFProgram associated with the targetFd at the hook specified by attachType.

func (*BPFProg) FileDescriptor

func (p *BPFProg) FileDescriptor() int

func (*BPFProg) GetFd deprecated

func (p *BPFProg) GetFd() int

Deprecated: use BPFProg.FileDescriptor() instead.

func (*BPFProg) GetModule

func (p *BPFProg) GetModule() *Module

func (*BPFProg) GetName deprecated

func (p *BPFProg) GetName() string

Deprecated: use BPFProg.Name() instead.

func (*BPFProg) GetPinPath deprecated

func (p *BPFProg) GetPinPath() string

Deprecated: use BPFProg.PinPath() instead.

func (*BPFProg) GetSectionName deprecated

func (p *BPFProg) GetSectionName() string

Deprecated: use BPFProg.SectionName() instead.

func (*BPFProg) GetType

func (p *BPFProg) GetType() BPFProgType

func (*BPFProg) Name

func (p *BPFProg) Name() string

func (*BPFProg) Pin

func (p *BPFProg) Pin(path string) error

func (*BPFProg) PinPath

func (p *BPFProg) PinPath() string

func (*BPFProg) SectionName

func (p *BPFProg) SectionName() string

func (*BPFProg) SetAttachTarget

func (p *BPFProg) SetAttachTarget(attachProgFD int, attachFuncName string) error

SetAttachTarget can be used to specify the program and/or function to attach the BPF program to. To attach to a kernel function specify attachProgFD as 0

func (*BPFProg) SetAttachType

func (p *BPFProg) SetAttachType(attachType BPFAttachType)

func (*BPFProg) SetAutoload

func (p *BPFProg) SetAutoload(autoload bool) error

func (*BPFProg) SetProgramType

func (p *BPFProg) SetProgramType(progType BPFProgType)

func (*BPFProg) Unpin

func (p *BPFProg) Unpin(path string) error

type BPFProgType

type BPFProgType uint32

BPFProgType is an enum as defined in https://elixir.bootlin.com/linux/latest/source/include/uapi/linux/bpf.h

const (
	BPFProgTypeUnspec BPFProgType = iota
	BPFProgTypeSocketFilter
	BPFProgTypeKprobe
	BPFProgTypeSchedCls
	BPFProgTypeSchedAct
	BPFProgTypeTracepoint
	BPFProgTypeXdp
	BPFProgTypePerfEvent
	BPFProgTypeCgroupSkb
	BPFProgTypeCgroupSock
	BPFProgTypeLwtIn
	BPFProgTypeLwtOut
	BPFProgTypeLwtXmit
	BPFProgTypeSockOps
	BPFProgTypeSkSkb
	BPFProgTypeCgroupDevice
	BPFProgTypeSkMsg
	BPFProgTypeRawTracepoint
	BPFProgTypeCgroupSockAddr
	BPFProgTypeLwtSeg6Local
	BPFProgTypeLircMode2
	BPFProgTypeSkReuseport
	BPFProgTypeFlowDissector
	BPFProgTypeCgroupSysctl
	BPFProgTypeRawTracepointWritable
	BPFProgTypeCgroupSockopt
	BPFProgTypeTracing
	BPFProgTypeStructOps
	BPFProgTypeExt
	BPFProgTypeLsm
	BPFProgTypeSkLookup
	BPFProgTypeSyscall
)

func (BPFProgType) String

func (b BPFProgType) String() (str string)

func (BPFProgType) Value

func (b BPFProgType) Value() uint64

type Callbacks

type Callbacks struct {
	Log        func(level int, msg string)
	LogFilters []func(libLevel int, msg string) bool
}

Callbacks stores the callbacks to be used by libbpfgo

type IterOpts

type IterOpts struct {
	MapFd           int
	CgroupIterOrder BPFCgroupIterOrder
	CgroupFd        int
	CgroupId        uint64
	Tid             int
	Pid             int
	PidFd           int
}

type LibbpfStrictMode

type LibbpfStrictMode uint32

LibbpfStrictMode is an enum as defined in https://github.com/libbpf/libbpf/blob/2cd2d03f63242c048a896179398c68d2dbefe3d6/src/libbpf_legacy.h#L23

const (
	LibbpfStrictModeAll               LibbpfStrictMode = C.LIBBPF_STRICT_ALL
	LibbpfStrictModeNone              LibbpfStrictMode = C.LIBBPF_STRICT_NONE
	LibbpfStrictModeCleanPtrs         LibbpfStrictMode = C.LIBBPF_STRICT_CLEAN_PTRS
	LibbpfStrictModeDirectErrs        LibbpfStrictMode = C.LIBBPF_STRICT_DIRECT_ERRS
	LibbpfStrictModeSecName           LibbpfStrictMode = C.LIBBPF_STRICT_SEC_NAME
	LibbpfStrictModeNoObjectList      LibbpfStrictMode = C.LIBBPF_STRICT_NO_OBJECT_LIST
	LibbpfStrictModeAutoRlimitMemlock LibbpfStrictMode = C.LIBBPF_STRICT_AUTO_RLIMIT_MEMLOCK
	LibbpfStrictModeMapDefinitions    LibbpfStrictMode = C.LIBBPF_STRICT_MAP_DEFINITIONS
)

func (LibbpfStrictMode) String

func (b LibbpfStrictMode) String() (str string)

type LinkType

type LinkType int
const (
	Tracepoint LinkType = iota
	RawTracepoint
	Kprobe
	Kretprobe
	LSM
	PerfEvent
	Uprobe
	Uretprobe
	Tracing
	XDP
	Cgroup
	CgroupLegacy
	Netns
	Iter
)

type MapFlag

type MapFlag uint32
const (
	MapFlagUpdateAny     MapFlag = iota // create new element or update existing
	MapFlagUpdateNoExist                // create new element if it didn't exist
	MapFlagUpdateExist                  // update existing element
	MapFlagFLock                        // spin_lock-ed map_lookup/map_update
)

type MapType

type MapType uint32
const (
	MapTypeUnspec MapType = iota
	MapTypeHash
	MapTypeArray
	MapTypeProgArray
	MapTypePerfEventArray
	MapTypePerCPUHash
	MapTypePerCPUArray
	MapTypeStackTrace
	MapTypeCgroupArray
	MapTypeLRUHash
	MapTypeLRUPerCPUHash
	MapTypeLPMTrie
	MapTypeArrayOfMaps
	MapTypeHashOfMaps
	MapTypeDevMap
	MapTypeSockMap
	MapTypeCPUMap
	MapTypeXSKMap
	MapTypeSockHash
	MapTypeCgroupStorage
	MapTypeReusePortSockArray
	MapTypePerCPUCgroupStorage
	MapTypeQueue
	MapTypeStack
	MapTypeSKStorage
	MapTypeDevmapHash
	MapTypeStructOps
	MapTypeRingbuf
	MapTypeInodeStorage
	MapTypeTaskStorage
	MapTypeBloomFilter
)

func (MapType) String

func (m MapType) String() string

type Module

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

func NewModuleFromBuffer

func NewModuleFromBuffer(bpfObjBuff []byte, bpfObjName string) (*Module, error)

func NewModuleFromBufferArgs

func NewModuleFromBufferArgs(args NewModuleArgs) (*Module, error)

func NewModuleFromFile

func NewModuleFromFile(bpfObjPath string) (*Module, error)

func NewModuleFromFileArgs

func NewModuleFromFileArgs(args NewModuleArgs) (*Module, error)

func (*Module) BPFLoadObject

func (m *Module) BPFLoadObject() error

func (*Module) Close

func (m *Module) Close()

func (*Module) GetMap

func (m *Module) GetMap(mapName string) (*BPFMap, error)

func (*Module) GetProgram

func (m *Module) GetProgram(progName string) (*BPFProg, error)

func (*Module) InitGlobalVariable

func (m *Module) InitGlobalVariable(name string, value interface{}) error

InitGlobalVariable sets global variables (defined in .data or .rodata) in bpf code. It must be called before the BPF object is loaded.

func (*Module) InitPerfBuf

func (m *Module) InitPerfBuf(mapName string, eventsChan chan []byte, lostChan chan uint64, pageCnt int) (*PerfBuffer, error)

func (*Module) InitRingBuf

func (m *Module) InitRingBuf(mapName string, eventsChan chan []byte) (*RingBuffer, error)

func (*Module) Iterator

func (m *Module) Iterator() *BPFObjectIterator

func (*Module) TcHookInit

func (m *Module) TcHookInit() *TcHook

type NewModuleArgs

type NewModuleArgs struct {
	KConfigFilePath string
	BTFObjPath      string
	BPFObjName      string
	BPFObjPath      string
	BPFObjBuff      []byte
	SkipMemlockBump bool
}

type PerfBuffer

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

func (*PerfBuffer) Close

func (pb *PerfBuffer) Close()

func (*PerfBuffer) Poll

func (pb *PerfBuffer) Poll(timeout int)

Poll will wait until timeout in milliseconds to gather data from the perf buffer.

func (*PerfBuffer) Start deprecated

func (pb *PerfBuffer) Start()

Deprecated: use PerfBuffer.Poll() instead.

func (*PerfBuffer) Stop

func (pb *PerfBuffer) Stop()

type RingBuffer

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

func (*RingBuffer) Close

func (rb *RingBuffer) Close()

func (*RingBuffer) Poll

func (rb *RingBuffer) Poll(timeout int)

Poll will wait until timeout in milliseconds to gather data from the ring buffer.

func (*RingBuffer) Start deprecated

func (rb *RingBuffer) Start()

Deprecated: use RingBuffer.Poll() instead.

func (*RingBuffer) Stop

func (rb *RingBuffer) Stop()

type Symbol

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

type TcAttachPoint

type TcAttachPoint uint32
const (
	BPFTcIngress       TcAttachPoint = C.BPF_TC_INGRESS
	BPFTcEgress        TcAttachPoint = C.BPF_TC_EGRESS
	BPFTcIngressEgress TcAttachPoint = C.BPF_TC_INGRESS | C.BPF_TC_EGRESS
	BPFTcCustom        TcAttachPoint = C.BPF_TC_CUSTOM
)

type TcFlags

type TcFlags uint32
const (
	BpfTcFReplace TcFlags = C.BPF_TC_F_REPLACE
)

type TcHook

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

func (*TcHook) Attach

func (hook *TcHook) Attach(tcOpts *TcOpts) error

func (*TcHook) Create

func (hook *TcHook) Create() error

func (*TcHook) Destroy

func (hook *TcHook) Destroy() error

func (*TcHook) Detach

func (hook *TcHook) Detach(tcOpts *TcOpts) error

func (*TcHook) GetInterfaceIndex

func (hook *TcHook) GetInterfaceIndex() int

func (*TcHook) Query

func (hook *TcHook) Query(tcOpts *TcOpts) error

func (*TcHook) SetAttachPoint

func (hook *TcHook) SetAttachPoint(attachPoint TcAttachPoint)

func (*TcHook) SetInterfaceByIndex

func (hook *TcHook) SetInterfaceByIndex(ifaceIdx int)

func (*TcHook) SetInterfaceByName

func (hook *TcHook) SetInterfaceByName(ifaceName string) error

func (*TcHook) SetParent

func (hook *TcHook) SetParent(a int, b int)

type TcOpts

type TcOpts struct {
	ProgFd   int
	Flags    TcFlags
	ProgId   uint
	Handle   uint
	Priority uint
}

Directories

Path Synopsis
helpers module

Jump to

Keyboard shortcuts

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