tinybpf

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2026 License: MIT Imports: 11 Imported by: 0

README

tinybpf

tinybpf

Write eBPF programs in Go. Compile with TinyGo. Run in the Linux kernel.

CI Go Report Card License


What is tinybpf?

eBPF lets sandboxed programs run inside the Linux kernel. Today those programs must be written in C or Rust. tinybpf is a Go library and CLI that lets you write them in Go instead.

graph LR
    A["Go source"] --> B["TinyGo"]
    B --> C["LLVM IR"]
    C --> D["tinybpf"]
    D --> E["bpf.o"]

The output is a standard BPF ELF object compatible with cilium/ebpf, libbpf, and bpftool. See Writing Go for eBPF for how the language subset and compilation model work.

Quick start

Prerequisites

Dependency Version Required
Go 1.24+ Yes
TinyGo 0.40+ Yes
LLVM (llvm-link, opt, llc) 20+ Yes
llvm-ar, llvm-objcopy 20+ For .a / .o inputs
pahole For BTF injection

Install

As a library:

go get github.com/kyleseneker/tinybpf@latest

As a CLI:

go install github.com/kyleseneker/tinybpf/cmd/tinybpf@latest

Or use the setup script (installs all dependencies):

make setup    # install everything
make doctor   # verify toolchain

Build your first BPF object

Scaffold a project:

tinybpf init my_probe
cd my_probe

This generates a tinybpf.json, a BPF source file in bpf/, a stub file for IDE compatibility, and a Makefile. Build it:

make

The output is a BPF ELF object at build/my_probe.bpf.o, ready for any BPF loader.

See Getting Started for a complete walkthrough.

Library usage

Use tinybpf as a Go library to compile BPF objects programmatically:

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/kyleseneker/tinybpf"
)

func main() {
	result, err := tinybpf.Build(context.Background(), tinybpf.Request{
		Package: "./bpf",        // compile Go source via TinyGo
		Output:  "probe.bpf.o",
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("wrote", result.Output)
}

Or link pre-compiled LLVM IR:

result, err := tinybpf.Build(ctx, tinybpf.Request{
	Inputs:    []string{"module_a.ll", "module_b.ll"},
	Output:    "combined.bpf.o",
	EnableBTF: true,
})

See the Request documentation for all available options.

Examples

Example Hook type What it demonstrates
tracepoint-connect Tracepoint Ring buffer, cilium/ebpf loader, live event capture
kprobe-openat Kprobe Function tracing, pt_regs context, architecture offsets
fentry-open Fentry BTF-based tracing (kernel 5.5+)
rawtp-sched Raw tracepoint CO-RE portable structs, perf event array
cgroup-connect Cgroup Hash map blocklist, connection policy
xdp-filter XDP Packet parsing, source IP blocklist
tc-filter TC classifier Port-based packet filtering

Build and run any example in one command:

make example NAME=tracepoint-connect
sudo ./examples/tracepoint-connect/scripts/run.sh

See Examples Guide for learning tracks and how to run them.

Documentation

Document Description
Getting Started Install, scaffold, build, and load your first BPF program
Writing Go for eBPF Language constraints, helpers, CO-RE, and patterns
CLI Reference Every command, flag, and default
Config Reference tinybpf.json schema, auto-discovery, and merge rules
Examples Guide Learning tracks and how to run examples
Troubleshooting Setup issues, pipeline errors, and verifier debugging
Architecture Pipeline design and the 8-pass IR transformation
Support Matrix Tested toolchain versions, kernels, and platforms
Project Layout Package map for contributors
Contributing Development setup, testing, and PR process
Project Relationship
cilium/ebpf Go library for loading eBPF programs; loads tinybpf output
bpf2go Compiles C eBPF and generates Go bindings; replaced when the program is Go
libbpf C loader library; compatible with tinybpf output
TinyGo Go compiler targeting LLVM; provides the IR that tinybpf transforms
Aya eBPF in Rust; similar goal, different language
miekg/bpf Prior effort to add BPF to TinyGo's LLVM; archived

License

MIT

Documentation

Overview

Package tinybpf compiles Go source or pre-compiled LLVM IR into BPF ELF objects suitable for loading with cilium/ebpf or libbpf.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Request

type Request struct {
	// Package is a Go package path to compile via TinyGo.
	// Mutually exclusive with Inputs.
	Package string

	// Inputs are pre-compiled LLVM IR/bitcode files to link.
	// Supported extensions: .ll, .bc, .o, .a.
	// Mutually exclusive with Package.
	Inputs []string

	// Output is the path for the resulting BPF ELF object.
	// Defaults to "bpf.o" if empty.
	Output string

	// CPU is the BPF CPU version passed to llc (e.g. "v3").
	// Defaults to "v3" if empty.
	CPU string

	// EnableBTF injects BTF type information via pahole.
	EnableBTF bool

	// ProgramType constrains section validation to a specific BPF program
	// type (e.g. "kprobe", "xdp", "tracepoint").
	ProgramType string

	// Programs lists BPF program function names to keep.
	// Auto-detected from IR if omitted.
	Programs []string

	// Sections maps program function names to ELF section names
	// (e.g. "handle_connect" -> "tracepoint/syscalls/sys_enter_connect").
	Sections map[string]string

	// OptProfile selects a named optimization profile:
	// "conservative", "default", "aggressive", or "verifier-safe".
	// Defaults to "default" if empty.
	OptProfile string

	// PassPipeline is an explicit LLVM opt pass pipeline string.
	// Overrides OptProfile when set.
	PassPipeline string

	// CustomPasses are additional LLVM pass names appended to the pipeline.
	CustomPasses []string

	// Timeout is the per-stage command timeout. Defaults to 30s.
	Timeout time.Duration

	// KeepTemp preserves intermediate artifacts after the run.
	KeepTemp bool

	// TempDir specifies a directory for intermediate artifacts.
	// When set, artifacts are kept regardless of KeepTemp.
	TempDir string

	// Cache enables the content-addressed build cache.
	Cache bool

	// DumpIR writes intermediate IR after each transform stage.
	DumpIR bool

	// Verbose enables detailed stage logging to Stdout/Stderr.
	Verbose bool

	// Jobs controls parallel input normalization workers. Defaults to 1.
	Jobs int

	// Toolchain overrides default tool discovery for LLVM and TinyGo binaries.
	Toolchain Toolchain

	// Stdout receives verbose and informational output.
	// Defaults to [io.Discard] if nil.
	Stdout io.Writer

	// Stderr receives warning and error detail output.
	// Defaults to [io.Discard] if nil.
	Stderr io.Writer
}

Request describes the inputs and options for a BPF compilation.

type Result

type Result struct {
	// Output is the path to the final BPF ELF object.
	Output string

	// TempDir is the directory containing intermediate artifacts,
	// populated when KeepTemp is true or TempDir was specified.
	TempDir string
}

Result holds the outputs of a successful Build.

func Build

func Build(ctx context.Context, req Request) (*Result, error)

Build compiles Go source or links pre-compiled LLVM IR into a BPF ELF object.

type Toolchain

type Toolchain struct {
	TinyGo   string
	LLVMLink string
	Opt      string
	LLC      string
	LLVMAr   string
	Objcopy  string
	Pahole   string
}

Toolchain configures explicit paths to LLVM and TinyGo binaries.

Directories

Path Synopsis
cmd
tinybpf command
Package config loads tinybpf project configuration from a tinybpf.json file and converts it to github.com/kyleseneker/tinybpf.Request values.
Package config loads tinybpf project configuration from a tinybpf.json file and converts it to github.com/kyleseneker/tinybpf.Request values.
Package diag provides structured, stage-attributed error types for the tinybpf pipeline.
Package diag provides structured, stage-attributed error types for the tinybpf pipeline.
Package elfcheck validates that an output file is a well-formed eBPF ELF object.
Package elfcheck validates that an output file is a well-formed eBPF ELF object.
internal
cache
Package cache provides a content-addressed build cache for pipeline artifacts.
Package cache provides a content-addressed build cache for pipeline artifacts.
cli
Package cli implements the tinybpf command-line interface.
Package cli implements the tinybpf command-line interface.
doctor
Package doctor implements the `tinybpf doctor` subcommand, which discovers and version-checks all LLVM toolchain binaries.
Package doctor implements the `tinybpf doctor` subcommand, which discovers and version-checks all LLVM toolchain binaries.
ir
Package ir provides a lightweight AST and round-trip parser for the subset of LLVM IR that TinyGo emits.
Package ir provides a lightweight AST and round-trip parser for the subset of LLVM IR that TinyGo emits.
llvm
Package llvm provides typed wrappers for discovering and executing LLVM toolchain binaries (llvm-link, opt, llc, and optional helpers).
Package llvm provides typed wrappers for discovering and executing LLVM toolchain binaries (llvm-link, opt, llc, and optional helpers).
pipeline
Package pipeline orchestrates the LLVM tool stages that transform input IR/bitcode into a valid eBPF ELF object.
Package pipeline orchestrates the LLVM tool stages that transform input IR/bitcode into a valid eBPF ELF object.
scaffold
Package scaffold generates the file structure for a new tinybpf project.
Package scaffold generates the file structure for a new tinybpf project.
testutil
Package testutil provides shared, portable test helpers for internal packages.
Package testutil provides shared, portable test helpers for internal packages.
transform
Package transform converts TinyGo-emitted LLVM IR into BPF-compatible IR via structured AST rewrites.
Package transform converts TinyGo-emitted LLVM IR into BPF-compatible IR via structured AST rewrites.

Jump to

Keyboard shortcuts

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