* Core: Lower annotated assignment (x: c_int32 = 0) The annotation types the slot, so `x: c_int32 = 0` is an i32 where the literal alone would give an i64; the store goes through the same handle_variable_assignment plain assignment uses. A bare `x: T` makes the slot and binds nothing. The already-bound and global-shadowing bookkeeping that Assign allocation did inline moves into _bind_name, which both statements now call. * Tests: Annotated assignment passes now * Core: Lower if-branches in the function's return type handle_if processed its branches without passing ret_type down, so a return inside an if fell back to process_stmt's i64 default: a -> c_int32 function got `ret i64 7`, which llc rejects. The branches now go through process_block, which threads ret_type and stops at a statement that ends the block instead of emitting after its terminator. * Core: Lower for-over-range and while loops, with break and continue `for i in range(...)` steps a hidden induction counter, allocated in the entry block next to the loop variable, and copies it into the variable each iteration, so rebinding the variable in the body leaves the trip count alone as in Python (and the loop stays visibly bounded for the verifier). The counter is 64-bit, signed unless the bounds make C's arithmetic unsigned. Bounds are evaluated once, before the loop; the step must be a nonzero integer literal, because its sign picks the loop test. `while` re-evaluates its test at the top of each iteration. `break` and `continue` branch through a loop-target stack on the compilation context; outside a loop they are a SyntaxError, as in Python. A loop's else-branch runs on normal exit only. Anything but range() as the iterable is rejected with NotImplementedError. The allocation pass now descends into loop bodies and counts helper temps in loop headers. Checked against clang -O2 on tests/c-form/loops.bpf.c: the constant-bound cases fold to the same ret, and a helper-bounded loop gets the same rotated loop. * Tests: Loops pass now, plus the cases the lowering promises - passing_tests/loops/: the seven range/while/break/continue/nested tests move over from failing_tests/, joined by rebinding the loop variable, a negative step, loop else-branches, and a helper-bounded loop over a @bpfglobal that survives -O2 as a real loop for the verifier. - failing_tests/loops/: break outside a loop, and a non-literal range step. - for_map_items stays xfail: map iteration needs its own design. - c-form/loops.bpf.c: the clang reference the lowering was checked against. * Tests: Indent the loop C reference with spaces The remove-tabs pre-commit hook rejects tab indentation outside docs/ and Makefiles, which failed the Format job. * Core: Fix loop edge cases the lowering got wrong - `pass` is accepted as a statement, the natural body of a loop run for its side effects. - Falling off the end of a function returns 0 in the function's own return type. After `while True` that block is unreachable, but a c_int32 function still emitted `ret i64 0`, which llc rejected. - A range() step other than 1 could wrap the counter past INT64_MAX or UINT64_MAX back inside the range and loop forever. The step block now ends the loop when the distance left to stop, exact as an unsigned number, is no longer than the step. That is a normal exit, so the else-branch runs. Steps of 1 cannot overshoot and keep the plain loop, so the helper-bounded loop the verifier walks is unchanged. - A step of 2**64 or more no longer truncates to 0: it is a compile error, since it does not fit the counter. Steps from 2**63 up are emitted by their bits. - The counter's signedness folds each bound into a signed 64-bit type rather than joining the bounds alone, so only a c_uint64 bound makes it unsigned: range(-1, n) over a c_uint32 n runs 4 times, as in C with an __s64 counter. * Tests: Run loop programs on the host, plus adversarial loop cases Levels 1 and 2 only prove a loop compiles; one can still run the wrong number of times, or forever. test_loops_run.py JIT-compiles each helper-free passing_tests/loops case on the host (framework/host_jit.py, in a subprocess with a timeout) and checks its return value against what CPython returns for the same body. - passing_tests/loops/: pass bodies, `while True` exited by a return in a c_int32 function, step overflow past INT64_MAX, INT64_MIN and UINT64_MAX, a c_uint32 stop with a negative start, and loop variables that must stay one local (a nested same-name loop, a read after the loop). - failing_tests/loops/range_step_too_wide.py: a 2**64 step is a compile error. - reuse_loop_var_signedness.py is xfail in test_loops_run.py: every local gets one slot typed by its first binding, so a second loop's `i` inherits the first loop's unsigned type. `x = n_u64; x = -3` does the same, so the fix is general, not loop-specific.
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.10
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.