ebpfhost

package module
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: 18 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.

README

ebpfhost

Linux/amd64 tracefs capture and ELF function resolution. This backend installs uprobes, return probes and optional scheduler tracepoints in an owned trace instance. It does not load an eBPF program; bpfload is a separate facility.

Tracefs must be mounted and writable. Capture requires appropriate kernel privileges. The instance uses the kernel mono clock. Raw line timestamps do not establish sensor timing, cross-process clock mappings, precise workload joins or loss-free acquisition. Per-CPU buffers are bounded by BufferKB; kernel overwrite and other losses remain unknown to this raw backend.

PID filtering covers existing threads. With scheduler capture, payload filters are fixed to that initial thread snapshot; threads created later are not covered. Child following is disabled so forked processes cannot acquire the parent identity. Use a fixed-thread workload or treat thread coverage as incomplete.

Close disables instance events, unregisters only owned probe names and removes the instance. All partial setup failures attempt the same cleanup and return cleanup errors. Read cancellation polls at 10 ms while idle and limits each raw line to 1 MiB. No live kernel or GPU qualification is claimed by CPU tests.

Documentation

Overview

Package ebpfhost collects Linux tracefs events from isolated trace instances. It uses kernel uprobes and scheduler tracepoints, not an eBPF program. Opening a collector requires tracefs access; loss is unknown unless independently established from kernel statistics. The supported source platforms are linux/amd64 and linux/arm64.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ProcessStartTime

func ProcessStartTime(pid int) (uint64, error)

ProcessStartTime returns /proc stat starttime ticks, a PID generation token. This is not a clock mapping or proof of workload identity.

func ResolveImagesFile

func ResolveImagesFile(file *os.File, symbols []string, maxBytes int64) (map[string]Image, error)

ResolveImagesFile resolves up to 256 distinct, nonempty symbol names, each at its default version as ResolveImage does, from one bounded descriptor snapshot. ELF parsing, SHA256 and build-ID extraction run once. Missing or undefined symbols are absent from the returned map; malformed or ambiguous requested definitions return an error. File limits, descriptor ownership and concurrent-change restrictions match ResolveImageFile.

Example
_, err := ResolveImagesFile(nil, []string{"cudaLaunchKernel", "cudaMalloc"}, 32<<20)
fmt.Println(err != nil)
Output:
true

func ResolveSymbol

func ResolveSymbol(path, name string) (uint64, error)

ResolveSymbol returns the executable file offset of an ELF symbol.

Types

type Collector

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

Collector owns one tracefs instance and its uniquely named global probes. Read may have only one concurrent caller. Close interrupts Read.

func Open

func Open(cfg Config) (_ *Collector, err error)

Open installs probes and enables an isolated tracefs instance.

func (*Collector) Close

func (c *Collector) Close() error

Close disables capture, closes the reader, removes owned probes and instance. Failed cleanup is retried on subsequent calls. The first cleanup error remains visible even after retry removes the remaining resources.

func (*Collector) Read

func (c *Collector) Read(ctx context.Context) (Record, error)

Read waits for one raw line. It bounds each line to 1 MiB and respects cancellation.

func (*Collector) TraceClock

func (c *Collector) TraceClock() string

TraceClock reports the explicitly selected tracefs clock.

Example
c := new(Collector)
fmt.Println(c.TraceClock())
Output:
mono

type Config

type Config struct {
	PID       int
	TraceRoot string
	Probes    []Probe
	Scheduler bool
	Lifecycle bool
	BufferKB  int
}

Config describes an isolated tracefs capture. PID selects one process and its existing threads; Scheduler also filters scheduler payload PIDs for that process.

type Frame

type Frame struct {
	PC                                   uint64
	ImageSHA256, DeclaredBuildID, Symbol string
	SymbolVersion, Reason                string
	SymbolOffset                         uint64
}

Frame is one observed native address. An empty Symbol has an explicit Reason. DeclaredBuildID is copied from the admitted descriptor; ImageSHA256 is recomputed from the supplied bytes. Native symbols are not logical Python frames, and SymbolOffset is an offset into a known nonzero function interval.

type FrameContext

type FrameContext struct {
	PID                uint32
	Generation, ExecID uint64
}

FrameContext identifies one process image lifetime. Generation is the caller's process-start token, not a thread token. These fields express caller consistency only; this package does not inspect a running process.

type FrameReport

type FrameReport struct {
	Context                      FrameContext
	CaptureID                    int64
	Requested                    bool
	Unavailable                  string
	FramePointerStatus           string
	Frames                       []Frame
	Partial, Truncated           bool
	IdentityScope, LogicalFrames string
}

FrameReport never claims a complete unwind. Truncated means the bounded capture cannot establish completeness, not a count of missing frames. LogicalFrames is always unresolved_not_captured. Frames preserves every PC, including repeated addresses. Context and image mappings are caller assertions.

type FrameResolver

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

FrameResolver snapshots admitted mapping bytes and indexes ordinary ELF symbol tables. Its zero value is not usable. It opens no path and performs no target-memory read, unwind, tool invocation or live identity verification. It is safe for concurrent calls after construction.

func NewFrameResolver

func NewFrameResolver(context FrameContext, images []MappedFrameImage) (*FrameResolver, error)

NewFrameResolver accepts at most64 mappings,16MiB total image bytes and65536 table symbols, with names at most4096bytes. Inputs must be caller-admitted ordinary ELF images; these API/index bounds are not hostile-ELF declared-work or allocation-safety admission for debug/elf. No fuzz/security claim follows. Data and mappings are snapshotted; callers must not mutate them concurrently with this call. ELF symbol names/versions are retained without demangling.

Example
// Ordinary inert metadata from this example's fixture helper, never loaded.
image := frameImage(frameFixture(elf.ET_DYN, "observed", false, false))
r, err := ebpfhost.NewFrameResolver(frameContext(), []ebpfhost.MappedFrameImage{image})
fmt.Println(r != nil, err)
Output:
true <nil>

func (*FrameResolver) ResolveStack

func (r *FrameResolver) ResolveStack(c StackCapture) (FrameReport, error)

ResolveStack symbolizes at most eight actual PCs against the snapshotted mappings. PID/generation and known execution epochs must agree. Unknown execution context retains PCs as unresolved. No address is added, reordered or adjusted to guess a return address. Caller declarations do not authenticate running mappings or frame-pointer coverage.

Example
image := frameImage(frameFixture(elf.ET_DYN, "observed", false, false))
r, err := ebpfhost.NewFrameResolver(frameContext(), []ebpfhost.MappedFrameImage{image})
if err != nil {
	fmt.Println(err)
	return
}
report, err := r.ResolveStack(captureFrames(0x700028))
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(report.Frames[0].Symbol, report.Frames[0].SymbolOffset, report.Partial)
fmt.Println(report.IdentityScope, report.LogicalFrames)
Output:
observed 8 true
caller_mapping_consistency_only unresolved_not_captured

type Image

type Image struct {
	Path, BuildID, SHA256 string
	Symbol, SymbolVersion string
	Size                  int64
	Offset                uint64
}

Image records the exact file used to resolve a probe.

func ResolveImage

func ResolveImage(path, symbol string) (Image, error)

ResolveImage resolves a regular function and records the image identity.

func ResolveImageFile

func ResolveImageFile(file *os.File, symbol, version string, maxBytes int64) (Image, error)

ResolveImageFile is like ResolveImageVersion but reads a held regular file. maxBytes must be in 1..256 MiB. Reads use ReaderAt, preserving the descriptor offset and ownership; the file is never reopened or closed. Path is file.Name(), which may describe a pathname that has since been replaced. Identity and offsets refer only to the bounded byte snapshot read from this descriptor. Changes in file size or modification time during capture are refused; this is not a lock against concurrent in-place modification after resolution.

Example
// The caller owns the held descriptor and supplies an explicit read budget.
_, err := ResolveImageFile(nil, "cudaLaunchKernel", "", 32<<20)
fmt.Println(err != nil)
Output:
true

func ResolveImageVersion

func ResolveImageVersion(path, symbol, version string) (Image, error)

ResolveImageVersion resolves an exact GNU ELF symbol version. An empty version selects the default dynamic version, or an unversioned symbol. SymbolVersion in the returned Image is read from the file, not copied from the request. PLT stubs and indirect functions are refused rather than followed.

Example
dir, err := os.MkdirTemp("", "elf-version-example-")
if err != nil {
	fmt.Println(err)
	return
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "probe.so")
if err := os.WriteFile(path, versionELF(), 0600); err != nil {
	fmt.Println(err)
	return
}
image, err := ResolveImageVersion(path, "probe", "V1")
if err != nil {
	fmt.Println(err)
	return
}
fmt.Printf("%s@%s at %#x\n", image.Symbol, image.SymbolVersion, image.Offset)
Output:
probe@V1 at 0x100

type MappedFrameImage

type MappedFrameImage struct {
	Identity               Image
	Data                   []byte
	Start, End, FileOffset uint64
}

MappedFrameImage supplies an admitted ordinary ELF image and one executable runtime mapping. Identity.Size and SHA256 must match Data. BuildID and Path remain caller descriptor provenance, not independently observed live facts. FileOffset is the image offset corresponding to Start; End is exclusive.

type Probe

type Probe struct {
	Path      string
	Offset    uint64
	Name      string
	Return    bool
	FetchArgs string
}

Probe describes a file-offset uprobe. FetchArgs is tracefs fetch syntax.

type Record

type Record struct{ Line string }

Record is a raw tracefs line; its timestamp belongs to the selected mono clock. Raw records do not prove loss-free capture or application workload identity.

type StackCapture

type StackCapture struct {
	Context                           FrameContext
	ID                                int64
	PCs                               []uint64
	Requested                         bool
	Unavailable                       string
	FramePointersKnown, FramePointers bool
}

StackCapture contains only observed addresses and explicit coverage context. FramePointersKnown/FramePointers are caller declarations, not inferred from ELF symbols. ID is an optional producer identifier. PCs retain capture order.

Directories

Path Synopsis
Package bpfload loads Linux BPF programs and opens pinned BPF maps.
Package bpfload loads Linux BPF programs and opens pinned BPF maps.
Package hostmetrics reads caller-selected Linux node statistics without opening files, discovering devices, or associating a node with a GPU.
Package hostmetrics reads caller-selected Linux node statistics without opening files, discovering devices, or associating a node with a GPU.

Jump to

Keyboard shortcuts

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