DefaultVerifierLogSize is the default number of bytes allocated for the verifier log.
const DefaultVerifierLogSize = 64 * 1024
Errors returned by Map and MapIterator methods.
var ( ErrKeyNotExist = errors.New("key does not exist") ErrKeyExist = errors.New("key already exists") ErrIterationAborted = errors.New("iteration aborted") ErrMapIncompatible = errors.New("map spec is incompatible with existing map") )
ErrNotSupported is returned whenever the kernel doesn't support a feature.
var ErrNotSupported = internal.ErrNotSupported
func EnableStats(which uint32) (io.Closer, error)
EnableStats starts the measuring of the runtime and run counts of eBPF programs.
Collecting statistics can have an impact on the performance.
Requires at least 5.8.
func SanitizeName(name string, replacement rune) string
SanitizeName replaces all invalid characters in name with replacement. Passing a negative value for replacement will delete characters instead of replacing them. Use this to automatically generate valid names for maps and programs at runtime.
The set of allowed characters depends on the running kernel version. Dots are only allowed as of kernel 5.2.
AttachFlags of the eBPF program used in BPF_PROG_ATTACH command
type AttachFlags uint32
AttachType of the eBPF program, needed to differentiate allowed context accesses in some newer program types like CGroupSockAddr. Should be set to AttachNone if not required. Will cause invalid argument (EINVAL) at program load time if set incorrectly.
type AttachType uint32
const ( AttachCGroupInetIngress AttachType = iota AttachCGroupInetEgress AttachCGroupInetSockCreate AttachCGroupSockOps AttachSkSKBStreamParser AttachSkSKBStreamVerdict AttachCGroupDevice AttachSkMsgVerdict AttachCGroupInet4Bind AttachCGroupInet6Bind AttachCGroupInet4Connect AttachCGroupInet6Connect AttachCGroupInet4PostBind AttachCGroupInet6PostBind AttachCGroupUDP4Sendmsg AttachCGroupUDP6Sendmsg AttachLircMode2 AttachFlowDissector AttachCGroupSysctl AttachCGroupUDP4Recvmsg AttachCGroupUDP6Recvmsg AttachCGroupGetsockopt AttachCGroupSetsockopt AttachTraceRawTp AttachTraceFEntry AttachTraceFExit AttachModifyReturn AttachLSMMac AttachTraceIter AttachCgroupInet4GetPeername AttachCgroupInet6GetPeername AttachCgroupInet4GetSockname AttachCgroupInet6GetSockname AttachXDPDevMap AttachCgroupInetSockRelease AttachXDPCPUMap AttachSkLookup AttachXDP AttachSkSKBVerdict AttachSkReuseportSelect AttachSkReuseportSelectOrMigrate AttachPerfEvent )
AttachNone is an alias for AttachCGroupInetIngress for readability reasons.
const AttachNone AttachType = 0
func (i AttachType) String() string
BatchOptions batch map operations options
Mirrors libbpf struct bpf_map_batch_opts Currently BPF_F_FLAG is the only supported flag (for ElemFlags).
type BatchOptions struct { ElemFlags uint64 Flags uint64 }
Collection is a collection of Programs and Maps associated with their symbols
type Collection struct { Programs map[string]*Program Maps map[string]*Map }
func LoadCollection(file string) (*Collection, error)
LoadCollection reads an object file and creates and loads its declared resources into the kernel.
Omitting Collection.Close() during application shutdown is an error. See the package documentation for details around Map and Program lifecycle.
func NewCollection(spec *CollectionSpec) (*Collection, error)
NewCollection creates a Collection from the given spec, creating and loading its declared resources into the kernel.
Omitting Collection.Close() during application shutdown is an error. See the package documentation for details around Map and Program lifecycle.
func NewCollectionWithOptions(spec *CollectionSpec, opts CollectionOptions) (*Collection, error)
NewCollectionWithOptions creates a Collection from the given spec using options, creating and loading its declared resources into the kernel.
Omitting Collection.Close() during application shutdown is an error. See the package documentation for details around Map and Program lifecycle.
func (coll *Collection) Close()
Close frees all maps and programs associated with the collection.
The collection mustn't be used afterwards.
func (coll *Collection) DetachMap(name string) *Map
DetachMap removes the named map from the Collection.
This means that a later call to Close() will not affect this map.
Returns nil if no map of that name exists.
func (coll *Collection) DetachProgram(name string) *Program
DetachProgram removes the named program from the Collection.
This means that a later call to Close() will not affect this program.
Returns nil if no program of that name exists.
CollectionOptions control loading a collection into the kernel.
Maps and Programs are passed to NewMapWithOptions and NewProgramsWithOptions.
type CollectionOptions struct { Maps MapOptions Programs ProgramOptions // MapReplacements takes a set of Maps that will be used instead of // creating new ones when loading the CollectionSpec. // // For each given Map, there must be a corresponding MapSpec in // CollectionSpec.Maps, and its type, key/value size, max entries and flags // must match the values of the MapSpec. // // The given Maps are Clone()d before being used in the Collection, so the // caller can Close() them freely when they are no longer needed. MapReplacements map[string]*Map }
CollectionSpec describes a collection.
type CollectionSpec struct { Maps map[string]*MapSpec Programs map[string]*ProgramSpec // Types holds type information about Maps and Programs. // Modifications to Types are currently undefined behaviour. Types *btf.Spec // ByteOrder specifies whether the ELF was compiled for // big-endian or little-endian architectures. ByteOrder binary.ByteOrder }
func LoadCollectionSpec(file string) (*CollectionSpec, error)
LoadCollectionSpec parses an ELF file into a CollectionSpec.
func LoadCollectionSpecFromReader(rd io.ReaderAt) (*CollectionSpec, error)
LoadCollectionSpecFromReader parses an ELF file into a CollectionSpec.
func (cs *CollectionSpec) Assign(to interface{}) error
Assign the contents of a CollectionSpec to a struct.
This function is a shortcut to manually checking the presence of maps and programs in a CollectionSpec. Consider using bpf2go if this sounds useful.
'to' must be a pointer to a struct. A field of the struct is updated with values from Programs or Maps if it has an `ebpf` tag and its type is *ProgramSpec or *MapSpec. The tag's value specifies the name of the program or map as found in the CollectionSpec.
struct { Foo *ebpf.ProgramSpec `ebpf:"xdp_foo"` Bar *ebpf.MapSpec `ebpf:"bar_map"` Ignored int }
Returns an error if any of the eBPF objects can't be found, or if the same MapSpec or ProgramSpec is assigned multiple times.
▹ Example
func (cs *CollectionSpec) Copy() *CollectionSpec
Copy returns a recursive copy of the spec.
func (cs *CollectionSpec) LoadAndAssign(to interface{}, opts *CollectionOptions) error
LoadAndAssign loads Maps and Programs into the kernel and assigns them to a struct.
Omitting Map/Program.Close() during application shutdown is an error. See the package documentation for details around Map and Program lifecycle.
This function is a shortcut to manually checking the presence of maps and programs in a CollectionSpec. Consider using bpf2go if this sounds useful.
'to' must be a pointer to a struct. A field of the struct is updated with a Program or Map if it has an `ebpf` tag and its type is *Program or *Map. The tag's value specifies the name of the program or map as found in the CollectionSpec. Before updating the struct, the requested objects and their dependent resources are loaded into the kernel and populated with values if specified.
struct { Foo *ebpf.Program `ebpf:"xdp_foo"` Bar *ebpf.Map `ebpf:"bar_map"` Ignored int }
opts may be nil.
Returns an error if any of the fields can't be found, or if the same Map or Program is assigned multiple times.
▹ Example
func (cs *CollectionSpec) RewriteConstants(consts map[string]interface{}) error
RewriteConstants replaces the value of multiple constants.
The constant must be defined like so in the C program:
volatile const type foobar; volatile const type foobar = default;
Replacement values must be of the same length as the C sizeof(type). If necessary, they are marshalled according to the same rules as map values.
From Linux 5.5 the verifier will use constants to eliminate dead code.
Returns an error if a constant doesn't exist.
func (cs *CollectionSpec) RewriteMaps(maps map[string]*Map) error
RewriteMaps replaces all references to specific maps.
Use this function to use pre-existing maps instead of creating new ones when calling NewCollection. Any named maps are removed from CollectionSpec.Maps.
Returns an error if a named map isn't used in at least one program.
Deprecated: Pass CollectionOptions.MapReplacements when loading the Collection instead.
LoadPinOptions control how a pinned object is loaded.
type LoadPinOptions struct { // Request a read-only or write-only object. The default is a read-write // object. Only one of the flags may be set. ReadOnly bool WriteOnly bool // Raw flags for the syscall. Other fields of this struct take precedence. Flags uint32 }
func (lpo *LoadPinOptions) Marshal() uint32
Marshal returns a value suitable for BPF_OBJ_GET syscall file_flags parameter.
Map represents a Map file descriptor.
It is not safe to close a map which is used by other goroutines.
Methods which take interface{} arguments by default encode them using binary.Read/Write in the machine's native endianness.
Implement encoding.BinaryMarshaler or encoding.BinaryUnmarshaler if you require custom encoding.
type Map struct {
// contains filtered or unexported fields
}
▹ Example (PerCPU)
▹ Example (ZeroCopy)
func LoadPinnedMap(fileName string, opts *LoadPinOptions) (*Map, error)
LoadPinnedMap loads a Map from a BPF file.
func NewMap(spec *MapSpec) (*Map, error)
NewMap creates a new Map.
It's equivalent to calling NewMapWithOptions with default options.
func NewMapFromFD(fd int) (*Map, error)
NewMapFromFD creates a map from a raw fd.
You should not use fd after calling this function.
func NewMapFromID(id MapID) (*Map, error)
NewMapFromID returns the map for a given id.
Returns ErrNotExist, if there is no eBPF map with the given id.
func NewMapWithOptions(spec *MapSpec, opts MapOptions) (*Map, error)
NewMapWithOptions creates a new Map.
Creating a map for the first time will perform feature detection by creating small, temporary maps.
The caller is responsible for ensuring the process' rlimit is set sufficiently high for locking memory during map creation. This can be done by calling rlimit.RemoveMemlock() prior to calling NewMapWithOptions.
May return an error wrapping ErrMapIncompatible.
func (m *Map) BatchDelete(keys interface{}, opts *BatchOptions) (int, error)
BatchDelete batch deletes entries in the map by keys. "keys" must be of type slice, a pointer to a slice or buffer will not work.
func (m *Map) BatchLookup(prevKey, nextKeyOut, keysOut, valuesOut interface{}, opts *BatchOptions) (int, error)
BatchLookup looks up many elements in a map at once.
"keysOut" and "valuesOut" must be of type slice, a pointer to a slice or buffer will not work. "prevKey" is the key to start the batch lookup from, it will *not* be included in the results. Use nil to start at the first key.
ErrKeyNotExist is returned when the batch lookup has reached the end of all possible results, even when partial results are returned. It should be used to evaluate when lookup is "done".
func (m *Map) BatchLookupAndDelete(prevKey, nextKeyOut, keysOut, valuesOut interface{}, opts *BatchOptions) (int, error)
BatchLookupAndDelete looks up many elements in a map at once,
It then deletes all those elements. "keysOut" and "valuesOut" must be of type slice, a pointer to a slice or buffer will not work. "prevKey" is the key to start the batch lookup from, it will *not* be included in the results. Use nil to start at the first key.
ErrKeyNotExist is returned when the batch lookup has reached the end of all possible results, even when partial results are returned. It should be used to evaluate when lookup is "done".
func (m *Map) BatchUpdate(keys, values interface{}, opts *BatchOptions) (int, error)
BatchUpdate updates the map with multiple keys and values simultaneously. "keys" and "values" must be of type slice, a pointer to a slice or buffer will not work.
func (m *Map) Clone() (*Map, error)
Clone creates a duplicate of the Map.
Closing the duplicate does not affect the original, and vice versa. Changes made to the map are reflected by both instances however. If the original map was pinned, the cloned map will not be pinned by default.
Cloning a nil Map returns nil.
func (m *Map) Close() error
Close the Map's underlying file descriptor, which could unload the Map from the kernel if it is not pinned or in use by a loaded Program.
func (m *Map) Delete(key interface{}) error
Delete removes a value.
Returns ErrKeyNotExist if the key does not exist.
func (m *Map) FD() int
FD gets the file descriptor of the Map.
Calling this function is invalid after Close has been called.
func (m *Map) Flags() uint32
Flags returns the flags of the map.
func (m *Map) Freeze() error
Freeze prevents a map to be modified from user space.
It makes no changes to kernel-side restrictions.
func (m *Map) Info() (*MapInfo, error)
Info returns metadata about the map.
func (m *Map) IsPinned() bool
IsPinned returns true if the map has a non-empty pinned path.
func (m *Map) Iterate() *MapIterator
Iterate traverses a map.
It's safe to create multiple iterators at the same time.
It's not possible to guarantee that all keys in a map will be returned if there are concurrent modifications to the map.
▹ Example
▹ Example (NestedMapsAndProgramArrays)
func (m *Map) KeySize() uint32
KeySize returns the size of the map key in bytes.
func (m *Map) Lookup(key, valueOut interface{}) error
Lookup retrieves a value from a Map.
Calls Close() on valueOut if it is of type **Map or **Program, and *valueOut is not nil.
Returns an error if the key doesn't exist, see ErrKeyNotExist.
func (m *Map) LookupAndDelete(key, valueOut interface{}) error
LookupAndDelete retrieves and deletes a value from a Map.
Returns ErrKeyNotExist if the key doesn't exist.
func (m *Map) LookupAndDeleteWithFlags(key, valueOut interface{}, flags MapLookupFlags) error
LookupAndDeleteWithFlags retrieves and deletes a value from a Map.
Passing LookupLock flag will look up and delete the value of a spin-locked map without returning the lock. This must be specified if the elements contain a spinlock.
Returns ErrKeyNotExist if the key doesn't exist.
func (m *Map) LookupBytes(key interface{}) ([]byte, error)
LookupBytes gets a value from Map.
Returns a nil value if a key doesn't exist.
func (m *Map) LookupWithFlags(key, valueOut interface{}, flags MapLookupFlags) error
LookupWithFlags retrieves a value from a Map with flags.
Passing LookupLock flag will look up the value of a spin-locked map without returning the lock. This must be specified if the elements contain a spinlock.
Calls Close() on valueOut if it is of type **Map or **Program, and *valueOut is not nil.
Returns an error if the key doesn't exist, see ErrKeyNotExist.
func (m *Map) MaxEntries() uint32
MaxEntries returns the maximum number of elements the map can hold.
func (m *Map) NextKey(key, nextKeyOut interface{}) error
NextKey finds the key following an initial key.
See NextKeyBytes for details.
Returns ErrKeyNotExist if there is no next key.
▹ Example
func (m *Map) NextKeyBytes(key interface{}) ([]byte, error)
NextKeyBytes returns the key following an initial key as a byte slice.
Passing nil will return the first key.
Use Iterate if you want to traverse all entries in the map.
Returns nil if there are no more keys.
func (m *Map) Pin(fileName string) error
Pin persists the map on the BPF virtual file system past the lifetime of the process that created it .
Calling Pin on a previously pinned map will overwrite the path, except when the new path already exists. Re-pinning across filesystems is not supported. You can Clone a map to pin it to a different path.
This requires bpffs to be mounted above fileName. See https://docs.cilium.io/en/k8s-doc/admin/#admin-mount-bpffs
func (m *Map) Put(key, value interface{}) error
Put replaces or creates a value in map.
It is equivalent to calling Update with UpdateAny.
func (m *Map) String() string
func (m *Map) Type() MapType
Type returns the underlying type of the map.
func (m *Map) Unpin() error
Unpin removes the persisted state for the map from the BPF virtual filesystem.
Failed calls to Unpin will not alter the state returned by IsPinned.
Unpinning an unpinned Map returns nil.
func (m *Map) Update(key, value interface{}, flags MapUpdateFlags) error
Update changes the value of a key.
func (m *Map) ValueSize() uint32
ValueSize returns the size of the map value in bytes.
MapID represents the unique ID of an eBPF map
type MapID uint32
func MapGetNextID(startID MapID) (MapID, error)
MapGetNextID returns the ID of the next eBPF map.
Returns ErrNotExist, if there is no next eBPF map.
MapInfo describes a map.
type MapInfo struct { Type MapType KeySize uint32 ValueSize uint32 MaxEntries uint32 Flags uint32 // Name as supplied by user space at load time. Available from 4.15. Name string // contains filtered or unexported fields }
func (mi *MapInfo) ID() (MapID, bool)
ID returns the map ID.
Available from 4.13.
The bool return value indicates whether this optional field is available.
MapIterator iterates a Map.
See Map.Iterate.
type MapIterator struct {
// contains filtered or unexported fields
}
func (mi *MapIterator) Err() error
Err returns any encountered error.
The method must be called after Next returns nil.
Returns ErrIterationAborted if it wasn't possible to do a full iteration.
func (mi *MapIterator) Next(keyOut, valueOut interface{}) bool
Next decodes the next key and value.
Iterating a hash map from which keys are being deleted is not safe. You may see the same key multiple times. Iteration may also abort with an error, see IsIterationAborted.
Returns false if there are no more entries. You must check the result of Err afterwards.
See Map.Get for further caveats around valueOut.
MapKV is used to initialize the contents of a Map.
type MapKV struct { Key interface{} Value interface{} }
MapLookupFlags controls the behaviour of the map lookup calls.
type MapLookupFlags uint64
LookupLock look up the value of a spin-locked map.
const LookupLock MapLookupFlags = 4
MapOptions control loading a map into the kernel.
type MapOptions struct { // The base path to pin maps in if requested via PinByName. // Existing maps will be re-used if they are compatible, otherwise an // error is returned. PinPath string LoadPinOptions LoadPinOptions }
MapSpec defines a Map.
type MapSpec struct { // Name is passed to the kernel as a debug aid. Must only contain // alpha numeric and '_' characters. Name string Type MapType KeySize uint32 ValueSize uint32 MaxEntries uint32 // Flags is passed to the kernel and specifies additional map // creation attributes. Flags uint32 // Automatically pin and load a map from MapOptions.PinPath. // Generates an error if an existing pinned map is incompatible with the MapSpec. Pinning PinType // Specify numa node during map creation // (effective only if unix.BPF_F_NUMA_NODE flag is set, // which can be imported from golang.org/x/sys/unix) NumaNode uint32 // The initial contents of the map. May be nil. Contents []MapKV // Whether to freeze a map after setting its initial contents. Freeze bool // InnerMap is used as a template for ArrayOfMaps and HashOfMaps InnerMap *MapSpec // Extra trailing bytes found in the ELF map definition when using structs // larger than libbpf's bpf_map_def. nil if no trailing bytes were present. // Must be nil or empty before instantiating the MapSpec into a Map. Extra *bytes.Reader // The key and value type of this map. May be nil. Key, Value btf.Type // The BTF associated with this map. BTF *btf.Spec }
func (ms *MapSpec) Copy() *MapSpec
Copy returns a copy of the spec.
MapSpec.Contents is a shallow copy.
func (ms *MapSpec) String() string
MapType indicates the type map structure that will be initialized in the kernel.
type MapType uint32
All the various map types that can be created
const ( UnspecifiedMap MapType = iota // Hash is a hash map Hash // Array is an array map Array // ProgramArray - A program array map is a special kind of array map whose map // values contain only file descriptors referring to other eBPF // programs. Thus, both the key_size and value_size must be // exactly four bytes. This map is used in conjunction with the // TailCall helper. ProgramArray // PerfEventArray - A perf event array is used in conjunction with PerfEventRead // and PerfEventOutput calls, to read the raw bpf_perf_data from the registers. PerfEventArray // PerCPUHash - This data structure is useful for people who have high performance // network needs and can reconcile adds at the end of some cycle, so that // hashes can be lock free without the use of XAdd, which can be costly. PerCPUHash // PerCPUArray - This data structure is useful for people who have high performance // network needs and can reconcile adds at the end of some cycle, so that // hashes can be lock free without the use of XAdd, which can be costly. // Each CPU gets a copy of this hash, the contents of all of which can be reconciled // later. PerCPUArray // StackTrace - This holds whole user and kernel stack traces, it can be retrieved with // GetStackID StackTrace // CGroupArray - This is a very niche structure used to help SKBInCGroup determine // if an skb is from a socket belonging to a specific cgroup CGroupArray // LRUHash - This allows you to create a small hash structure that will purge the // least recently used items rather than thow an error when you run out of memory LRUHash // LRUCPUHash - This is NOT like PerCPUHash, this structure is shared among the CPUs, // it has more to do with including the CPU id with the LRU calculation so that if a // particular CPU is using a value over-and-over again, then it will be saved, but if // a value is being retrieved a lot but sparsely across CPUs it is not as important, basically // giving weight to CPU locality over overall usage. LRUCPUHash // LPMTrie - This is an implementation of Longest-Prefix-Match Trie structure. It is useful, // for storing things like IP addresses which can be bit masked allowing for keys of differing // values to refer to the same reference based on their masks. See wikipedia for more details. LPMTrie // ArrayOfMaps - Each item in the array is another map. The inner map mustn't be a map of maps // itself. ArrayOfMaps // HashOfMaps - Each item in the hash map is another map. The inner map mustn't be a map of maps // itself. HashOfMaps // DevMap - Specialized map to store references to network devices. DevMap // SockMap - Specialized map to store references to sockets. SockMap // CPUMap - Specialized map to store references to CPUs. CPUMap // XSKMap - Specialized map for XDP programs to store references to open sockets. XSKMap // SockHash - Specialized hash to store references to sockets. SockHash // CGroupStorage - Special map for CGroups. CGroupStorage // ReusePortSockArray - Specialized map to store references to sockets that can be reused. ReusePortSockArray // PerCPUCGroupStorage - Special per CPU map for CGroups. PerCPUCGroupStorage // Queue - FIFO storage for BPF programs. Queue // Stack - LIFO storage for BPF programs. Stack // SkStorage - Specialized map for local storage at SK for BPF programs. SkStorage // DevMapHash - Hash-based indexing scheme for references to network devices. DevMapHash // StructOpsMap - This map holds a kernel struct with its function pointer implemented in a BPF // program. StructOpsMap // RingBuf - Similar to PerfEventArray, but shared across all CPUs. RingBuf // InodeStorage - Specialized local storage map for inodes. InodeStorage // TaskStorage - Specialized local storage map for task_struct. TaskStorage )
func (MapType) Max() MapType
Max returns the latest supported MapType.
func (i MapType) String() string
MapUpdateFlags controls the behaviour of the Map.Update call.
The exact semantics depend on the specific MapType.
type MapUpdateFlags uint64
const ( // UpdateAny creates a new element or update an existing one. UpdateAny MapUpdateFlags = iota // UpdateNoExist creates a new element. UpdateNoExist MapUpdateFlags = 1 << (iota - 1) // UpdateExist updates an existing element. UpdateExist // UpdateLock updates elements under bpf_spin_lock. UpdateLock )
PinType determines whether a map is pinned into a BPFFS.
type PinType int
Valid pin types.
Mirrors enum libbpf_pin_type.
const ( PinNone PinType = iota // Pin an object by using its name as the filename. PinByName )
func (i PinType) String() string
Program represents BPF program loaded into the kernel.
It is not safe to close a Program which is used by other goroutines.
type Program struct { // Contains the output of the kernel verifier if enabled, // otherwise it is empty. VerifierLog string // contains filtered or unexported fields }
▹ Example (RetrieveVerifierOutput)
▹ Example (UnmarshalFromMap)
▹ Example (VerifierError)
func LoadPinnedProgram(fileName string, opts *LoadPinOptions) (*Program, error)
LoadPinnedProgram loads a Program from a BPF file.
Requires at least Linux 4.11.
func NewProgram(spec *ProgramSpec) (*Program, error)
NewProgram creates a new Program.
See NewProgramWithOptions for details.
func NewProgramFromFD(fd int) (*Program, error)
NewProgramFromFD creates a program from a raw fd.
You should not use fd after calling this function.
Requires at least Linux 4.10.
func NewProgramFromID(id ProgramID) (*Program, error)
NewProgramFromID returns the program for a given id.
Returns ErrNotExist, if there is no eBPF program with the given id.
func NewProgramWithOptions(spec *ProgramSpec, opts ProgramOptions) (*Program, error)
NewProgramWithOptions creates a new Program.
Loading a program for the first time will perform feature detection by loading small, temporary programs.
Returns an error wrapping VerifierError if the program or its BTF is rejected by the kernel.
func (p *Program) Benchmark(in []byte, repeat int, reset func()) (uint32, time.Duration, error)
Benchmark runs the Program with the given input for a number of times and returns the time taken per iteration.
Returns the result of the last execution of the program and the time per run or an error. reset is called whenever the benchmark syscall is interrupted, and should be set to testing.B.ResetTimer or similar.
Note: profiling a call to this function will skew it's results, see https://github.com/cilium/ebpf/issues/24
This function requires at least Linux 4.12.
func (p *Program) BindMap(m *Map) error
BindMap binds map to the program and is only released once program is released.
This may be used in cases where metadata should be associated with the program which otherwise does not contain any references to the map.
func (p *Program) Clone() (*Program, error)
Clone creates a duplicate of the Program.
Closing the duplicate does not affect the original, and vice versa.
Cloning a nil Program returns nil.
func (p *Program) Close() error
Close the Program's underlying file descriptor, which could unload the program from the kernel if it is not pinned or attached to a kernel hook.
func (p *Program) FD() int
FD gets the file descriptor of the Program.
It is invalid to call this function after Close has been called.
func (p *Program) Handle() (*btf.Handle, error)
Handle returns a reference to the program's type information in the kernel.
Returns ErrNotSupported if the kernel has no BTF support, or if there is no BTF associated with the program.
func (p *Program) Info() (*ProgramInfo, error)
Info returns metadata about the program.
Requires at least 4.10.
func (p *Program) IsPinned() bool
IsPinned returns true if the Program has a non-empty pinned path.
func (p *Program) Pin(fileName string) error
Pin persists the Program on the BPF virtual file system past the lifetime of the process that created it
Calling Pin on a previously pinned program will overwrite the path, except when the new path already exists. Re-pinning across filesystems is not supported.
This requires bpffs to be mounted above fileName. See https://docs.cilium.io/en/k8s-doc/admin/#admin-mount-bpffs
func (p *Program) Run(opts *RunOptions) (uint32, error)
Run runs the Program in kernel with given RunOptions.
Note: the same restrictions from Test apply.
func (p *Program) String() string
func (p *Program) Test(in []byte) (uint32, []byte, error)
Test runs the Program in the kernel with the given input and returns the value returned by the eBPF program. outLen may be zero.
Note: the kernel expects at least 14 bytes input for an ethernet header for XDP and SKB programs.
This function requires at least Linux 4.12.
func (p *Program) Type() ProgramType
Type returns the underlying type of the program.
func (p *Program) Unpin() error
Unpin removes the persisted state for the Program from the BPF virtual filesystem.
Failed calls to Unpin will not alter the state returned by IsPinned.
Unpinning an unpinned Program returns nil.
ProgramID represents the unique ID of an eBPF program.
type ProgramID uint32
func ProgramGetNextID(startID ProgramID) (ProgramID, error)
ProgramGetNextID returns the ID of the next eBPF program.
Returns ErrNotExist, if there is no next eBPF program.
ProgramInfo describes a program.
type ProgramInfo struct { Type ProgramType // Truncated hash of the BPF bytecode. Available from 4.13. Tag string // Name as supplied by user space at load time. Available from 4.15. Name string // contains filtered or unexported fields }
func (pi *ProgramInfo) BTFID() (btf.ID, bool)
BTFID returns the BTF ID associated with the program.
The ID is only valid as long as the associated program is kept alive. Available from 5.0.
The bool return value indicates whether this optional field is available and populated. (The field may be available but not populated if the kernel supports the field but the program was loaded without BTF information.)
func (pi *ProgramInfo) ID() (ProgramID, bool)
ID returns the program ID.
Available from 4.13.
The bool return value indicates whether this optional field is available.
func (pi *ProgramInfo) Instructions() (asm.Instructions, error)
Instructions returns the 'xlated' instruction stream of the program after it has been verified and rewritten by the kernel. These instructions cannot be loaded back into the kernel as-is, this is mainly used for inspecting loaded programs for troubleshooting, dumping, etc.
For example, map accesses are made to reference their kernel map IDs, not the FDs they had when the program was inserted. Note that before the introduction of bpf_insn_prepare_dump in kernel 4.16, xlated instructions were not sanitized, making the output even less reusable and less likely to round-trip or evaluate to the same program Tag.
The first instruction is marked as a symbol using the Program's name.
Available from 4.13. Requires CAP_BPF or equivalent.
func (pi *ProgramInfo) MapIDs() ([]MapID, bool)
MapIDs returns the maps related to the program.
Available from 4.15.
The bool return value indicates whether this optional field is available.
func (pi *ProgramInfo) RunCount() (uint64, bool)
RunCount returns the total number of times the program was called.
Can return 0 if the collection of statistics is not enabled. See EnableStats(). The bool return value indicates whether this optional field is available.
func (pi *ProgramInfo) Runtime() (time.Duration, bool)
Runtime returns the total accumulated runtime of the program.
Can return 0 if the collection of statistics is not enabled. See EnableStats(). The bool return value indicates whether this optional field is available.
ProgramOptions control loading a program into the kernel.
type ProgramOptions struct { // Controls the detail emitted by the kernel verifier. Set to non-zero // to enable logging. LogLevel uint32 // Controls the output buffer size for the verifier. Defaults to // DefaultVerifierLogSize. LogSize int // Type information used for CO-RE relocations and when attaching to // kernel functions. // // This is useful in environments where the kernel BTF is not available // (containers) or where it is in a non-standard location. Defaults to // use the kernel BTF from a well-known location if nil. KernelTypes *btf.Spec }
ProgramSpec defines a Program.
type ProgramSpec struct { // Name is passed to the kernel as a debug aid. Must only contain // alpha numeric and '_' characters. Name string // Type determines at which hook in the kernel a program will run. Type ProgramType // AttachType of the program, needed to differentiate allowed context // accesses in some newer program types like CGroupSockAddr. // // Available on kernels 4.17 and later. AttachType AttachType // Name of a kernel data structure or function to attach to. Its // interpretation depends on Type and AttachType. AttachTo string // The program to attach to. Must be provided manually. AttachTarget *Program // The name of the ELF section this program orininated from. SectionName string Instructions asm.Instructions // Flags is passed to the kernel and specifies additional program // load attributes. Flags uint32 // License of the program. Some helpers are only available if // the license is deemed compatible with the GPL. // // See https://www.kernel.org/doc/html/latest/process/license-rules.html#id1 License string // Version used by Kprobe programs. // // Deprecated on kernels 5.0 and later. Leave empty to let the library // detect this value automatically. KernelVersion uint32 // The BTF associated with this program. Changing Instructions // will most likely invalidate the contained data, and may // result in errors when attempting to load it into the kernel. BTF *btf.Spec // The byte order this program was compiled for, may be nil. ByteOrder binary.ByteOrder }
func (ps *ProgramSpec) Copy() *ProgramSpec
Copy returns a copy of the spec.
func (ps *ProgramSpec) Tag() (string, error)
Tag calculates the kernel tag for a series of instructions.
Use asm.Instructions.Tag if you need to calculate for non-native endianness.
▹ Example
ProgramType of the eBPF program
type ProgramType uint32
eBPF program types
const ( UnspecifiedProgram ProgramType = iota SocketFilter Kprobe SchedCLS SchedACT TracePoint XDP PerfEvent CGroupSKB CGroupSock LWTIn LWTOut LWTXmit SockOps SkSKB CGroupDevice SkMsg RawTracepoint CGroupSockAddr LWTSeg6Local LircMode2 SkReuseport FlowDissector CGroupSysctl RawTracepointWritable CGroupSockopt Tracing StructOps Extension LSM SkLookup Syscall )
func (ProgramType) Max() ProgramType
Max return the latest supported ProgramType.
func (i ProgramType) String() string
Various options for Run'ing a Program
type RunOptions struct { // Program's data input. Required field. Data []byte // Program's data after Program has run. Caller must allocate. Optional field. DataOut []byte // Program's context input. Optional field. Context interface{} // Program's context after Program has run. Must be a pointer or slice. Optional field. ContextOut interface{} // Number of times to run Program. Optional field. Defaults to 1. Repeat uint32 // Optional flags. Flags uint32 // CPU to run Program on. Optional field. // Note not all program types support this field. CPU uint32 // Called whenever the syscall is interrupted, and should be set to testing.B.ResetTimer // or similar. Typically used during benchmarking. Optional field. Reset func() }
type VerifierError = internal.VerifierError
Name | Synopsis |
---|---|
.. | |
asm | Package asm is an assembler for eBPF bytecode. |
btf | Package btf handles data encoded according to the BPF Type Format. |
cmd | |
bpf2go | Program bpf2go embeds eBPF in Go. |
test | Package test checks that the code generated by bpf2go conforms to a specific API. |
features | Package features allows probing for BPF features available to the calling process. |
link | Package link allows attaching eBPF programs to various kernel hooks. |
perf | Package perf allows interacting with Linux perf_events. |
ringbuf | Package ringbuf allows interacting with Linux BPF ring buffer. |
rlimit | Package rlimit allows raising RLIMIT_MEMLOCK if necessary for the use of BPF. |