gobpfld

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2022 License: MIT Imports: 28 Imported by: 2

README

GoBPFLD

GoDoc

GoBPFLD is a pure go eBPF loader/userspace library as an alternative to using gobpf which requires CGO to work. The goal of GoBPFLD is to provide a library for eBPF development which is comparable to libbpf(C library) but without CGO which improves the development experience.

WARNING GoBPFLD is currently not (yet) feature complete, and may lack critical features for some eBPF program types. This library is still fairly young and the API is still subject to change.

WARNING GoBPFLD has only been tested on X86_64 machines, due to the nature of interacting with the kernel via syscalls it is likely that architecture dependant bugs may arise. For now it is not recommended to trust this library with any architecture other than X86_64.

Requirements

eBPF is a Linux specific feature (ignoring userspace eBPF) which was introduced in kernel 3.18. This means that for this library to work the executable must be run on a Linux machine with 3.18 or above.

This library detects (at runtime) which version of the linux kernel is being used. Higher level features will attempt to fallback to still offer as much functionality as possible. This library attempts to catch the usage of unsupported features and return nice verbose human readable errors. If this fails the kernel will still return an error, which is less verbose. For some features running on a newer kernel version may be required. You can find a great overview of features per kernel version here.

Security

Programs which interact with the kernel via the bpf syscall need to have extra capabilities if they are not running as the root user. In particular the CAP_BPF or CAP_SYS_ADMIN capability. CAP_BPF is available since kernel 5.8 and is preferred since it has the least privileges needed. If you run on a kernel version lower than 5.8, CAP_SYS_ADMIN is the only option you have to grant non-root users access to the bpf syscall. In this case it might be a better option to run you program as root and switch to a non-root user when not using the bpf syscall. This can be accomplished by using the seteuid syscall via the syscall.Seteuid function.

Programs that use tracepoints, kprobes, and/or uprobes also require the CAP_SYS_ADMIN capability in kernels versions below 5.8. Since kernel 5.8 the CAP_PERFMON capability can be assigned which specifically grants the permissions required and no more.

There are a number of eBPF related vulnerabilities known so far: CVE-2016-2383, CVE-2016-4557, CVE-2021-20268. The kernel has the ability to JIT eBPF programs which translates the eBPF instruction into actual machine code to be executed. Not only that but it executes in the kernel with all associated privileges. To ensure that eBPF programs don't access memory outside the eBPF vm, the kernel attempts to detect illegal code, if the verifier fails we have security issues. Programs using this library therefor must be sure that the eBPF programs don't contain user input without sanitization. Even normal features of eBPF such as packet manipulation or dropping may be considered security issues in some cases. More info about eBPF JIT and eBPF hardening can be found in the cilium reference guide

Features

  • Pure Go - no CGO, missing libraries, forced dynamic linking, ect.
  • Load pre-compiled eBPF programs from ELF files
  • eBPF bytecode decoder
  • eBPF instructions to bytecode encoder
  • eBPF clang style assembly parser/assembler
  • Loading eBPF maps into the kernel
  • Loading eBPF programs into the kernel
  • Interacting with eBPF maps (lookup, set, delete, batch-lookup, batch-set, and batch-delete)
  • Map iterators
  • Attaching eBPF programs to network interfaces as XDP programs
  • Attaching eBPF programs to sockets
  • Attaching eBPF programs to tracepoints, kprobes, and uprobes
  • XSK/AF_XDP socket support
  • Go wrappers around all bpf syscall commands
  • XDP program testing
  • Array map memory mapping
  • BTF loading

Motivation

GoBPFLD is a loader/library to make eBPF tool development in Go smoother. It is not a standalone tool like bpftool but rather more like libbpf or gobpf.

The kernel developers also maintain libbpf which is the most up-to-date library for eBPF program loading. This is great for C or C++ developers, but we userspace programmers would like to also use different programming languages. The most common solution is to create a wrapper library around the C API. In the case of go we would use CGO for this, the downside of CGO is that it has negative effects on features of Go like static linking, dependency management, and cross-compiling. GoBPFLD is written in pure Go so we still retain all the benefits and feature we love in Go.

Once catch is that there currently is no way(that I know of) to generate eBPF programs from higher level programing languages other than C. Altho technically possible since LLVM is used in clang to compile the programs, it has not yet been done. This means that you will still need to compile any eBPF programs with a clang pipeline if you are not willing to create eBPF programs in eBPF-assembly. But since the eBPF programs are a separate code base the generated ELF files can just be embedded in your Go application or shipped and loaded from file without compromise.

In a number of use cases you might want to generate an eBPF program completely dynamically, a classic example of this is tcpdump. In this case no C code is required at all. As far as I know there are no libraries with specific support for this, and creating the required eBPF bytecode yourself is quite hard. The ebpf sub-package attempts to improve the process of crafting your own dynamic programs by providing an abstraction between the instructions and byte representation. The package allows you to decompile a program into its instructions, every instruction has a Go type so properties can be changed without worrying about the binary representation. These instruction types can be used to craft a program fully from Go and to recompile them into a program which can be loaded. The package also provides a assembler which is compatible with the text assembly used by clang, thus allowing you to write your program as an assembly string and turn that into a program. Using the text based assembler can be easier since it allows you to use labels without manually tracking offsets in the instructions. So developers will require some knowledge about the eBPF instruction set, but should be able to focus more on the the functionality of their own application.

Examples

The cmd/examples directory contains examples programs which demonstrate how to use this library, its capabilities, and the capabilities of eBPF.

TODO/Roadmap/Scope limits

As mentioned earlier the first milestone/focus area of this project has been on implementing basic eBPF and XDP related features, and thus is missing a lot of stuff. At some point the API of this library should become backwards compatible along the lines of the go 1 compatibility promise, though I don't yet know when this will be.

This is a list of features to be added later, just to keep track.

Must have

Features/tasks in this list are commonly used/requested because they are used in common use cases / scenarios.

  • Data relocation from ELF files(static global variables)
  • Attach to sockets
  • Attach to kprobes
  • Attach to kretprobes
  • Attach to uprobes
  • Attach to tracepoints
  • Tailcall support
  • Map pinning and unpinning
  • Bulk map ops
  • Program pinning and unpinning
  • BPF2BPF function calls
  • Map iterator construct (looping over maps is very common)
  • Support perf event array maps
  • Support stack trace maps
  • Support dev and devhash map
  • Support sock and sockhash map
  • Support cpu map
  • Support queue map
  • Support stack map
  • Support ringbuffer map
  • Attach to tc (traffic control)
  • Linux kernel version detection (so programs can programmatically decide which features they can use, then error, warn or be backwards compatible)
  • Library testing framework (We need some way to guarantee the library works, and stays working)
    • Library+kernel testing, verify the ABI is implemented correctly
    • Fuzzing, we parse a lot like ELF files, eBPF programs, assembly. Panics are not desirable.
    • Race condition testing
    • Cross architecture testing, QEMU supports emulation of other architectures which we should be able to use to test architectures like ARM and RISC-V without dedicated testing hardware.
    • Cross kernel version testing, we should run the tests on a number of kernels, both older and newer, to test version dependant fallbacks and kernel ABI issues.
Should have

Features/tasks in this list are not critical for most users but still important for a significant portion.

  • XSK/AF_XDP support (useful for kernel bypass and packet capture)
  • Map access via memory mapping https://lwn.net/Articles/805043/ (could improve performance)
  • Map in map support (useful but not widely used)
  • XSK multiple sockets per netdev,queue pair (currently only one socket per pair is supported)
  • (partially implemented) Program testing (Being able to unit test an XDP program would be great)
  • Support reuse port sock array map
  • Support cGroup storage maps
  • Support SK storage map
  • Support struct ops map
  • Support inode storage map
  • Support task storage map
  • Support for LWT programs (Light weight tunnel)
  • BTF support (So we have more type info to work with, some newer features require BTF support in the loader)
  • ARM64 support / testing (ARM is on the rise)
  • ARM32 support / testing (ARM is on the rise)
  • ELF symbols to offset functionality for perf package
Could have

Features/tasks in this list are cool to have but secondary to the primary goal of this project.

  • Built-in XSK kernel program (like libbpf) (only useful for people intrested in full kernel bypass without additional logic in XDP/eBPF)
  • RISC-V support / testing (RISC-V has promise, would be cool, but not yet widely used)
  • x86_32 support / testing (32 bit is not very popular anymore, but maybe still useful for IOT or raspberry pi like machines)
  • Userspace VM (It would be cool to be able to run eBPF in Go, for testing or as plugin mechanism like LUA and WASM. But not an important feature related to eBPF loading)
  • Userspace map caching (Depending on the map flags and eBPF program, maps can be cached in the userspace without requesting value via syscalls (userspace -> kernel only maps))
Won't have

Features/tasks in this list are out of the scope of the project. We have to draw the line somewhere to avoid feature creep.

  • cBPF support (cBPF is not even supported by Linux anymore, just converted to eBPF, which you can also do with tools for any exiting program)

Documentation

Index

Constants

View Source
const BPFSysPath = "/sys/fs/bpf/"

BPFSysPath is the path to the bpf FS used to pin objects to

Variables

View Source
var (
	// ErrProgramNotLoaded is returned when attempting to attach a non-loaded program
	ErrProgramNotLoaded = errors.New("the program is not yet loaded and thus can't be attached")
	// ErrProgramNotXDPType is returned when attempting to attach a non-XDP program to a netdev
	ErrProgramNotXDPType = errors.New("the program is not loaded as an XDP program and thus can't be " +
		"attached as such")
	// ErrNetlinkAlreadyHasXDPProgram is returned when attempting to attach a program to an
	// netdev that already has an XDP program attached
	ErrNetlinkAlreadyHasXDPProgram = errors.New("the netlink already has an XDP program attached")
)
View Source
var BTFKernelFuncSize = int(unsafe.Sizeof(BTFKernelFunc{}))

BTFKernelFuncSize size of BTFKernelFunc in bytes

View Source
var BTFKernelLineSize = int(unsafe.Sizeof(BTFKernelLine{}))

BTFKernelLineSize size of BTFKernelLine in bytes

View Source
var ErrIteratorDone = errors.New("iterator is done")

ErrIteratorDone indicates that Next has been called on an iterator which is done iterating

View Source
var ErrMissingBTFData = errors.New("missing indicated bytes in slice")

ErrMissingBTFData is returned when a datastructure indicates that there should be additional bytes but

the given bytes slice doesn't contain any.
View Source
var ErrObjNameToLarge = errors.New("object name to large")

ErrObjNameToLarge is returned when a given string or byte slice is to large. The kernel limits names to 15 usable bytes plus a null-termination char

View Source
var ErrProgramNotSocketFilterType = errors.New("the program is not loaded as an socket filter program and " +
	"thus can't be attached as such")

ErrProgramNotSocketFilterType is returned when attempting to attach a non-socket filter program to a socket.

Functions

func GetNetDevQueueCount

func GetNetDevQueueCount(netdev string) (int, error)

GetNetDevQueueCount uses the /sys/class/net/<dev>/queues/ directory to figure out how many queues a network device has. Knowing the number of queues is critical when binding XSK sockets to a network device.

func MapIterForEach

func MapIterForEach(iter MapIterator, key, value interface{}, callback func(key, value interface{}) error) error

MapIterForEach fully loops over the given iterator, calling the callback for each entry. This offers less control but requires less external setup.

MapIterForEach accepts non-pointer values for key and value in which case they will only be used for type information. If callback returns an error the iterator will stop iterating and return the error from callback. Callback is always invoked with pointer types, even if non-pointer types were supplied to key and value.

func PinFD

func PinFD(relativePath string, fd bpfsys.BPFfd) error

PinFD pins an eBPF object(map, program, link) identified by the given `fd` to the given `relativePath` relative to the `BPFSysPath` on the BPF FS.

This function is exposed so custom program or map implementations can use outside of this library. However, it is recommendd to use the BPFProgram.Pin and AbstractMap.Pin functions if gobpfld types are used.

func UnpinFD

func UnpinFD(relativePath string, deletePin bool) (bpfsys.BPFfd, error)

UnpinFD gets the fd of an eBPF object(map, program, link) which is pinned at the given `relativePath` relative to the `BPFSysPath` on the BPF FS. If `deletePin` is true, this function will remove the pin from the BPF FS after successfully getting it.

This function is exposed so custom program or map implementations can use outside of this library. However, it is recommend to use the BPFProgram.Unpin and AbstractMap.Unpin functions if gobpfld types are used.

TODO make this function unexported and create an UnpinMap and UnpinProgram function which will automatically recreate

the proper maps. (also necessary to handle map registration properly)

Types

type AbstractBPFProgram added in v0.5.0

type AbstractBPFProgram struct {
	// The program type as which it was loaded into the kernel
	ProgramType bpftypes.BPFProgType
	// Name of the program
	Name    ObjName
	License string
	// The actual instructions of the program
	Instructions []ebpf.RawInstruction
	// Locations where map fds need to be inserted into the
	// program before loading
	MapFDLocations map[string][]uint64
	Maps           map[string]BPFMap

	BTF      *BTF
	BTFLines []BTFKernelLine
	BTFFuncs []BTFKernelFunc
	// contains filtered or unexported fields
}

func NewAbstractBPFProgram added in v0.5.0

func NewAbstractBPFProgram() AbstractBPFProgram

func (*AbstractBPFProgram) DecodeToReader added in v0.5.0

func (p *AbstractBPFProgram) DecodeToReader(w io.Writer) error

DecodeToReader decodes the eBPF program and writes the human readable format to the provided w. The output that is generated is inspired by the llvm-objdump -S output format of eBPF programs

func (*AbstractBPFProgram) Fd added in v0.5.0

func (p *AbstractBPFProgram) Fd() (bpfsys.BPFfd, error)

func (AbstractBPFProgram) GetAbstractProgram added in v0.6.0

func (p AbstractBPFProgram) GetAbstractProgram() AbstractBPFProgram

func (*AbstractBPFProgram) Pin added in v0.5.0

func (p *AbstractBPFProgram) Pin(relativePath string) error

Pin pins the program to a location in the bpf filesystem, since the file system now also holds a reference to the program, the original creator of the program can terminate without triggering the program to be closed as well. A program can be unpinned from the bpf FS by another process thus transferring it or persisting it across multiple runs of the same program.

type AbstractMap

type AbstractMap struct {
	// The name of map. This value is passed to the kernel, it is limited to 15 characters. Its use is limited
	// and mostly to aid diagnostic tools which inspect the BPF subsystem. For primary identification the ID or FD
	// should be used.
	Name ObjName
	// Definition describes the properties of this map
	Definition BPFMapDef
	// A reference to the BTF which contains the type of this map.
	BTF *BTF
	// The type of the map.
	BTFMapType BTFMap

	// Initial contents of the map, set just after loading
	InitialData map[interface{}]interface{}
	// contains filtered or unexported fields
}

AbstractMap is a base struct which implements BPFMap however it lacks any features for interacting with the map, these need to be implemented by a specific map type which can embed this type to reduce code dupplication. This type is exported so users of the library can also embed this struct in application specific implementation.

func (*AbstractMap) GetBTF added in v0.6.0

func (m *AbstractMap) GetBTF() *BTF

func (*AbstractMap) GetBTFMapType added in v0.6.0

func (m *AbstractMap) GetBTFMapType() BTFMap

func (*AbstractMap) GetDefinition

func (m *AbstractMap) GetDefinition() BPFMapDef

func (*AbstractMap) GetFD

func (m *AbstractMap) GetFD() bpfsys.BPFfd

func (*AbstractMap) GetInitialData added in v0.6.0

func (m *AbstractMap) GetInitialData() map[interface{}]interface{}

func (*AbstractMap) GetName

func (m *AbstractMap) GetName() ObjName

func (*AbstractMap) IsLoaded

func (m *AbstractMap) IsLoaded() bool

func (*AbstractMap) Pin

func (m *AbstractMap) Pin(relativePath string) error

Pin pins the map to a location in the bpf filesystem, since the file system now also holds a reference to the map the original creator of the map can terminate without triggering the map to be closed as well. A map can be unpinned from the bpf FS by another process thus transferring it or persisting it across multiple runs of the same program.

func (*AbstractMap) Unpin

func (m *AbstractMap) Unpin(relativePath string, deletePin bool) error

Unpin captures the file descriptor of the map at the given 'relativePath' from the kernel. The definition in this map must match the definition of the pinned map, otherwise this function will return an error since mismatched definitions might cause seemingly unrelated bugs in other functions. If 'deletePin' is true the bpf FS pin will be removed after successfully loading the map, thus transferring ownership of the map in a scenario where the map is not shared between multiple programs. Otherwise the pin will keep existing which will cause the map to not be deleted when this program exits.

type ArrayMap added in v0.4.0

type ArrayMap struct {
	AbstractMap
	// contains filtered or unexported fields
}

ArrayMap is a map which has a integer key from 0 to MaxEntries. It is a generic map type so the value can be any type.

func (*ArrayMap) Close added in v0.6.0

func (m *ArrayMap) Close() error

Close closes the file descriptor associate with the map, this will cause the map to unload from the kernel if it is not still in use by a eBPF program, bpf FS, or a userspace program still holding a fd to the map.

func (*ArrayMap) Get added in v0.4.0

func (m *ArrayMap) Get(key uint32, value interface{}) error

func (*ArrayMap) GetBatch added in v0.4.0

func (m *ArrayMap) GetBatch(
	keys []uint32,
	values interface{},
) (
	count int,
	partial bool,
	err error,
)

GetBatch fills the keys slice and values array/slice with the keys and values inside the map. The keys slice and values array/slice must have the same length. The key and value of an entry is has the same index, so for example the value for keys[2] is in values[2]. Count is the amount of entries returns, partial is true if not all elements of keys and values could be set.

This function is intended for small maps which can be read into userspace all at once since GetBatch can only read from the beginning of the map. If the map is to large to read all at once a iterator should be used instead of the Get or GetBatch function.

func (*ArrayMap) Iterator added in v0.4.0

func (m *ArrayMap) Iterator() MapIterator

func (*ArrayMap) Load added in v0.4.0

func (m *ArrayMap) Load() error

func (*ArrayMap) Set added in v0.4.0

func (m *ArrayMap) Set(key uint32, value interface{}, flags bpfsys.BPFAttrMapElemFlags) error

func (*ArrayMap) SetBatch added in v0.4.0

func (m *ArrayMap) SetBatch(
	keys []uint32,
	values interface{},
	flags bpfsys.BPFAttrMapElemFlags,
) (
	count int,
	err error,
)

type ArrayOfMapsMap added in v0.5.0

type ArrayOfMapsMap struct {
	AbstractMap

	// InnerMapDef is the definition of the inner map
	// TODO: Once BTF is implemented we can infer this map type from the BTF debug symbols
	InnerMapDef BPFMapDef
	// contains filtered or unexported fields
}

ArrayOfMapsMap is a map which has a integer key from 0 to MaxEntries. The value type must be any loaded BPF map

func (*ArrayOfMapsMap) Close added in v0.6.0

func (m *ArrayOfMapsMap) Close() error

Close closes the file descriptor associate with the map, this will cause the map to unload from the kernel if it is not still in use by a eBPF program, bpf FS, or a userspace program still holding a fd to the map.

func (*ArrayOfMapsMap) Get added in v0.5.0

func (m *ArrayOfMapsMap) Get(key uint32) (BPFMap, error)

func (*ArrayOfMapsMap) Iterator added in v0.5.0

func (m *ArrayOfMapsMap) Iterator() MapIterator

func (*ArrayOfMapsMap) Load added in v0.5.0

func (m *ArrayOfMapsMap) Load() error

func (*ArrayOfMapsMap) Set added in v0.5.0

func (m *ArrayOfMapsMap) Set(key uint32, value BPFMap, flags bpfsys.BPFAttrMapElemFlags) error

type BPFELF

type BPFELF struct {
	ByteOrder binary.ByteOrder
	// Programs contained within the ELF
	Programs map[string]BPFProgram
	// Maps defined in the ELF
	Maps map[string]BPFMap
	// BTF contains type and debugging information regarding the programs and maps.
	BTF *BTF
}

BPFELF is the result of parsing an eBPF ELF file. It can contain multiple programs and maps.

func LoadProgramFromELF

func LoadProgramFromELF(r io.ReaderAt, settings ELFParseSettings) (BPFELF, error)

type BPFMap

type BPFMap interface {
	GetName() ObjName
	GetFD() bpfsys.BPFfd
	IsLoaded() bool
	GetDefinition() BPFMapDef
	GetBTF() *BTF
	GetBTFMapType() BTFMap
	GetInitialData() map[interface{}]interface{}

	// Pin pins the map to a location in the bpf filesystem, since the file system now also holds a reference
	// to the map the original creator of the map can terminate without triggering the map to be closed as well.
	// A map can be unpinned from the bpf FS by another process thus transferring it or persisting it across
	// multiple runs of the same program.
	Pin(relativePath string) error

	// Unpin captures the file descriptor of the map at the given 'relativePath' from the kernel.
	// The definition in this map must match the definition of the pinned map, otherwise this function
	// will return an error since mismatched definitions might cause seemingly unrelated bugs in other functions.
	// If 'deletePin' is true the bpf FS pin will be removed after successfully loading the map, thus transferring
	// ownership of the map in a scenario where the map is not shared between multiple programs.
	// Otherwise the pin will keep existing which will cause the map to not be deleted when this program exits.
	Unpin(relativePath string, deletePin bool) error

	// Load validates and loads the userspace map definition into the kernel.
	Load() error

	// Close closes the file descriptor associated with the map. The map can't be used after it is closed.
	// If this is the last file descriptor pointing to the map, the map will be unloaded from the kernel.
	// If a map is pinned to the filesystem, in use by a bpf program or referenced any other way it will stay loaded
	// until all references are closed/removed.
	Close() error
}

func MapFromFD added in v0.5.0

func MapFromFD(fd bpfsys.BPFfd) (BPFMap, error)

MapFromFD creates a BPFMap object from a map that is already loaded into the kernel and for which we already have a file descriptor.

func MapFromID

func MapFromID(id uint32) (BPFMap, error)

MapFromID creates a BPFMap object from a map that is already loaded into the kernel.

type BPFMapDef

type BPFMapDef struct {
	// Type describes map type this map is
	Type bpftypes.BPFMapType
	// KeySize is the size of the map key in bytes
	KeySize uint32
	// ValueSize is the size of the map value in bytes
	ValueSize uint32
	// MaxEntries is the maximum amount of entries in a map. Depending on the map type and flags, memory for all of
	// these entries might be allocated on map creation or dynamically when inserting.
	MaxEntries uint32
	// Flags can be used to ask the kernel for special behavior, not all flags are allowed on all map types.
	Flags bpftypes.BPFMapFlags
}

func (BPFMapDef) Equal

func (def BPFMapDef) Equal(other BPFMapDef) bool

Equal checks if two map definitions are functionally identical

func (BPFMapDef) Validate

func (def BPFMapDef) Validate() error

Validate checks if the map definition is valid, the kernel also does these checks but if the kernel finds an error it doesn't return a nice error message. This give a better user experience.

type BPFProgInfo

type BPFProgInfo struct {
	Type            bpftypes.BPFProgType
	ID              uint32
	Tag             [bpftypes.BPF_TAG_SIZE]byte
	JitedProgInsns  []ebpf.RawInstruction
	XlatedProgInsns []ebpf.RawInstruction
	LoadTime        time.Time
	CreatedByUID    uint32
	MapIDs          []uint32
	Name            ObjName
	IfIndex         uint32
	Flags           bpftypes.BPFProgInfoFlags
	NetNSDev        uint64
	NetNSIno        uint64
	JitedKsyms      []uint64
	JitedFuncLens   []uint32
	BTFID           uint32
	FuncInfo        []bpftypes.BPFFuncInfo
	LineInfo        []bpftypes.BPFLineInfo
	JitedLineInfo   []bpftypes.BPFLineInfo
	ProgTags        [][bpftypes.BPF_TAG_SIZE]byte
	RunTimeNs       uint64
	RunCnt          uint64
	RecursionMisses uint64
}

BPFProgInfo is a more easy to use version of the bpftypes.BPFProgInfo the main difference being that this struct contains the actual from the kernel not just pointers to them

func GetLoadedPrograms

func GetLoadedPrograms() ([]BPFProgInfo, error)

GetLoadedPrograms returns a slice of info object about all loaded bpf programs

func GetProgramInfo

func GetProgramInfo(fd bpfsys.BPFfd) (*BPFProgInfo, error)

type BPFProgram

type BPFProgram interface {
	Fd() (bpfsys.BPFfd, error)
	Pin(relativePath string) error
	Unpin(relativePath string, deletePin bool) error
	GetAbstractProgram() AbstractBPFProgram
}

func BPFProgramFromAbstract added in v0.5.0

func BPFProgramFromAbstract(abstract AbstractBPFProgram) BPFProgram

func NewBPFProgram

func NewBPFProgram(progType bpftypes.BPFProgType) BPFProgram

type BPFProgramXDPLinkDetachSettings

type BPFProgramXDPLinkDetachSettings struct {
	// Name of the network interface from which the program should detach
	InterfaceName string
	// If true, the program will be detached from all network interfaces
	All bool
}

type BTF added in v0.6.0

type BTF struct {
	// Parsed type information, the index of the types is equal to their ID's
	Types []BTFType

	// Parsed Lines information with ELF section relative instruction offsets
	Lines []BTFLine
	// Parsed function information with ELF section relative instruction offsets
	Funcs []BTFFunc

	StringsTbl StringTbl
	// contains filtered or unexported fields
}

BTF Type and String info

func NewBTF added in v0.6.0

func NewBTF() *BTF

func (*BTF) Fd added in v0.6.0

func (btf *BTF) Fd() (bpfsys.BPFfd, error)

func (*BTF) Load added in v0.6.0

func (btf *BTF) Load(opts BTFLoadOpts) (string, error)

func (*BTF) ParseBTF added in v0.6.0

func (btf *BTF) ParseBTF(btfBytes []byte) error

ParseBTF parses BTF type and string data.

func (*BTF) ParseBTFExt added in v0.6.0

func (btf *BTF) ParseBTFExt(btfBytes []byte) error

ParseBTFExt parses

func (*BTF) SerializeBTF added in v0.6.0

func (btf *BTF) SerializeBTF() ([]byte, error)

SerializeBTF takes the contents BTF.Types and serializes it into a byte slice which can be loaded into the kernel

type BTFArrayType added in v0.6.0

type BTFArrayType struct {

	// The type of the array values
	Type BTFType

	// The type of the array index
	IndexType BTFType

	// The number of elements in the array
	NumElements uint32
	// contains filtered or unexported fields
}

BTFArrayType is the type for KIND_ARR, which represents a array

func (*BTFArrayType) GetID added in v0.6.0

func (ct *BTFArrayType) GetID() int

func (*BTFArrayType) GetKind added in v0.6.0

func (ct *BTFArrayType) GetKind() BTFKind

func (*BTFArrayType) GetName added in v0.6.0

func (ct *BTFArrayType) GetName() string

func (*BTFArrayType) Serialize added in v0.6.0

func (t *BTFArrayType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

func (BTFArrayType) ToBTFType added in v0.6.0

func (ct BTFArrayType) ToBTFType(strTbl *StringTbl) btfType

type BTFConstType added in v0.6.0

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

func (*BTFConstType) GetID added in v0.6.0

func (ct *BTFConstType) GetID() int

func (*BTFConstType) GetKind added in v0.6.0

func (ct *BTFConstType) GetKind() BTFKind

func (*BTFConstType) GetName added in v0.6.0

func (ct *BTFConstType) GetName() string

func (*BTFConstType) Serialize added in v0.6.0

func (t *BTFConstType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

func (BTFConstType) ToBTFType added in v0.6.0

func (ct BTFConstType) ToBTFType(strTbl *StringTbl) btfType

type BTFDataSecType added in v0.6.0

type BTFDataSecType struct {
	Variables []BTFDataSecVariable
	// contains filtered or unexported fields
}

func (*BTFDataSecType) GetID added in v0.6.0

func (ct *BTFDataSecType) GetID() int

func (*BTFDataSecType) GetKind added in v0.6.0

func (ct *BTFDataSecType) GetKind() BTFKind

func (*BTFDataSecType) GetName added in v0.6.0

func (ct *BTFDataSecType) GetName() string

func (*BTFDataSecType) Serialize added in v0.6.0

func (t *BTFDataSecType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

func (BTFDataSecType) ToBTFType added in v0.6.0

func (ct BTFDataSecType) ToBTFType(strTbl *StringTbl) btfType

type BTFDataSecVariable added in v0.6.0

type BTFDataSecVariable struct {
	Type BTFType

	Offset uint32
	Size   uint32
	// contains filtered or unexported fields
}

type BTFDeclTagType added in v0.6.0

type BTFDeclTagType struct {
	ComponentIdx uint32
	// contains filtered or unexported fields
}

BTFDeclTagType The name_off encodes btf_decl_tag attribute string. The type should be struct, union, func, var or typedef. For var or typedef type, btf_decl_tag.component_idx must be -1. For the other three types, if the btf_decl_tag attribute is applied to the struct, union or func itself, btf_decl_tag.component_idx must be -1. Otherwise, the attribute is applied to a struct/union member or a func argument, and btf_decl_tag.component_idx should be a valid index (starting from 0) pointing to a member or an argument.

func (*BTFDeclTagType) GetID added in v0.6.0

func (ct *BTFDeclTagType) GetID() int

func (*BTFDeclTagType) GetKind added in v0.6.0

func (ct *BTFDeclTagType) GetKind() BTFKind

func (*BTFDeclTagType) GetName added in v0.6.0

func (ct *BTFDeclTagType) GetName() string

func (*BTFDeclTagType) Serialize added in v0.6.0

func (t *BTFDeclTagType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

func (BTFDeclTagType) ToBTFType added in v0.6.0

func (ct BTFDeclTagType) ToBTFType(strTbl *StringTbl) btfType

type BTFEnumOption added in v0.6.0

type BTFEnumOption struct {
	Name  string
	Value int32
}

type BTFEnumType added in v0.6.0

type BTFEnumType struct {
	Options []BTFEnumOption
	// contains filtered or unexported fields
}

func (*BTFEnumType) GetID added in v0.6.0

func (ct *BTFEnumType) GetID() int

func (*BTFEnumType) GetKind added in v0.6.0

func (ct *BTFEnumType) GetKind() BTFKind

func (*BTFEnumType) GetName added in v0.6.0

func (ct *BTFEnumType) GetName() string

func (*BTFEnumType) Serialize added in v0.6.0

func (t *BTFEnumType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

func (BTFEnumType) ToBTFType added in v0.6.0

func (ct BTFEnumType) ToBTFType(strTbl *StringTbl) btfType

type BTFFloatType added in v0.6.0

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

func (*BTFFloatType) GetID added in v0.6.0

func (ct *BTFFloatType) GetID() int

func (*BTFFloatType) GetKind added in v0.6.0

func (ct *BTFFloatType) GetKind() BTFKind

func (*BTFFloatType) GetName added in v0.6.0

func (ct *BTFFloatType) GetName() string

func (*BTFFloatType) Serialize added in v0.6.0

func (t *BTFFloatType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

func (BTFFloatType) ToBTFType added in v0.6.0

func (ct BTFFloatType) ToBTFType(strTbl *StringTbl) btfType

type BTFForwardType added in v0.6.0

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

func (*BTFForwardType) GetID added in v0.6.0

func (ct *BTFForwardType) GetID() int

func (*BTFForwardType) GetKind added in v0.6.0

func (ct *BTFForwardType) GetKind() BTFKind

func (*BTFForwardType) GetName added in v0.6.0

func (ct *BTFForwardType) GetName() string

func (*BTFForwardType) Serialize added in v0.6.0

func (t *BTFForwardType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

func (BTFForwardType) ToBTFType added in v0.6.0

func (ct BTFForwardType) ToBTFType(strTbl *StringTbl) btfType

type BTFFunc added in v0.6.0

type BTFFunc struct {
	// The ELF section in which the function is defined
	Section string
	// Offset in the strings table to the name of the section
	SectionOffset uint32
	// Offset from the start of the ELF section to the function
	InstructionOffset uint32
	// The resolved Type of the Function
	Type BTFType
	// The TypeID, used to resolve Type
	TypeID uint32
}

BTFFunc the go version of bpf_func_info. Which is used to link a instruction offset to a function type. https://elixir.bootlin.com/linux/v5.15.3/source/include/uapi/linux/bpf.h#L6165

func (BTFFunc) ToKernel added in v0.6.0

func (bf BTFFunc) ToKernel() BTFKernelFunc

type BTFFuncProtoParam added in v0.6.0

type BTFFuncProtoParam struct {
	Name string
	Type BTFType
	// contains filtered or unexported fields
}

type BTFFuncProtoType added in v0.6.0

type BTFFuncProtoType struct {
	Params []BTFFuncProtoParam
	// contains filtered or unexported fields
}

func (*BTFFuncProtoType) GetID added in v0.6.0

func (ct *BTFFuncProtoType) GetID() int

func (*BTFFuncProtoType) GetKind added in v0.6.0

func (ct *BTFFuncProtoType) GetKind() BTFKind

func (*BTFFuncProtoType) GetName added in v0.6.0

func (ct *BTFFuncProtoType) GetName() string

func (*BTFFuncProtoType) Serialize added in v0.6.0

func (t *BTFFuncProtoType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

func (BTFFuncProtoType) ToBTFType added in v0.6.0

func (ct BTFFuncProtoType) ToBTFType(strTbl *StringTbl) btfType

type BTFFuncType added in v0.6.0

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

A BTFFuncType defines not a type, but a subprogram (function) whose signature is defined by type. The subprogram is thus an instance of that type. The KIND_FUNC may in turn be referenced by a func_info in the 4.2 .BTF.ext section (ELF) or in the arguments to 3.3 BPF_PROG_LOAD (ABI).

func (*BTFFuncType) GetID added in v0.6.0

func (ct *BTFFuncType) GetID() int

func (*BTFFuncType) GetKind added in v0.6.0

func (ct *BTFFuncType) GetKind() BTFKind

func (*BTFFuncType) GetName added in v0.6.0

func (ct *BTFFuncType) GetName() string

func (*BTFFuncType) Serialize added in v0.6.0

func (t *BTFFuncType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

func (BTFFuncType) ToBTFType added in v0.6.0

func (ct BTFFuncType) ToBTFType(strTbl *StringTbl) btfType

type BTFIntEncoding added in v0.6.0

type BTFIntEncoding uint8

BTFIntEncoding is used to indicate what the integer encodes, used to determine how to pretty print an integer.

const (
	// INT_SIGNED the int should be printed at a signed integer
	INT_SIGNED BTFIntEncoding = 1 << iota
	// INT_CHAR the int should be printed as hex encoded
	INT_CHAR
	// INT_BOOL the int should be printed as a boolean
	INT_BOOL
)

func (BTFIntEncoding) String added in v0.6.0

func (ie BTFIntEncoding) String() string

type BTFIntType added in v0.6.0

type BTFIntType struct {

	// Extra information, mainly useful for pretty printing
	Encoding BTFIntEncoding
	// specifies the starting bit offset to calculate values for this int
	Offset uint8
	// The number of actual bits held by this int type
	Bits uint8
	// contains filtered or unexported fields
}

BTFIntType is the type of KIND_INT, it represents a integer type.

func (*BTFIntType) GetID added in v0.6.0

func (ct *BTFIntType) GetID() int

func (*BTFIntType) GetKind added in v0.6.0

func (ct *BTFIntType) GetKind() BTFKind

func (*BTFIntType) GetName added in v0.6.0

func (ct *BTFIntType) GetName() string

func (*BTFIntType) Serialize added in v0.6.0

func (t *BTFIntType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

func (BTFIntType) ToBTFType added in v0.6.0

func (ct BTFIntType) ToBTFType(strTbl *StringTbl) btfType

type BTFKernelFunc added in v0.6.0

type BTFKernelFunc struct {
	InstructionOffset uint32
	TypeID            uint32
}

BTFKernelFunc is the version of the BTFFunc struct the way the kernel want to see it.

type BTFKernelLine added in v0.6.0

type BTFKernelLine struct {
	InstructionOffset uint32
	FileNameOffset    uint32
	LineOffset        uint32
	LineCol           uint32
}

BTFKernelLine is the version of the BTFLine struct the way the kernel want to see it.

type BTFKind added in v0.6.0

type BTFKind uint8

BTFKind is an enum indicating what kind of type is indicated

const (
	// BTF_KIND_UNKN Unknown
	BTF_KIND_UNKN BTFKind = iota
	// BTF_KIND_INT Integer
	BTF_KIND_INT
	// BTF_KIND_PTR Pointer
	BTF_KIND_PTR
	// BTF_KIND_ARRAY Array
	BTF_KIND_ARRAY
	// BTF_KIND_STRUCT Struct
	BTF_KIND_STRUCT
	// BTF_KIND_UNION Union
	BTF_KIND_UNION
	// BTF_KIND_ENUM Enumeration
	BTF_KIND_ENUM
	// BTF_KIND_FWD Forward
	BTF_KIND_FWD
	// BTF_KIND_TYPEDEF Typedef
	BTF_KIND_TYPEDEF
	// BTF_KIND_VOLATILE Volatile
	BTF_KIND_VOLATILE
	// BTF_KIND_CONST Const
	BTF_KIND_CONST
	// BTF_KIND_RESTRICT Restrict
	BTF_KIND_RESTRICT
	// BTF_KIND_FUNC Function
	BTF_KIND_FUNC
	// BTF_KIND_FUNC_PROTO Function Proto
	BTF_KIND_FUNC_PROTO
	// BTF_KIND_VAR Variable
	BTF_KIND_VAR
	// BTF_KIND_DATASEC Section
	BTF_KIND_DATASEC
	// BTF_KIND_FLOAT Floating point
	BTF_KIND_FLOAT
	// BTF_KIND_DECL_TAG Decl Tag
	BTF_KIND_DECL_TAG
)

func (BTFKind) String added in v0.6.0

func (bk BTFKind) String() string

type BTFLine added in v0.6.0

type BTFLine struct {
	// The ELF section in which the line is defined
	Section string
	// The offset into the strings table for the section name
	SectionOffset uint32
	// Offset from the start of the ELF section to the function
	InstructionOffset uint32
	// The name and path of the source file
	FileName string
	// The offset into the strings table for the file name
	FileNameOffset uint32
	// The full line of source code
	Line string
	// The offset into the strings table for the line.
	LineOffset uint32
	// The line number within the file
	LineNumber uint32
	// The column number within Line of the instruction
	ColumnNumber uint32
}

BTFLine the go version of bpf_line_info. Which maps an instruction to a source code. https://elixir.bootlin.com/linux/v5.15.3/source/include/uapi/linux/bpf.h#L6173

func (BTFLine) ToKernel added in v0.6.0

func (bl BTFLine) ToKernel() BTFKernelLine

type BTFLoadOpts added in v0.6.0

type BTFLoadOpts struct {
	LogLevel bpftypes.BPFLogLevel
	LogSize  int
}

type BTFMap added in v0.6.0

type BTFMap struct {
	Key   BTFType
	Value BTFType
}

BTFMap is a struct which describes a BPF map

type BTFMember added in v0.6.0

type BTFMember struct {
	// Name of the member/field
	Name string
	// Type of the member/field
	Type BTFType

	BitfieldSize uint32
	BitOffset    uint32
	// contains filtered or unexported fields
}

BTFMember is a member of a struct or union.

type BTFPtrType added in v0.6.0

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

BTFPtrType is the type for KIND_PTR, which represents a pointer type which points to some other type.

func (*BTFPtrType) GetID added in v0.6.0

func (ct *BTFPtrType) GetID() int

func (*BTFPtrType) GetKind added in v0.6.0

func (ct *BTFPtrType) GetKind() BTFKind

func (*BTFPtrType) GetName added in v0.6.0

func (ct *BTFPtrType) GetName() string

func (*BTFPtrType) Serialize added in v0.6.0

func (t *BTFPtrType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

func (BTFPtrType) ToBTFType added in v0.6.0

func (ct BTFPtrType) ToBTFType(strTbl *StringTbl) btfType

type BTFRestrictType added in v0.6.0

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

func (*BTFRestrictType) GetID added in v0.6.0

func (ct *BTFRestrictType) GetID() int

func (*BTFRestrictType) GetKind added in v0.6.0

func (ct *BTFRestrictType) GetKind() BTFKind

func (*BTFRestrictType) GetName added in v0.6.0

func (ct *BTFRestrictType) GetName() string

func (*BTFRestrictType) Serialize added in v0.6.0

func (t *BTFRestrictType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

func (BTFRestrictType) ToBTFType added in v0.6.0

func (ct BTFRestrictType) ToBTFType(strTbl *StringTbl) btfType

type BTFStructType added in v0.6.0

type BTFStructType struct {

	// The individual members / fields of the struct.
	Members []BTFMember
	// contains filtered or unexported fields
}

BTFStructType is the type for KIND_STRUCT, which represents a structure.

func (*BTFStructType) GetID added in v0.6.0

func (ct *BTFStructType) GetID() int

func (*BTFStructType) GetKind added in v0.6.0

func (ct *BTFStructType) GetKind() BTFKind

func (*BTFStructType) GetName added in v0.6.0

func (ct *BTFStructType) GetName() string

func (*BTFStructType) Serialize added in v0.6.0

func (t *BTFStructType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

func (BTFStructType) ToBTFType added in v0.6.0

func (ct BTFStructType) ToBTFType(strTbl *StringTbl) btfType

func (*BTFStructType) Verify added in v0.6.0

func (t *BTFStructType) Verify() error

type BTFType added in v0.6.0

type BTFType interface {
	// Returns the TypeID of the type, which is determined by the position of the type within the encoded
	// BTF bytes sequence.
	GetID() int
	GetKind() BTFKind
	GetName() string
	Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)
}

BTFType is a BTF type, each Kind has its own corresponding BTFType.

type BTFTypeDefType added in v0.6.0

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

func (*BTFTypeDefType) GetID added in v0.6.0

func (ct *BTFTypeDefType) GetID() int

func (*BTFTypeDefType) GetKind added in v0.6.0

func (ct *BTFTypeDefType) GetKind() BTFKind

func (*BTFTypeDefType) GetName added in v0.6.0

func (ct *BTFTypeDefType) GetName() string

func (*BTFTypeDefType) Serialize added in v0.6.0

func (t *BTFTypeDefType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

func (BTFTypeDefType) ToBTFType added in v0.6.0

func (ct BTFTypeDefType) ToBTFType(strTbl *StringTbl) btfType

type BTFUnionType added in v0.6.0

type BTFUnionType struct {

	// The individual members / fields of the union.
	Members []BTFMember
	// contains filtered or unexported fields
}

BTFUnionType is the type for KIND_UNION, which represents a union, where all members occupy the same memory.

func (*BTFUnionType) GetID added in v0.6.0

func (ct *BTFUnionType) GetID() int

func (*BTFUnionType) GetKind added in v0.6.0

func (ct *BTFUnionType) GetKind() BTFKind

func (*BTFUnionType) GetName added in v0.6.0

func (ct *BTFUnionType) GetName() string

func (*BTFUnionType) Serialize added in v0.6.0

func (t *BTFUnionType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

func (BTFUnionType) ToBTFType added in v0.6.0

func (ct BTFUnionType) ToBTFType(strTbl *StringTbl) btfType

type BTFVarType added in v0.6.0

type BTFVarType struct {
	Linkage uint32
	// contains filtered or unexported fields
}

func (*BTFVarType) GetID added in v0.6.0

func (ct *BTFVarType) GetID() int

func (*BTFVarType) GetKind added in v0.6.0

func (ct *BTFVarType) GetKind() BTFKind

func (*BTFVarType) GetName added in v0.6.0

func (ct *BTFVarType) GetName() string

func (*BTFVarType) Serialize added in v0.6.0

func (t *BTFVarType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

func (BTFVarType) ToBTFType added in v0.6.0

func (ct BTFVarType) ToBTFType(strTbl *StringTbl) btfType

type BTFVoidType added in v0.6.0

type BTFVoidType struct{}

BTFVoidType is not an actual type in BTF, it is used as type ID 0.

func (*BTFVoidType) GetID added in v0.6.0

func (vt *BTFVoidType) GetID() int

func (*BTFVoidType) GetKind added in v0.6.0

func (vt *BTFVoidType) GetKind() BTFKind

func (*BTFVoidType) GetName added in v0.6.0

func (vt *BTFVoidType) GetName() string

func (*BTFVoidType) Serialize added in v0.6.0

func (vt *BTFVoidType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

type BTFVolatileType added in v0.6.0

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

func (*BTFVolatileType) GetID added in v0.6.0

func (ct *BTFVolatileType) GetID() int

func (*BTFVolatileType) GetKind added in v0.6.0

func (ct *BTFVolatileType) GetKind() BTFKind

func (*BTFVolatileType) GetName added in v0.6.0

func (ct *BTFVolatileType) GetName() string

func (*BTFVolatileType) Serialize added in v0.6.0

func (t *BTFVolatileType) Serialize(strTbl *StringTbl, order binary.ByteOrder) ([]byte, error)

func (BTFVolatileType) ToBTFType added in v0.6.0

func (ct BTFVolatileType) ToBTFType(strTbl *StringTbl) btfType

type ELFParseSettings

type ELFParseSettings struct {
	// If true, names which are to large will be truncated, this can cause unexpected behavior
	// Otherwise an error will be generated.
	TruncateNames bool
}

type FrameLeaser

type FrameLeaser interface {
	ReadLease() (*XSKLease, error)
	WriteLease() (*XSKLease, error)
}

type FrameReader

type FrameReader interface {
	ReadFrame(p []byte) (n int, err error)
}

A FrameReader can read whole or partial ethernet frames. Every time ReadFrame is called, p will be filled with up to len(p) bytes from a single frame. These bytes include both the header and body of the ethernet frame. If p to small to fit the whole frame, the remaining bytes of the frame are discarded. The next call to ReadFrame will start at the next frame.

n will be set to the number of bytes read from the the frame. err is non nil if any error has occurred during the process. If both n is 0 and err is nil nothing was read for an expected reason like a timout or external interrupt.

type FrameWriter

type FrameWriter interface {
	WriteFrame(p []byte) (n int, err error)
}

type HashMap added in v0.4.0

type HashMap struct {
	AbstractMap
}

HashMap is a generic map type, both the key and value may be of any type. The value of the key is hashed so values do not need to be contiguous.

func (*HashMap) Close added in v0.6.0

func (m *HashMap) Close() error

Close closes the file descriptor associate with the map, this will cause the map to unload from the kernel if it is not still in use by a eBPF program, bpf FS, or a userspace program still holding a fd to the map.

func (*HashMap) Delete added in v0.4.0

func (m *HashMap) Delete(key interface{}) error

func (*HashMap) DeleteBatch added in v0.4.0

func (m *HashMap) DeleteBatch(
	keys interface{},
	maxBatchSize uint32,
) (
	count int,
	err error,
)

func (*HashMap) Get added in v0.4.0

func (m *HashMap) Get(key interface{}, value interface{}) error

func (*HashMap) GetAndDelete added in v0.4.0

func (m *HashMap) GetAndDelete(key interface{}, value interface{}) error

func (*HashMap) GetAndDeleteBatch added in v0.4.0

func (m *HashMap) GetAndDeleteBatch(
	keys interface{},
	values interface{},
	maxBatchSize uint32,
) (
	count int,
	err error,
)

func (*HashMap) GetBatch added in v0.4.0

func (m *HashMap) GetBatch(
	keys interface{},
	values interface{},
	maxBatchSize uint32,
) (
	count int,
	partial bool,
	err error,
)

GetBatch fills the keys and values array/slice with the keys and values inside the map up to a maximum of maxBatchSize entries. The keys and values array/slice must have at least a length of maxBatchSize. The key and value of an entry is has the same index, so for example the value for keys[2] is in values[2]. Count is the amount of entries returns, partial is true if not all elements of keys and values could be set.

This function is intended for small maps which can be read into userspace all at once since GetBatch can only read from the beginning of the map. If the map is to large to read all at once a iterator should be used instead of the Get or GetBatch function.

func (*HashMap) Iterator added in v0.4.0

func (m *HashMap) Iterator() MapIterator

func (*HashMap) Load added in v0.4.0

func (m *HashMap) Load() error

func (*HashMap) Set added in v0.4.0

func (m *HashMap) Set(key interface{}, value interface{}, flags bpfsys.BPFAttrMapElemFlags) error

func (*HashMap) SetBatch added in v0.4.0

func (m *HashMap) SetBatch(
	keys interface{},
	values interface{},
	flags bpfsys.BPFAttrMapElemFlags,
	maxBatchSize uint32,
) (
	count int,
	err error,
)

type HashOfMapsMap added in v0.5.0

type HashOfMapsMap struct {
	AbstractMap

	// InnerMapDef is the definition of the inner map
	// TODO: Once BTF is implemented we can infer this map type from the BTF debug symbols
	InnerMapDef BPFMapDef
	// contains filtered or unexported fields
}

HashOfMapsMap is a map with as value another map, the value type must be any loaded BPF map. The key type can be anything, the keys are hashed and thus do not need to be contiguous.

func (*HashOfMapsMap) Close added in v0.6.0

func (m *HashOfMapsMap) Close() error

Close closes the file descriptor associate with the map, this will cause the map to unload from the kernel if it is not still in use by a eBPF program, bpf FS, or a userspace program still holding a fd to the map.

func (*HashOfMapsMap) Get added in v0.5.0

func (m *HashOfMapsMap) Get(key interface{}) (BPFMap, error)

func (*HashOfMapsMap) Iterator added in v0.5.0

func (m *HashOfMapsMap) Iterator() MapIterator

func (*HashOfMapsMap) Load added in v0.5.0

func (m *HashOfMapsMap) Load() error

func (*HashOfMapsMap) Set added in v0.5.0

func (m *HashOfMapsMap) Set(key interface{}, value BPFMap, flags bpfsys.BPFAttrMapElemFlags) error

type LPMTrieIPv4Key added in v0.5.0

type LPMTrieIPv4Key struct {
	Prefix  uint32
	Address [4]byte
}

func (*LPMTrieIPv4Key) LPMTrieKey added in v0.5.0

func (k *LPMTrieIPv4Key) LPMTrieKey()

LPMTrieKey does nothing, it is just defined so LPMTrieIPv4Key implements LPMTrieKey

type LPMTrieIPv6Key added in v0.5.0

type LPMTrieIPv6Key struct {
	Prefix  uint32
	Address [16]byte
}

func (*LPMTrieIPv6Key) LPMTrieKey added in v0.5.0

func (k *LPMTrieIPv6Key) LPMTrieKey()

LPMTrieKey does nothing, it is just defined so LPMTrieIPv6Key implements LPMTrieKey

type LPMTrieKey added in v0.5.0

type LPMTrieKey interface {
	LPMTrieKey()
}

func LPMKeyFromNetwork added in v0.5.0

func LPMKeyFromNetwork(n net.IPNet) LPMTrieKey

LPMKeyFromNetwork converts an net.IPNet struct into an LPMTrieKey

type LPMTrieMap added in v0.5.0

type LPMTrieMap struct {
	AbstractMap
}

LPMTrieMap is a specialized map type which used Longest Prefix Matching on the key when getting values from the map. LPM is commonly used in routing tables or any other application where the most specific network range should overrule settings of less specific network ranges.

func (*LPMTrieMap) Close added in v0.6.0

func (m *LPMTrieMap) Close() error

Close closes the file descriptor associate with the map, this will cause the map to unload from the kernel if it is not still in use by a eBPF program, bpf FS, or a userspace program still holding a fd to the map.

func (*LPMTrieMap) Delete added in v0.5.0

func (m *LPMTrieMap) Delete(key LPMTrieKey) error

func (*LPMTrieMap) DeleteBatch added in v0.5.0

func (m *LPMTrieMap) DeleteBatch(
	keys interface{},
	maxBatchSize uint32,
) (
	count int,
	err error,
)

func (*LPMTrieMap) Get added in v0.5.0

func (m *LPMTrieMap) Get(key LPMTrieKey, value interface{}) error

func (*LPMTrieMap) GetBatch added in v0.5.0

func (m *LPMTrieMap) GetBatch(
	keys interface{},
	values interface{},
	maxBatchSize uint32,
) (
	count int,
	partial bool,
	err error,
)

GetBatch fills the keys and values array/slice with the keys and values inside the map up to a maximum of maxBatchSize entries. The keys and values array/slice must have at least a length of maxBatchSize. The key and value of an entry is has the same index, so for example the value for keys[2] is in values[2]. Count is the amount of entries returns, partial is true if not all elements of keys and values could be set.

This function is intended for small maps which can be read into userspace all at once since GetBatch can only read from the beginning of the map. If the map is to large to read all at once a iterator should be used instead of the Get or GetBatch function.

func (*LPMTrieMap) Iterator added in v0.5.0

func (m *LPMTrieMap) Iterator() MapIterator

func (*LPMTrieMap) Load added in v0.5.0

func (m *LPMTrieMap) Load() error

func (*LPMTrieMap) Set added in v0.5.0

func (m *LPMTrieMap) Set(key LPMTrieKey, value interface{}, flags bpfsys.BPFAttrMapElemFlags) error

func (*LPMTrieMap) SetBatch added in v0.5.0

func (m *LPMTrieMap) SetBatch(
	keys interface{},
	values interface{},
	flags bpfsys.BPFAttrMapElemFlags,
	maxBatchSize uint32,
) (
	count int,
	err error,
)

type MapIterator

type MapIterator interface {
	// Init should be called with a key and value pointer to variables which will be used on subsequent calls to
	// Next to set values. The key and value pointers must be compatible with the map.
	// The value of key should not be modified between the first call to Next and discarding of the iterator since
	// it is reused. Doing so may cause skipped entries, duplicate entries, or error opon calling Next.
	Init(key, value interface{}) error
	// Next assigns the next value to the key and value last passed via the Init func.
	// True is returned if key and value was updated.
	// If updated is false and err is nil, all values from the iterator were read.
	// On error a iterator should also be considered empty and can be discarded.
	Next() (updated bool, err error)
}

A MapIterator describes an iterator which can iterate over all keys and values of a map without keeping all contents in userspace memory at the same time. Since maps can be constantly updated by a eBPF program the results are not guaranteed, expect to read duplicate values or not get all keys. This depends greatly on the frequency of change of the map, the type of map (arrays are not effected, hashes are) and speed of iteration. It is recommended to quickly iterate over maps and not to change them during iteration to reduce these effects.

type ObjName

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

func MustNewObjName

func MustNewObjName(initialName string) ObjName

func NewObjName

func NewObjName(initialName string) (*ObjName, error)

func (*ObjName) GetCstr

func (on *ObjName) GetCstr() [bpftypes.BPF_OBJ_NAME_LEN]byte

func (*ObjName) SetBytes

func (on *ObjName) SetBytes(strBytes []byte) error

func (*ObjName) SetString

func (on *ObjName) SetString(str string) error

func (*ObjName) String

func (on *ObjName) String() string

type PerCPUArrayMap added in v0.4.0

type PerCPUArrayMap struct {
	AbstractMap
}

PerCPUArrayMap is a map which has a integer key from 0 to MaxEntries. It is a generic map type so the value can be any type. This map type stores an array of values for each key, the size of the array is equal to the CPU count returned by the runtime.NumCPU() function.

func (*PerCPUArrayMap) Close added in v0.6.0

func (m *PerCPUArrayMap) Close() error

Close closes the file descriptor associate with the map, this will cause the map to unload from the kernel if it is not still in use by a eBPF program, bpf FS, or a userspace program still holding a fd to the map.

func (*PerCPUArrayMap) Get added in v0.4.0

func (m *PerCPUArrayMap) Get(key uint32, value interface{}) error

func (*PerCPUArrayMap) GetBatch added in v0.4.0

func (m *PerCPUArrayMap) GetBatch(
	keys []uint32,
	values interface{},
) (
	count int,
	partial bool,
	err error,
)

GetBatch fills the keys slice and values array/slice with the keys and values inside the map. The keys slice and values array/slice must have the same length. The key and value of an entry is has the same index, so for example the value for keys[2] is in values[2]. Count is the amount of entries returns, partial is true if not all elements of keys and values could be set.

This function is intended for small maps which can be read into userspace all at once since GetBatch can only read from the beginning of the map. If the map is to large to read all at once a iterator should be used instead of the Get or GetBatch function.

func (*PerCPUArrayMap) Iterator added in v0.4.0

func (m *PerCPUArrayMap) Iterator() MapIterator

func (*PerCPUArrayMap) Load added in v0.4.0

func (m *PerCPUArrayMap) Load() error

func (*PerCPUArrayMap) Set added in v0.4.0

func (m *PerCPUArrayMap) Set(key uint32, value interface{}, flags bpfsys.BPFAttrMapElemFlags) error

func (*PerCPUArrayMap) SetBatch added in v0.4.0

func (m *PerCPUArrayMap) SetBatch(
	keys []uint32,
	values interface{},
	flags bpfsys.BPFAttrMapElemFlags,
) (
	count int,
	err error,
)

type ProgArrayMap

type ProgArrayMap struct {
	AbstractMap
}

ProgArrayMap is a specialized map type used for tail calls https://docs.cilium.io/en/stable/bpf/#tail-calls

func (*ProgArrayMap) Close added in v0.6.0

func (m *ProgArrayMap) Close() error

Close closes the file descriptor associate with the map, this will cause the map to unload from the kernel if it is not still in use by a eBPF program, bpf FS, or a userspace program still holding a fd to the map.

func (*ProgArrayMap) Get

func (m *ProgArrayMap) Get(key int) (int, error)

Get performs a lookup in the xskmap based on the key and returns the file descriptor of the socket

func (*ProgArrayMap) Load added in v0.4.0

func (m *ProgArrayMap) Load() error

func (*ProgArrayMap) Set

func (m *ProgArrayMap) Set(key int32, value BPFProgram) error

type ProgKPAttachOpts added in v0.5.0

type ProgKPAttachOpts struct {
	Type perf.ProbeType
	// Group name. If omitted, use "kprobes" for it.
	Group string
	// Event name. If omitted, the event name is generated
	// based on SYM+offs or MEMADDR.
	Event string

	// Module name which has given Symbol.
	Module string
	// Symbol+Offset where the probe is inserted.
	Symbol string
	// Path is the path to the executable to be probed.
	Path string
	// Offset of the address to be be probed.
	Offset int
}

type ProgKPLoadOpts added in v0.5.0

type ProgKPLoadOpts struct {
	VerifierLogLevel bpftypes.BPFLogLevel
	VerifierLogSize  int
}

type ProgSKFilterDetachOpts added in v0.5.0

type ProgSKFilterDetachOpts struct {
	// the file descriptor of the network socket from which the program should be detached
	Fd int
	// If true, the program will be detached from all network interfaces
	All bool
}

type ProgSKFilterLoadOpts added in v0.5.0

type ProgSKFilterLoadOpts struct {
	VerifierLogLevel bpftypes.BPFLogLevel
	VerifierLogSize  int
}

type ProgTPAttachOpts added in v0.5.0

type ProgTPAttachOpts struct {
	Category string
	Name     string
}

type ProgTPLoadOpts added in v0.5.0

type ProgTPLoadOpts struct {
	VerifierLogLevel bpftypes.BPFLogLevel
	VerifierLogSize  int
}

type ProgXDPAttachOpts added in v0.5.0

type ProgXDPAttachOpts struct {
	// Name of the network interface to which to attach the XDP program
	InterfaceName string
	// If true, this program will replace any existing program.
	// If false, attempting to attach a program while one is still loaded will cause an error
	Replace bool
	XDPMode XDPMode
	// If true, we will return a error when we can't attach the program in the specified mode
	// If false, we will automatically fallback to a less specific XPDMode if the current mode fails.
	DisableFallback bool
}

type ProgXDPLoadOpts added in v0.5.0

type ProgXDPLoadOpts struct {
	// A hint to the verifier about where you are going to attach the program.
	// This value can be left default for most program types, but must be set for some programs types.
	// This value may restrict where the program may be attached
	ExpectedAttachType bpftypes.BPFAttachType
	// The index of the network interface to which the program will be attached.
	// This option is only required for XDP offloading in hardware mode.
	// In hardware mode the kernel needs to know how to convert eBPF into code that can run on the
	// hardware, so at load time it needs to know which devices will be used.
	IfIndex          uint32
	VerifierLogLevel bpftypes.BPFLogLevel
	VerifierLogSize  int
}

type ProgramKProbe added in v0.5.0

type ProgramKProbe struct {
	AbstractBPFProgram

	DefaultType perf.ProbeType
	// DefaultCategory is the kprobe group used if no group is specified during attaching.
	// It can be set when loading from ELF file.
	DefaultGroup string
	// DefaultName is the kprobe event used if no event is specified during attaching.
	// It can be set when loading from ELF file.
	DefaultEvent  string
	DefaultModule string
	DefaultSymbol string
	DefaultPath   string
	DefaultOffset int
	// contains filtered or unexported fields
}

func (*ProgramKProbe) Attach added in v0.5.0

func (p *ProgramKProbe) Attach(opts ProgKPAttachOpts) error

func (*ProgramKProbe) Detach added in v0.5.0

func (p *ProgramKProbe) Detach() error

func (*ProgramKProbe) Load added in v0.5.0

func (p *ProgramKProbe) Load(opts ProgKPLoadOpts) (log string, err error)

func (*ProgramKProbe) Unpin added in v0.5.0

func (p *ProgramKProbe) Unpin(relativePath string, deletePin bool) error

Unpin captures the file descriptor of the program at the given 'relativePath' from the kernel. If 'deletePin' is true the bpf FS pin will be removed after successfully loading the program, thus transferring ownership of the program in a scenario where the program is not shared between multiple userspace programs. Otherwise the pin will keep existing which will cause the map to not be deleted when this program exits.

type ProgramSocketFilter added in v0.5.0

type ProgramSocketFilter struct {
	AbstractBPFProgram

	AttachedSocketFDs []int
}

func (*ProgramSocketFilter) Attach added in v0.5.0

func (p *ProgramSocketFilter) Attach(fd uintptr) error

Attach attempts to attach a filter program to the network socket indicated by the given file descriptor. This function can be used if network file descriptors are managed outside of the net package or when using the net.TCPListener.File function to get a duplicate file descriptor.

func (*ProgramSocketFilter) Detach added in v0.5.0

func (p *ProgramSocketFilter) Detach(settings ProgSKFilterDetachOpts) error

Detach detaches the program from one or all sockets.

func (*ProgramSocketFilter) Load added in v0.5.0

func (p *ProgramSocketFilter) Load(opts ProgSKFilterLoadOpts) (log string, err error)

func (*ProgramSocketFilter) SocketAttachControlFunc added in v0.5.0

func (p *ProgramSocketFilter) SocketAttachControlFunc(network, address string, c syscall.RawConn) error

SocketAttachControlFunc attaches a "socket filter" program to a network socket. This function is meant to be used as function pointer in net.Dialer.Control or net.ListenConfig.Control.

func (*ProgramSocketFilter) Unpin added in v0.5.0

func (p *ProgramSocketFilter) Unpin(relativePath string, deletePin bool) error

Unpin captures the file descriptor of the program at the given 'relativePath' from the kernel. If 'deletePin' is true the bpf FS pin will be removed after successfully loading the program, thus transferring ownership of the program in a scenario where the program is not shared between multiple userspace programs. Otherwise the pin will keep existing which will cause the map to not be deleted when this program exits.

type ProgramTracepoint added in v0.5.0

type ProgramTracepoint struct {
	AbstractBPFProgram

	// DefaultCategory is the tracepoint category used if no category is specified during attaching.
	// It can be set when loading from ELF file.
	DefaultCategory string
	// DefaultName is the tracepoint name used if no name is specified during attaching.
	// It can be set when loading from ELF file.
	DefaultName string
	// contains filtered or unexported fields
}

func (*ProgramTracepoint) Attach added in v0.5.0

func (p *ProgramTracepoint) Attach(opts ProgTPAttachOpts) error

func (*ProgramTracepoint) Detach added in v0.5.0

func (p *ProgramTracepoint) Detach() error

func (*ProgramTracepoint) Load added in v0.5.0

func (p *ProgramTracepoint) Load(opts ProgTPLoadOpts) (log string, err error)

func (*ProgramTracepoint) Unpin added in v0.5.0

func (p *ProgramTracepoint) Unpin(relativePath string, deletePin bool) error

Unpin captures the file descriptor of the program at the given 'relativePath' from the kernel. If 'deletePin' is true the bpf FS pin will be removed after successfully loading the program, thus transferring ownership of the program in a scenario where the program is not shared between multiple userspace programs. Otherwise the pin will keep existing which will cause the map to not be deleted when this program exits.

type ProgramXDP added in v0.5.0

type ProgramXDP struct {
	AbstractBPFProgram

	// A list of network interface ids the program is linked to
	AttachedNetlinkIDs []int
}

func (*ProgramXDP) Attach added in v0.5.0

func (p *ProgramXDP) Attach(opts ProgXDPAttachOpts) error

Attach attaches a already loaded eBPF XDP program to a network device. If attaching fails due to the XDP mode we will automatically attempt to fallback to slower but better supported XDP mode

func (*ProgramXDP) Load added in v0.5.0

func (p *ProgramXDP) Load(opts ProgXDPLoadOpts) (log string, err error)

func (*ProgramXDP) Unpin added in v0.5.0

func (p *ProgramXDP) Unpin(relativePath string, deletePin bool) error

Unpin captures the file descriptor of the program at the given 'relativePath' from the kernel. If 'deletePin' is true the bpf FS pin will be removed after successfully loading the program, thus transferring ownership of the program in a scenario where the program is not shared between multiple userspace programs. Otherwise the pin will keep existing which will cause the map to not be deleted when this program exits.

func (*ProgramXDP) XDPLinkDetach added in v0.5.0

func (p *ProgramXDP) XDPLinkDetach(settings BPFProgramXDPLinkDetachSettings) error

XDPLinkDetach detaches a XDP program from one or all network interfaces it is attached to.

func (*ProgramXDP) XDPTestProgram added in v0.5.0

func (p *ProgramXDP) XDPTestProgram(settings TestXDPProgSettings) (*TestXDPProgResult, error)

XDPTestProgram executes a loaded XDP program on supplied data. This feature can be used to test the functionality of an XDP program without having to generate actual traffic on an interface. It is also useful for benchmarking a XDP programs which is otherwise impractical.

type QueueMap added in v0.6.0

type QueueMap struct {
	AbstractMap
}

QueueMap is a specialized map type, it has no key type, only a value type. It works like any other FIFO queue.

func (*QueueMap) Close added in v0.6.0

func (m *QueueMap) Close() error

Close closes the file descriptor associate with the map, this will cause the map to unload from the kernel if it is not still in use by a eBPF program, bpf FS, or a userspace program still holding a fd to the map.

func (*QueueMap) Dequeue added in v0.6.0

func (m *QueueMap) Dequeue(value interface{}) error

Dequeue returns the value of the from of the queue, removing it in the process.

func (*QueueMap) Enqueue added in v0.6.0

func (m *QueueMap) Enqueue(value interface{}) error

Enqueue enqueues a new value

func (*QueueMap) Iterator added in v0.6.0

func (m *QueueMap) Iterator() MapIterator

Iterator returns a map iterator which can be used to loop over all values of the map. Looping over the queue will consume all values.

func (*QueueMap) Load added in v0.6.0

func (m *QueueMap) Load() error

func (*QueueMap) Peek added in v0.6.0

func (m *QueueMap) Peek(value interface{}) error

Peek peeks at the first value in the queue without removing it.

type StackMap added in v0.6.0

type StackMap struct {
	AbstractMap
}

StackMap is a specialized map type, it has no key type, only a value type. It works like any other FILO stack.

func (*StackMap) Close added in v0.6.0

func (m *StackMap) Close() error

Close closes the file descriptor associate with the map, this will cause the map to unload from the kernel if it is not still in use by a eBPF program, bpf FS, or a userspace program still holding a fd to the map.

func (*StackMap) Iterator added in v0.6.0

func (m *StackMap) Iterator() MapIterator

Iterator returns a map iterator which can be used to loop over all values of the map. Looping over the stack will consume all values.

func (*StackMap) Load added in v0.6.0

func (m *StackMap) Load() error

func (*StackMap) Peek added in v0.6.0

func (m *StackMap) Peek(value interface{}) error

Peek peeks at the value at the top of the stack without removing it.

func (*StackMap) Pop added in v0.6.0

func (m *StackMap) Pop(value interface{}) error

Pop returns the top value of the stack, removing it in the process.

func (*StackMap) Push added in v0.6.0

func (m *StackMap) Push(value interface{}) error

Push pushes a new value onto the stack

type StringTbl added in v0.6.0

type StringTbl struct {
	Strings []string
	// contains filtered or unexported fields
}

func StringTblFromBlob added in v0.6.0

func StringTblFromBlob(blob []byte) StringTbl

func (*StringTbl) GetStringAtOffset added in v0.6.0

func (st *StringTbl) GetStringAtOffset(offset int) string

func (*StringTbl) Serialize added in v0.6.0

func (st *StringTbl) Serialize()

func (*StringTbl) StrToOffset added in v0.6.0

func (st *StringTbl) StrToOffset(str string) int

type TestXDPProgResult added in v0.3.0

type TestXDPProgResult struct {
	// The return value of the program
	ReturnValue int32
	// The avarage duration of a single run in nanoseconds
	Duration uint32
	// The modified data (as it would be received by the network stack)
	Data []byte
}

TestXDPProgResult is the result of XDPTestProgram

type TestXDPProgSettings added in v0.3.0

type TestXDPProgSettings struct {
	// How often should the test be repeated? For benchmarking purposes
	Repeat uint32
	// The input data, in this case the ethernet frame to check
	Data []byte
}

TestXDPProgSettings are the settings passed to XDPTestProgram

type XDPMode

type XDPMode int
const (
	// XDPModeHW indicates that the XDP program should be loaded in hardware mode.
	// This requires support from the NIC and driver but is the fastest mode available.
	XDPModeHW XDPMode = iota
	// XDPModeDRV indicates that the XDP program should be loaded in driver mode.
	// This requires driver support but is faster than SKB mode because it runs at the driver level.
	XDPModeDRV
	// XDPModeSKB indicates that the XDP program should be loaded driver independent mode.
	// This works for every network driver but is the slowest option, if other loading methods fail this is the fallback
	XDPModeSKB
)

type XSKIterator

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

func (*XSKIterator) Init

func (xi *XSKIterator) Init(key, value interface{}) error

func (*XSKIterator) Next

func (xi *XSKIterator) Next() (updated bool, err error)

Next gets the key and value at the current location and writes them to the pointers given to the iterator during initialization. It then advances the internal pointer to the next key and value. If the iterator can't get the key and value at the current location since we are done iterating or an error was encountered 'updated' is false.

type XSKLease

type XSKLease struct {
	Data []byte
	// The amount of bytes which are prefixed at the start which don't contain frame data.
	// This headroom can be used to add an extra header(encapsulation) without having to
	// copy or move the existing packet data.
	Headroom int
	// contains filtered or unexported fields
}

XSKLease is used to "lease" a piece of buffer memory from the socket and return it after the user is done using it. This allows us to implement true zero copy packet access. After a XSKLease is released or written the underlaying array of Data will be repurposed, to avoid strage bugs users must use Data or sub-slices of Data after the lease has been released.

func (*XSKLease) Release

func (xl *XSKLease) Release() error

Release releases the leased memory so the kernel can fill it with new data.

func (*XSKLease) Write

func (xl *XSKLease) Write() error

Write writes a lease to the network interface. The len property of the 'Data' slice - 'Headroom' is the length of the packet. Make sure to resize the Data to the size of the data to be transmitted. The headroom should always be included(never resize the start of the slice). The 'Headroom' should be used to indicate from which byte the headroom starts. After Write has been called the lease will be released and the Data slice or its subslices should not be used anymore.

type XSKMap

type XSKMap struct {
	AbstractMap
	// contains filtered or unexported fields
}

XSKMap is a specialized map type designed to work in conjunction with XSKSocket's.

func (*XSKMap) Close added in v0.6.0

func (m *XSKMap) Close() error

Close closes the file descriptor associate with the map, this will cause the map to unload from the kernel if it is not still in use by a eBPF program, bpf FS, or a userspace program still holding a fd to the map.

func (*XSKMap) Delete

func (m *XSKMap) Delete(key uint32) error

func (*XSKMap) Get

func (m *XSKMap) Get(key uint32) (*XSKSocket, error)

Get performs a lookup in the xskmap based on the key and returns the file descriptor of the socket

func (*XSKMap) Iterator

func (m *XSKMap) Iterator() MapIterator

func (*XSKMap) Load

func (m *XSKMap) Load() error

func (*XSKMap) Set

func (m *XSKMap) Set(key uint32, value *XSKSocket) error

type XSKMultiSocket

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

XSKMultiSocket is a collection of XSKSockets. The multi socket balances reads and writes between all XSKSockets. This is useful for multi queue netdevices since a XSKSocket can only read or write from one rx/tx queue pair at a time. A multi queue allows you to bundle all of these sockets so you get a socket for the whole netdevice.

An alternative use for the multi socket is to add sockets from multiple netdevices.

TODO look into using epoll for multi sockets. Using poll for single sockets still makes sense since there is always

1 fd, but for multi sockets we can have much more. For high-end NICs with ~40 rx/tx queues(mallanox for example)
it makes sense to start using epoll since it is supposed to scale better. Should make it configurable when adding
support in case freeBSD or other unix-like os adds XSK support since epoll is non-POSIX

TODO dynamic socket adding/removing. Should not be to hard, the main edge case to solve is dealing with

pending/blocking syscalls for read/write. But presumably epoll can allow us to dynamically add/remove
fds without interrupting the reads/writes. Otherwise adding/removing sockets will have to request both the
rmu and wmu.

func NewXSKMultiSocket

func NewXSKMultiSocket(xskSockets ...*XSKSocket) (*XSKMultiSocket, error)

func (*XSKMultiSocket) Close

func (xms *XSKMultiSocket) Close() error

func (*XSKMultiSocket) ReadFrame

func (xms *XSKMultiSocket) ReadFrame(p []byte) (n int, err error)

func (*XSKMultiSocket) ReadLease

func (xms *XSKMultiSocket) ReadLease() (lease *XSKLease, err error)

ReadLease reads a frame from the socket and returns its memory in a XSKLease. After reading the contents of the frame it can be released or written, both will allow the memory to be reused. Calling Write on the lease will cause the contents of Data to be written back to the network interface. The contents of Data can be modified before calling Write thus allowing a program to implement zero-copy/zero-allocation encaptulation or request/response protocols.

func (*XSKMultiSocket) SetReadTimeout

func (xms *XSKMultiSocket) SetReadTimeout(ms int) error

SetReadTimeout sets the timeout for Read and ReadLease calls. If ms == 0 (default), we will never block/wait and return no data if there isn't any ready. If ms == -1, we will block forever until we can read. If ms > 0, we will wait for x miliseconds for an oppurunity to read or return no data.

func (*XSKMultiSocket) SetWriteTimeout

func (xms *XSKMultiSocket) SetWriteTimeout(ms int) error

SetWriteTimeout sets the timeout for Write and XSKLease.WriteBack calls. If ms == 0 (default), we will never block/wait and error if we can't write at once. If ms == -1, we will block forever until we can write. If ms > 0, we will wait for x miliseconds for an oppurunity to write or error afterwards.

func (*XSKMultiSocket) WriteFrame

func (xms *XSKMultiSocket) WriteFrame(p []byte) (n int, err error)

func (*XSKMultiSocket) WriteLease

func (xms *XSKMultiSocket) WriteLease() (lease *XSKLease, err error)

WriteLease creates a XSKLease which points to a piece of preallocated memory. This memory can be used to build packets for writing. Unlike XSKLeases gotten from ReadLease, write leases have no Headroom. The Data slice of the lease is the full length of the usable frame, this length should not be exceeded. Any memory held by the lease can't be reused until released or written.

This function blocks until a frame for transmission is available and is not subject to the write timeout.

type XSKSettings

type XSKSettings struct {
	// Size of the umem frames/packet buffers (2048 or 4096)
	FrameSize int
	// Amount of frames/packets which can be used, must be a power of 2
	FrameCount int
	// The index of the network device on which XSK will be used
	NetDevIfIndex int
	// The id of the Queue on which this XSK will be used
	QueueID int
	// How much unused space should be left at the start of each buffer.
	// This can be used to for example encapsulate a packet whichout having to move or copy memory
	Headroom int
	// Is Tx disabled for this socket?
	DisableTx bool
	// Is Rx disabled for this socket?
	DisableRx bool
	// If true, XDP_USE_NEED_WAKEUP is not used. Should be on by default
	// unless there is a reason it doesn't work (like on older kernels)
	DisableNeedWakeup bool
	// If true, zero copy mode is forced. By default zero copy mode is attempted and if not available
	// in the driver will automatically fallback to copy mode.
	ForceZeroCopy bool
	// If true, copy mode is always used and zero copy mode never attempted.
	ForceCopy bool
	// The minimum time between two checks of the completion queue. A lower value allows for more transmitted
	// packets per seconds at the cost of higher CPU usage, even when not transmitting.
	// By default this value is 10ms which seems a sane value, it means that there is a theorethical max TX rate of
	// (1000/10) * (tx ring size) which is 100 * 2048 = 204,800 packets per second when DisableRx = false
	// or 100 * 4096 = 409,600 when DisableRx = true at the default FrameCount of 4096.
	// Setting this setting to 0 will cause one goroutine to busy poll(use 100% CPU) per socket.
	CQConsumeInterval *time.Duration
}

type XSKSocket

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

A XSKSocket can bind to one queue on one netdev

func NewXSKSocket

func NewXSKSocket(settings XSKSettings) (_ *XSKSocket, err error)

func (*XSKSocket) Close

func (xs *XSKSocket) Close() error

func (*XSKSocket) Fd

func (xs *XSKSocket) Fd() int

Fd returns the file descriptor of the socket.

func (*XSKSocket) ReadFrame

func (xs *XSKSocket) ReadFrame(p []byte) (n int, err error)

ReadFrame implements FrameReader, however we have to implement this with a memory copy which is not ideal for efficiency. For zero copy packet access ReadLease should be used.

func (*XSKSocket) ReadLease

func (xs *XSKSocket) ReadLease() (lease *XSKLease, err error)

ReadLease reads a frame from the socket and returns its memory in a XSKLease. After reading the contents of the frame it can be released or written, both will allow the memory to be reused. Calling Write on the lease will cause the contents of Data to be written back to the network interface. The contents of Data can be modified before calling Write thus allowing a program to implement zero-copy/zero-allocation encaptulation or request/response protocols.

func (*XSKSocket) SetReadTimeout

func (xs *XSKSocket) SetReadTimeout(ms int) error

SetReadTimeout sets the timeout for Read and ReadLease calls. If ms == 0 (default), we will never block/wait and return no data if there isn't any ready. If ms == -1, we will block forever until we can read. If ms > 0, we will wait for x miliseconds for an oppurunity to read or return no data.

func (*XSKSocket) SetWriteTimeout

func (xs *XSKSocket) SetWriteTimeout(ms int) error

SetWriteTimeout sets the timeout for Write and XSKLease.WriteBack calls. If ms == 0 (default), we will never block/wait and error if we can't write at once. If ms == -1, we will block forever until we can write. If ms > 0, we will wait for x miliseconds for an oppurunity to write or error afterwards.

func (*XSKSocket) WriteFrame

func (xs *XSKSocket) WriteFrame(p []byte) (n int, err error)

WriteFrame implements FrameWriter. The interface requires us to copy p into umem which is not optimal for speed. For maximum performance use WriteLease instead.

func (*XSKSocket) WriteLease

func (xs *XSKSocket) WriteLease() (lease *XSKLease, err error)

WriteLease creates a XSKLease which points to a piece of preallocated memory. This memory can be used to build packets for writing. Unlike XSKLeases gotten from ReadLease, write leases have no Headroom. The Data slice of the lease is the full length of the usable frame, this length should not be exceeded. Any memory held by the lease can't be reused until released or written.

This function blocks until a frame for transmission is available and is not subject to the write timeout.

Directories

Path Synopsis
Package bpfsys contains low level functions related to syscalls and kernel interactions.
Package bpfsys contains low level functions related to syscalls and kernel interactions.
Package bpftypes contains a lot of constants/enums, the package exists because all of these constants clutter the generated documentation.
Package bpftypes contains a lot of constants/enums, the package exists because all of these constants clutter the generated documentation.
cmd
Package ebpf contains all types and constants to decode, encode, and generate eBPF bytecode in go.
Package ebpf contains all types and constants to decode, encode, and generate eBPF bytecode in go.
package emulator contains a userspace emulator/runtime for eBPF.
package emulator contains a userspace emulator/runtime for eBPF.
internal
package kernelsupport is used to query what eBPF features are supported for different version of the linux kernel
package kernelsupport is used to query what eBPF features are supported for different version of the linux kernel
Package perf contains logic to interact with the linux perf subsystem.
Package perf contains logic to interact with the linux perf subsystem.

Jump to

Keyboard shortcuts

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