bpfprobe

package
v0.1.0 Latest Latest
Warning

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

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

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

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ReportStack

func ReportStack(event Event, options StackReportOptions, resolver *ebpfhost.FrameResolver) (ebpfhost.FrameReport, error)

ReportStack consumes the actual bounded Event.Stack from Probe.Read. It does not add InstructionPointer, guess a missing generation or recover interpreter frames. Unknown execution identity leaves PCs unresolved. Run after draining; this function performs no attachment, map syscall, tool or target-memory read.

Example
image := stackImage(stackFixture(elf.ET_DYN, "observed", true, false))
r, err := ebpfhost.NewFrameResolver(ebpfhost.FrameContext{PID: 10, Generation: 20, ExecID: 30}, []ebpfhost.MappedFrameImage{image})
if err != nil {
	fmt.Println(err)
	return
}
// Same Event fields as a retained Probe.Read result; this is fixture data.
e := bpfprobe.Event{PIDTGID: uint64(10)<<32 | 11, ExecID: 30, ExecIDKnown: true, UserStackRequested: true, StackID: 7, Stack: []uint64{0x700028}}
out, err := bpfprobe.ReportStack(e, bpfprobe.StackReportOptions{ProcessGeneration: 20}, r)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(out.Frames[0].Symbol, out.Frames[0].SymbolOffset, out.Partial)
Output:
observed 8 true

Types

type Config

type Config struct {
	// ArgumentsMask selects entry ABI slots. Zero preserves legacy capture of
	// all eleven slots. Unrequested slots are zero and absent from Event's mask.
	ArgumentsMask uint16
	// NoArguments explicitly requests no entry arguments or entry pt_regs
	// metadata. It conflicts with ArgumentsMask. Return metadata is unchanged.
	NoArguments bool
	// ProcessGeneration captures the TGID leader start_boottime directly from
	// the kernel. It appends an identity footer; ordinary attachment is opt-in.
	ProcessGeneration bool

	// UserStack captures up to eight user instruction addresses in a bounded
	// 1024-entry stack map. Symbols and Go goroutine identities are not inferred.
	UserStack bool
	Path      string
	Offset    uint64
	PID       int
	Tag       uint64
	Return    bool
	Capacity  int
	// OutputPointer captures an eight-byte value through OutputArgument on
	// successful (low 32-bit status zero) return. Entry and return probes must
	// share a nonzero CorrelationTag. Per-task nesting is bounded to eight;
	// maps are bounded to 4096 bindings and state failures remain explicit.
	OutputPointer bool
	// OutputArgument selects the scalar argument containing OutputPointer.
	OutputArgument uint8
	// MemoryRead requests a bounded copy of user memory.
	MemoryRead     *MemoryRead
	CorrelationTag uint64
	// InheritThreads is unsupported and rejected before attachment. Linux perf
	// reinitializes inherited uprobes in the child, which can prevent thread
	// creation. Attach existing tasks explicitly; future tasks remain unknown.
	InheritThreads bool
	TGID           uint32
	// contains filtered or unexported fields
}

Config identifies one uprobe file offset on a single Linux task (thread). Callers must explicitly attach each thread they intend to observe. PID -1 and system-wide capture are refused by Attach; use AttachSystemGroup for explicit system-wide attachment. Offset is an ELF file offset, not a runtime virtual address. Return requests a uretprobe.

type Event

type Event struct {
	// ProcessGeneration is the group leader start_boottime in kernel boot
	// nanoseconds. It is acquired at the probe, never inferred during draining.
	ProcessGenerationRequested, ProcessGenerationKnown bool
	ProcessGeneration                                  uint64
	// ProcessGenerationError is one when a bounded kernel identity read failed
	// or produced zero. An omitted identity has Requested=false and Error=0.
	ProcessGenerationError uint32
	// MemoryRequested distinguishes a configured read from omitted collection.
	// MemoryKnown means the entire requested copy succeeded. MemoryError uses
	// the same bits as OutputError. Memory is owned by this event.
	MemoryRequested, MemoryKnown bool
	MemoryError                  uint32
	Memory                       []byte
	UserStackRequested           bool
	StackID                      int64
	Stack                        []uint64
	StackUnavailable             string
	ExecID                       uint64
	ExecIDKnown                  bool
	ThreadGeneration             uint64
	ThreadGenerationKnown        bool
	OutputKnown                  bool
	Output                       uint64
	// OutputError bits mark missing state (1), depth overflow (2), unreadable
	// user memory (4), and map operation failure (8).
	OutputError                                   uint32
	ReturnKnown                                   bool
	ArgumentsMask                                 uint16
	Timestamp, PIDTGID, Tag                       uint64
	Arguments                                     [11]uint64
	ReturnValue, StackPointer, InstructionPointer uint64
}

Event records host uprobe register observations, not device execution. Timestamp is kernel monotonic nanoseconds; PIDTGID contains tgid in the upper 32 bits and tid in the lower 32 bits. On amd64 Arguments are the first six SysV integer argument registers followed by five stack slots. On arm64 they are x0..x7 followed by three stack slots under AAPCS64. ArgumentsMask marks successfully acquired slots. Return probes have no arguments; ReturnValue alone is the return register observation.

func DecodeEvent

func DecodeEvent(data []byte) (Event, error)

DecodeEvent decodes a little-endian normalized uprobe record. Legacy records contain 168 bytes. Memory reads of up to 64 bytes append 72 bytes; reads of 65..128 bytes append 136 bytes. ProcessGeneration appends another 16 bytes after any of these layouts.

type Group

type Group struct {
	*Probe
	// contains filtered or unexported fields
}

Group shares one ordered kernel ring across bounded entry/return and task attachments. Tags identify each configured observation. Attachments are installed sequentially; callers must hold their workload until setup returns to obtain a complete start boundary. Add installs new attachments without replacing shared maps; callers must retain explicit coverage boundaries.

func AttachGroup

func AttachGroup(configs []Config) (_ *Group, err error)

AttachGroup creates one kernel ring for all configured attachments.

func (*Group) Add

func (g *Group) Add(configs []Config, verify func() error) error

Add installs additional task attachments into the same ordered event ring. At most 256 attachments may be installed over a group's lifetime. Existing attachments continue observing during setup; new attachments start sequentially. Capacity must match the original group. Stack/output acquisition and ProcessGeneration require maps and task layout provisioned by the original configurations; Add never creates replacement maps.

verify must validate process/task birth identities before and after attachment. It runs under the group mutation lock and must not call group methods. A nil verifier is refused. Verification failure is terminal for future additions.

On an attachment or verification failure, Add closes only new attachments and retains the original group. Events submitted before rollback may remain in the shared ring. Further additions are refused after failure, Disable or Close. The owner must stop, drain and record incomplete coverage; Add does not retry kernel refusals.

Example
package main

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

func main() {
	// Establish a group with AttachGroup first, and supply a verifier checking
	// process and task birth identities against retained /proc evidence.
	var group *bpfprobe.Group
	err := group.Add([]bpfprobe.Config{{PID: 42, Path: "/proc/42/exe"}}, nil)
	fmt.Println(err)
}
Output:
bpf probe: nil group

func (*Group) Close

func (g *Group) Close() error

Close closes all perf attachments before closing their shared ring and maps.

func (*Group) Disable

func (g *Group) Disable() error

Disable stops all attachments while keeping the ring and final counters readable. It must precede a final drain and completeness receipt.

type MemoryRead

type MemoryRead struct {
	Argument    uint8
	Offset      uint32
	Size        uint16
	AtReturn    bool
	SuccessOnly bool
}

MemoryRead selects user memory relative to a scalar argument. Size must be 1..128 and Offset at most 4096. AtReturn saves the pointer at entry and reads it on the paired return, requiring a nonzero CorrelationTag on both probes. SuccessOnly gates return reads on a zero low 32-bit status. Argument is an observed ABI slot, not a source-language parameter index.

Example
read := MemoryRead{Argument: 0, Offset: 8, Size: 64}
fmt.Println(read.Size, read.AtReturn)
Output:
64 false

type OutputFailures

type OutputFailures struct{ Missing, Overflow, Unreadable, MapFailure, GenerationUnknown, ExecUnknown, StackFailure uint64 }

OutputFailures reports missing entry state, nesting overflow, user-memory read refusal, and map operation failures. Counts include failed observations even when the event ring was full; they are not deduplicated request counts.

type Probe

type Probe struct {
	TaskExecOffset, TaskExecSize       uint32
	KernelBTFHash                      string
	TaskStartOffset                    uint32
	TaskGroupLeaderOffset              uint32
	TaskSignalOffset, SignalLiveOffset uint32
	// contains filtered or unexported fields
}

Probe owns a perf-event attachment, loaded BPF program, and ring buffer. Closing disables capture and unmaps buffers; Close is idempotent.

func Attach

func Attach(config Config) (_ *Probe, err error)

Attach loads and attaches an upstream Linux BPF uprobe on amd64 or arm64. It does not modify tracefs, attach GPU driver policies, or retry kernel refusals.

func (*Probe) Close

func (p *Probe) Close() error

func (*Probe) Counts

func (p *Probe) Counts() (submitted, dropped uint64, err error)

Counts reports successful ring submissions and failed submissions. Counts are monotonic kernel counters; callers should sample after disabling capture when they need a final completeness decision.

func (*Probe) Disable

func (p *Probe) Disable() error

Disable stops capture while retaining the event ring and counters.

func (*Probe) OutputFailures

func (p *Probe) OutputFailures() (OutputFailures, error)

func (*Probe) ProcessGenerationFailures

func (p *Probe) ProcessGenerationFailures() (uint64, error)

ProcessGenerationFailures reports refused leader identity reads, including events dropped by a full ring. Probes configured without ProcessGeneration have no such counter; their map lookup returns an error, never a zero count.

Example
var probe Probe
_, err := probe.ProcessGenerationFailures()
fmt.Println(err != nil)
Output:
true

func (*Probe) Read

func (p *Probe) Read(ctx context.Context) (Event, error)

Read waits for and decodes the next record. It may be canceled by ctx or Close. It does not infer device timestamps or request identities.

type Ring

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

Ring reads records from a BPF_MAP_TYPE_RINGBUF map. The zero value is not usable. Only one caller may call Read at a time. Close may run concurrently. The map descriptor remains owned by the caller.

func OpenRing

func OpenRing(fd int, capacity uint32) (*Ring, error)

OpenRing maps a ring-buffer map descriptor. Capacity must match the map's max_entries and must be a power of two and a multiple of the system page size.

func (*Ring) Close

func (r *Ring) Close() error

Close releases both mappings and interrupts a pending Read. It is idempotent.

func (*Ring) Read

func (r *Ring) Read(ctx context.Context) ([]byte, error)

Read waits for the next committed record and returns an owned copy. Discarded records are skipped. Cancellation leaves the next unconsumed record intact.

type StackReportOptions

type StackReportOptions struct {
	ProcessGeneration                 uint64
	FramePointersKnown, FramePointers bool
}

StackReportOptions supplies the caller's process-start snapshot and frame pointer declaration. ProcessGeneration is not Event.ThreadGeneration: Event does not contain a process-start token. Matching declarations establish consistency only, not authentic running-image or unwind coverage.

type SystemConfig

type SystemConfig struct {
	// Lifecycle attaches owned sched_process_exec/exit tracepoints. Records
	// contain only tracked task identities; CUDA remains global unless selected.
	// Last-group exit atomically clears its admission cookie, making
	// ProcessAllowed false even when the final record is dropped.
	Lifecycle bool
	// Lifecycle tags must be distinct, nonzero and disjoint from Add tags.
	LifecycleExecTag, LifecycleExitTag uint64
	// SelectedProcesses restricts capture in BPF to pidfd-authorized TGID
	// leaders before any argument or user-memory observation. It requires task
	// storage helpers for KPROBE programs (upstream Linux 5.13 or later).
	// Kernel refusals remain errors even on newer versions.
	SelectedProcesses bool
	// MaxProcesses bounds admitted pidfd handles; tracking zero uses 4096.
	MaxProcesses   int
	CPUs           []int
	Capacity       int
	MaxAttachments int
}

SystemConfig requests system-wide attachment on explicit CPUs. Hotplug is not followed. MaxAttachments bounds perf descriptors, including additions.

Example
config := SystemConfig{CPUs: []int{0, 1}, MaxAttachments: 128}
fmt.Println(len(config.CPUs), config.MaxAttachments)
Output:
2 128

type SystemGroup

type SystemGroup struct {
	*Probe
	// contains filtered or unexported fields
}

SystemGroup owns one ring and shared bounded correlation maps. Its zero value is not usable. All attachments acquire the kernel TGID leader generation; kernel BTF must describe group_leader as a task_struct pointer. Each attachment change is a coverage boundary: target tasks are not stopped during Add or Remove. Read requires one consumer.

Example
var group *SystemGroup
fmt.Println(group.Close())
Output:
<nil>

func AttachSystemGroup

func AttachSystemGroup(config SystemConfig) (*SystemGroup, error)

AttachSystemGroup creates an empty owner on Linux amd64 or arm64. Kernel privileges and readable BTF are required. Unlike Attach, Add requires PID=0 and opens perf events with pid=-1 on each explicitly configured CPU.

The kernel runs every such event's program on each hit, whatever CPU the event was opened for, so each program first compares bpf_get_smp_processor_id with its own CPU and returns on a mismatch. Each hit is then recorded once, by the event for the CPU it ran on. Upstream Linux 6.6 and later could instead attach one uprobe_multi link per image; the per-CPU form is kept because it works on older kernels.

Example
// An explicit CPU set is required; this configuration never attaches.
_, err := AttachSystemGroup(SystemConfig{MaxAttachments: 128})
fmt.Println(err != nil)
Output:
true

func (*SystemGroup) Add

func (g *SystemGroup) Add(id string, configs []Config) error

Add attaches configs on all owner CPUs under a unique image id. Failure closes every descriptor created by this call. Entry/return memory pairs must be added together with identical read configuration and unique nonzero CorrelationTags. Tags cannot be reused during the owner lifetime, including after failed additions; the historical set is bounded by MaxAttachments. Path names the mapped inode, for example /proc/PID/map_files. PID, TGID, inheritance and user stacks are refused in system mode.

Example
var group SystemGroup
fmt.Println(group.Add("image", []Config{{Path: "image.so"}}) != nil)
Output:
true

func (*SystemGroup) AllowProcess

func (g *SystemGroup) AllowProcess(pidfd int, cookie uint64) error

AllowProcess admits the TGID leader referenced by pidfd with a nonzero cookie. Pass a process pidfd, not a thread pidfd. The caller retains its descriptor, which must remain stable during this call. The group owns a duplicate until RemoveProcess or Close, so caller descriptor reuse cannot retarget revocation. No child process is admitted implicitly. An unsupported kernel returns an error, never a numeric-PID fallback. A duplicate task entry is refused.

Example
var group SystemGroup
fmt.Println(group.AllowProcess(-1, 0) != nil)
Output:
true

func (*SystemGroup) AttachmentCount

func (g *SystemGroup) AttachmentCount() int

AttachmentCount reports owned perf descriptors.

Example
var group SystemGroup
fmt.Println(group.AttachmentCount())
Output:
0

func (*SystemGroup) Close

func (g *SystemGroup) Close() error

Close stops attachments before freeing shared maps and ring. It is idempotent.

Example
var group *SystemGroup
fmt.Println(group.Close())
Output:
<nil>

func (*SystemGroup) Disable

func (g *SystemGroup) Disable() error

Disable stops capture and refuses additions. The ring remains readable and counts remain available until Close, permitting a bounded final drain.

Example
var group *SystemGroup
fmt.Println(group.Disable())
Output:
<nil>

func (*SystemGroup) Epoch

func (g *SystemGroup) Epoch() uint64

Epoch reports attachment changes and attempts, not a device clock.

Example
var group *SystemGroup
fmt.Println(group.Epoch())
Output:
0

func (*SystemGroup) ForgetTask

func (g *SystemGroup) ForgetTask(pidtgid, generation, exec uint64) (int, error)

ForgetTask removes bounded pending entry/return state for an exact observed task identity. The caller must establish that this task generation has exited or been exec-replaced; calling it for a live task loses correlation. It does not remove events already queued in the ring or infer PID identity.

Example
var group SystemGroup
_, err := group.ForgetTask(1, 0, 0)
fmt.Println(err != nil)
Output:
true

func (*SystemGroup) ProcessAllowed

func (g *SystemGroup) ProcessAllowed(pidfd int) (bool, error)

ProcessAllowed checks the original admitted handle against its private duplicate and expected cookie. It does not read process memory, reopen a PID or admit a replacement leader. Missing task storage, including a leader replaced by nonleader exec, returns false. Unknown handles and lookup failures return errors. Caller descriptor reuse cannot retarget the query. The check remains valid after Disable until Close. It is a snapshot; admission may change after this method returns.

Example
var group SystemGroup
_, err := group.ProcessAllowed(-1)
fmt.Println(err != nil)
Output:
true

func (*SystemGroup) Remove

func (g *SystemGroup) Remove(id string) error

Remove closes only id's attachments. Queued events and bounded correlation state may remain. Invalidate pending accounting at the new epoch.

Example
var group SystemGroup
fmt.Println(group.Remove("unknown") != nil)
Output:
true

func (*SystemGroup) RemoveProcess

func (g *SystemGroup) RemoveProcess(pidfd int) error

RemoveProcess revokes only the admission owned under the original caller pidfd handle. It uses the group's duplicate, so a reused caller fd number cannot select a different task. If task storage has a different cookie, only this admission and its duplicate are released; replacement storage is preserved. Lookup failure retains ownership and returns an error. Existing queued records remain readable; callers must retain this coverage boundary in their accounting.

Example
var group SystemGroup
fmt.Println(group.RemoveProcess(-1) != nil)
Output:
true

Jump to

Keyboard shortcuts

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