A 'global x' statement is a fact about one function's scope, but it was
tracked as current_func_globals on the compilation-wide context -- per-function
state living at the wrong level, which had to be set before each body and
reset after, and which every read and write site then had to consult in a
specific order relative to local_sym_tab (the source of the parameter
collision fixed in f4ec12d).
The declaration now does what it means: it binds the name in local_sym_tab to
the @bpfglobal's storage, as a LocalSymbol whose var is the GlobalVariable and
whose declared_global flag records why. A GlobalVariable is a pointer to
storage exactly as an alloca is, so every existing path that loads from or
stores through a symbol's var works unchanged. That deletes the dedicated
global-store branch in handle_variable_assignment, the global branch in
handle_aug_assign, the allocation-pass skip, and the reset -- one table, one
lookup, no order to get wrong. Reads of an undeclared global (legal in Python)
still fall back to bpf_globals after local_sym_tab.
Python's rules fall out naturally: a parameter is already in the table when
the declarations are processed, so 'global ctx' on a parameter is detected by
the same membership check. LocalSymbol.__iter__ deliberately still yields
three fields, since several sites tuple-unpack a symbol.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BSDVsZH5NtoASyxB8FCtGU
Python-BPF is an LLVM IR generator for eBPF programs written in Python. It uses llvmlite to generate LLVM IR and then compiles to LLVM object files. These object files can be loaded into the kernel for execution. Python-BPF performs compilation without relying on BCC.
Note
: This project is under active development and not ready for production use.
Overview
- Generate eBPF programs directly from Python.
- Compile to LLVM object files for kernel execution.
- Built with
llvmlitefor IR generation. - Supports maps, helpers, and global definitions for BPF.
- Companion project: pylibbpf, which provides the bindings required for object loading and execution.
Installation
Dependencies:
bpftoolclang- Python ≥ 3.8
Install via pip:
pip install pythonbpf pylibbpf
Try It Out!
First, generate the vmlinux.py file for your kernel:
- Install the required dependencies:
- On Ubuntu:
sudo apt-get install bpftool clang
pip install pythonbpf pylibbpf ctypeslib2
- Generate the
vmlinux.pyusing:
sudo tools/vmlinux-gen.py
- Copy this file to
BCC-Examples/
Next, install requirements for BCC-Examples:
- These requirements are only required for the python notebooks, vfsreadlat and container-monitor examples.
pip install -r BCC-Examples/requirements.txt
- Now, follow the instructions in the BCC-Examples/README.md to run the examples.
To spin up jupyter notebook examples:
- Run and follow the instructions on screen
curl -s https://raw.githubusercontent.com/pythonbpf/Python-BPF/refs/heads/master/tools/setup.sh | sudo bash
- Check the jupyter server on the web browser and run the notebooks in the
BCC-Examples/folder.
Example Usage
import time
from pythonbpf import bpf, map, section, bpfglobal, BPF
from pythonbpf.helper import pid
from pythonbpf.maps import HashMap
from pylibbpf import *
from ctypes import c_void_p, c_int64, c_uint64, c_int32
import matplotlib.pyplot as plt
# This program attaches an eBPF tracepoint to sys_enter_clone,
# counts per-PID clone syscalls, stores them in a hash map,
# and then plots the distribution as a histogram using matplotlib.
# It provides a quick view of process creation activity over 10 seconds.
@bpf
@map
def hist() -> HashMap:
return HashMap(key=c_int32, value=c_uint64, max_entries=4096)
@bpf
@section("tracepoint/syscalls/sys_enter_clone")
def hello(ctx: c_void_p) -> c_int64:
process_id = pid()
prev = hist.lookup(process_id)
if prev:
previous_value = prev + 1
print(f"count: {previous_value} with {process_id}")
hist.update(process_id, previous_value)
return 0
else:
hist.update(process_id, 1)
return 0
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
b = BPF()
b.load_and_attach()
hist = BpfMap(b, hist)
print("Recording")
time.sleep(10)
counts = list(hist.values())
plt.hist(counts, bins=20)
plt.xlabel("Clone calls per PID")
plt.ylabel("Frequency")
plt.title("Syscall clone counts")
plt.show()
Architecture
Python-BPF provides a complete pipeline to write, compile, and load eBPF programs in Python:
-
Python Source Code
- Users write BPF programs in Python using decorators like
@bpf,@map,@section, and@bpfglobal. - Maps (hash maps), helpers (e.g.,
ktime,deref), and tracepoints are defined using Python constructs, preserving a syntax close to standard Python.
- Users write BPF programs in Python using decorators like
-
AST Generation
- The Python
astmodule parses the source code into an Abstract Syntax Tree (AST). - Decorators and type annotations are captured to determine BPF maps, tracepoints, and global variables.
- The Python
-
LLVM IR Emission
- The AST is transformed into LLVM Intermediate Representation (IR) using
llvmlite. - IR captures BPF maps, control flow, assignments, and calls to helper functions.
- Debug information is emitted for easier inspection.
- The AST is transformed into LLVM Intermediate Representation (IR) using
-
LLVM Object File Compilation
- The LLVM IR (
.ll) is compiled into a BPF target object file (.o) usingllc -march=bpf -O2. - This produces a kernel-loadable ELF object file containing the BPF bytecode.
- The LLVM IR (
-
libbpf Integration (via pylibbpf)
- The compiled object file can be loaded into the kernel using
pylibbpf. - Maps, tracepoints, and program sections are initialized, and helper functions are resolved.
- Programs are attached to kernel hooks (e.g., syscalls) for execution.
- The compiled object file can be loaded into the kernel using
-
Execution in Kernel
- The kernel executes the loaded eBPF program.
- Hash maps, helpers, and global variables behave as defined in the Python source.
- Output can be read via BPF maps, helper functions, or trace printing.
This architecture eliminates the need for embedding C code in Python, allowing full Python tooling support while generating true BPF object files ready for kernel execution.
Development
-
Create a virtual environment and activate it:
python3 -m venv .venv source .venv/bin/activate -
Install dependencies:
make installThen, run any example in
examples -
Verify an object file with the kernel verifier:
./tools/check.sh check execve2.o -
Run an object file using
bpftool:./tools/check.sh run execve2.o -
Explore LLVM IR output from clang in
examples/c-formby runningmake.