Compare commits

...

7 Commits

Author SHA1 Message Date
47586a49ad Docs: Stop calling LICENSE required in the user guide overview
The overview example still labelled the LICENSE declaration as required,
which contradicts the GPL default documented in decorators.md and the
quickstart.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 04:26:27 +05:30
4d2bf6842c Docs: Document the GPL default for programs without a LICENSE
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 03:01:13 +05:30
b843b8f343 Core: Default to a GPL license, with a warning, when none is defined
Without a LICENSE, @llvm.compiler.used still named one, and opt stopped on
"use of undefined value @LICENSE". A program with no LICENSE now gets "GPL",
the kernel's own license, and a warning that says so; an explicit LICENSE
is emitted as written.

The old failing license test becomes passing_tests/license_default.py: it
calls print, which lowers to the GPL-only bpf_trace_printk, so the verifier
accepts it only if the default reaches the kernel. license_non_gpl.py is
the counterpart, a verifier-level negative fixture pinned to the kernel's
GPL rejection, and test_license_ir.py checks both license sections and the
warning.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 03:01:11 +05:30
de259c8e86 Merge pull request #109 from pythonbpf/tests/loop-selftests
Port selftests for loop (non-volatile) which are feasible now
2026-10-09 02:21:16 +05:30
99744914ba Tests: Load without -d in the verifier tests, and report a timeout properly
-d asks the kernel for the instruction-level verifier log on every load. For
loop1, which makes the verifier walk nested loops, that log outgrows libbpf's
buffer; the kernel fails the load with ENOSPC, libbpf doubles the buffer and
verifies again, and on CI the load ran past the 30s timeout. A rejection
still comes with its log without -d, since libbpf retries a failed load at
log level 1 and prints it as a warning.

The timeout path also returned a bare string where callers expect stdout and
stderr, so a timeout surfaced as an AttributeError instead of the timeout.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 02:11:02 +05:30
77a5ff15e0 Tests: Port the loop1, loop2, loop4 and loop5 verifier-scale selftests
Four programs from prog_tests/bpf_verif_scale.c that loops alone kept out.
The loop lowering matches clang's for the same C, but volatile, barrier()
and the no-unroll pragma have no spelling here: loop2 folds to a constant
and loop4 unrolls, so those two no longer make the verifier walk a loop.
Their headers and PORTING-NOTES.md say so.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 01:54:15 +05:30
8907fd511a Tools: Stop counting plain loops as a hard blocker in the selftest audit
for/while lower since #106. The iterator loops (bpf_for, bpf_repeat) and the
bpf_loop helper do not, so they keep a hard label of their own, and a
do { } while (0) macro is no longer read as a loop. Against bpf-next 5714ca8
the programs with no hard blocker go from 29 to 39.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 01:54:13 +05:30
17 changed files with 404 additions and 35 deletions

View File

@ -96,9 +96,10 @@ def LICENSE() -> str:
return "GPL"
```
* The Linux kernel requires BPF programs to declare a license
* The Linux kernel reads a license from every BPF program
* Most kernel features require GPL-compatible licenses
* This is defined as a BPF global variable
* If you leave it out, PythonBPF uses `"GPL"` and logs a warning saying so
### Compilation and Execution
@ -197,7 +198,7 @@ def xdp_pass(ctx: c_void_p) -> c_int64:
## Best Practices
1. **Always include a LICENSE** - Required by the kernel
1. **Declare a LICENSE** - Without one, PythonBPF defaults to `"GPL"` and warns
2. **Use type hints** - Required by PythonBPF to generate correct code
3. **Return the correct type** - Match the expected return type for your program type
4. **Test incrementally** - Start simple and add complexity gradually

View File

@ -281,9 +281,10 @@ BPF global variables are values that:
### Common Global Variables
#### LICENSE (Required)
#### LICENSE
Every BPF program must declare a license:
Every BPF program carries a license, which the kernel reads when the program is
loaded. Declare it as a string global:
```python
@bpf
@ -292,14 +293,24 @@ def LICENSE() -> str:
return "GPL"
```
Valid licenses include:
If a program defines no `LICENSE`, PythonBPF uses `"GPL"`, the kernel's own
license, and logs a warning:
```text
No LICENSE defined; defaulting to "GPL". Define @bpf @bpfglobal def LICENSE() -> str to choose another license.
```
Define `LICENSE` yourself to choose a different license or to silence the
warning. The kernel treats these as GPL-compatible:
* `"GPL"` - GNU General Public License
* `"GPL v2"` - GPL version 2
* `"GPL and additional rights"`
* `"Dual BSD/GPL"` - Dual licensed
* `"Dual MIT/GPL"` - Dual licensed
* `"Dual MPL/GPL"` - Dual licensed
```{warning}
Many BPF features require a GPL-compatible license. Using a non-GPL license may prevent your program from loading or accessing certain kernel features.
Many BPF features require a GPL-compatible license. A program with any other license may not call GPL-only helpers, including `bpf_trace_printk`, which `print()` uses; the verifier rejects it with "cannot call GPL-restricted function from non-GPL compatible program".
```
#### Custom Global Variables

View File

@ -69,7 +69,7 @@ def my_function(ctx: c_void_p) -> c_int64:
# BPF logic here
return 0
# License (required)
# License (optional: without one, PythonBPF uses "GPL" and logs a warning)
@bpf
@bpfglobal
def LICENSE() -> str:

View File

@ -5,6 +5,11 @@ import logging
logger: Logger = logging.getLogger(__name__)
# The license a program gets when it declares none. The kernel is GPL, and a
# program whose license is not GPL-compatible may not call GPL-only helpers
# (bpf_trace_printk, which `print` lowers to, is one).
DEFAULT_LICENSE = "GPL"
def emit_license(module: ir.Module, license_str: str):
license_bytes = license_str.encode("utf8") + b"\x00"
@ -24,7 +29,10 @@ def emit_license(module: ir.Module, license_str: str):
def license_processing(tree, compilation_context):
"""Process the LICENSE function decorated with @bpf and @bpfglobal and return the section name"""
"""Process the LICENSE function decorated with @bpf and @bpfglobal and return the section name.
A program without one gets DEFAULT_LICENSE, with a warning.
"""
count = 0
for node in tree.body:
if isinstance(node, ast.FunctionDef) and node.name == "LICENSE":
@ -52,4 +60,10 @@ def license_processing(tree, compilation_context):
)
else:
raise SyntaxError("ERROR: Multiple LICENSE globals defined")
return None
logger.warning(
f'No LICENSE defined; defaulting to "{DEFAULT_LICENSE}". Define '
"@bpf @bpfglobal def LICENSE() -> str to choose another license."
)
emit_license(compilation_context.module, DEFAULT_LICENSE)
return "LICENSE"

View File

@ -1,14 +0,0 @@
from pythonbpf import compile, bpf, section
from ctypes import c_void_p, c_int64
# FAILS WHEN THERE IS NO LICENSE. which is wrong.
@bpf
@section("sometag1")
def sometag(ctx: c_void_p) -> c_int64:
a = 1 + 2
print(f"{a}")
return c_int64(0)
compile()

View File

@ -0,0 +1,23 @@
# A license that is not GPL-compatible may not call GPL-only helpers: `print`
# lowers to bpf_trace_printk, so the verifier rejects this program. The
# counterpart of passing_tests/license_default.py, which proves the default
# license is GPL.
from pythonbpf import compile, bpf, bpfglobal, section
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_getpid")
def sometag(ctx: c_void_p) -> c_int64:
print("hello")
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "Proprietary"
compile()

View File

@ -3,25 +3,34 @@ import uuid
from collections import namedtuple
from pathlib import Path
Output = namedtuple("Output", ["stdout", "stderr"])
def verify_object(obj_path: Path) -> tuple[bool, str]:
"""Run bpftool prog load -d to verify a BPF object file against the kernel verifier.
def verify_object(obj_path: Path) -> tuple[bool, Output]:
"""Run bpftool prog load to verify a BPF object file against the kernel verifier.
Pins the program temporarily at /sys/fs/bpf/bpf_prog_test_<uuid>, then removes it.
Returns (success, combined_output). Requires sudo / root.
Returns (success, Output(stdout, stderr)). Requires sudo / root.
No -d: it asks the kernel for the full instruction-level log (log level
1+2+4) on every load. For a program that makes the verifier walk a loop that
log outgrows libbpf's buffer, the kernel then fails the load with ENOSPC, and
libbpf doubles the buffer and verifies the whole program again, until the
load takes longer than the timeout. A rejection still comes with its log:
libbpf retries a failed load at log level 1 and prints the log as a warning.
"""
pin_path = f"/sys/fs/bpf/bpf_prog_test_{uuid.uuid4().hex[:8]}"
try:
result = subprocess.run(
["sudo", "bpftool", "prog", "load", "-d", str(obj_path), pin_path],
["sudo", "bpftool", "prog", "load", str(obj_path), pin_path],
capture_output=True,
text=True,
timeout=30,
)
Output = namedtuple("Output", ["stdout", "stderr"])
output = Output(stdout=result.stdout, stderr=result.stderr)
return result.returncode == 0, output
return result.returncode == 0, Output(
stdout=result.stdout, stderr=result.stderr
)
except subprocess.TimeoutExpired:
return False, "bpftool timed out after 30s"
return False, Output(stdout="", stderr="bpftool timed out after 30s")
finally:
subprocess.run(["sudo", "rm", "-f", pin_path], check=False, capture_output=True)

View File

@ -200,6 +200,41 @@ Globals no longer appear as a blocker at all. The next unlocks by count are help
long tail, but `bpf_get_current_task`, `bpf_ktime_get_boot_ns` and the `bpf_probe_read_user*`
family recur), array maps, and typed program arguments.
## Fourth batch: loops
With `for`/`while` lowering (#106) the audit no longer counts a plain loop as a hard
blocker; the bpf_for/bpf_repeat iterators and the `bpf_loop` helper still are (38
programs), and `do { } while (0)` macros are no longer mistaken for loops. Against
bpf-next `5714ca8` that takes the programs with no hard blocker from 29 to 39. Four of
the ten are ported, all from `prog_tests/bpf_verif_scale.c`:
| Port | Upstream | Section | Upstream BPF insns | Port BPF insns |
|---|---|---|---|---|
| `vmlinux/loop1.py` | `loop1.c` | `raw_tracepoint/kfree_skb` | 21 | 20 |
| `vmlinux/loop2.py` | `loop2.c` | `raw_tracepoint/consume_skb` | 12 | 2 |
| `vmlinux/loop4.py` | `loop4.c` | `socket` | 14 | 97 |
| `vmlinux/loop5.py` | `loop5.c` | `socket` | 18 | 13 |
The loop lowering matches clang's: with `volatile`, `barrier()` and the no-unroll pragma
taken out of the C, clang emits the same 2 and 97 instructions for `loop2` and `loop4`.
Those three are what the ports cannot say, and they are the point of the upstream tests,
which exist to make the verifier walk a loop. `loop2` folds to `return 42` and `loop4`
unrolls, so those two ports compile, load and verify but no longer exercise what their
upstream counterparts do. Each says so in its header; they are the first tests to
tighten once volatile reads have a spelling. `loop1` and `loop5` keep their loops.
The other six stay unported:
- `loop3.c` is a negative test (the verifier must give up on a 2^32-iteration loop), and
without `volatile` LLVM replaces that loop with a closed form.
- `test_skb_ctx.c` needs a subscript on a context array (`skb->cb[i]`) and writes to
context fields. Today the first fails with a bare `TypeError` in `handle_cond` and the
second with a `KeyError` in `handle_struct_field_assignment`.
- `test_verif_scale1.c`, `2` and `3` contain no loop, only a `do { } while (0)` macro;
they need `jhash` over packet bytes through casts, and `scale1` a `noinline` subprogram.
- `test_parse_tcp_hdr_opt.c` reads packet bytes through casts and passes a struct pointer
to a static function.
## 3. Incidental findings
- **Nested struct field access fails with a misleading error.** `ctx.regs.ip` reports

View File

@ -0,0 +1,56 @@
# Ported from Linux tools/testing/selftests/bpf/progs/loop1.c
#
# A verifier-scale test (prog_tests/bpf_verif_scale.c, test_verif_scale_loop1):
# two nested bounded loops, the inner one bounded by the outer counter, so the
# verifier has to prove termination of ~45000 iterations. Upstream:
#
# SEC("raw_tracepoint/kfree_skb")
# int nested_loops(volatile struct pt_regs* ctx)
# {
# int i, j, sum = 0, m;
#
# for (j = 0; j < 300; j++)
# for (i = 0; i < j; i++) {
# if (j & 1)
# m = PT_REGS_RC(ctx);
# else
# m = j;
# sum += i * m;
# }
#
# return sum;
# }
#
# PT_REGS_RC is ctx->ax on x86. The `volatile` on ctx, which forces a reload of
# ctx->ax on every iteration, has no PythonBPF spelling yet; without it LLVM may
# hoist the load out of the loops. Here it does not (the load sits in a branch),
# and the object keeps upstream's nested-loop shape: 20 instructions against
# clang's 21, with 64-bit loop counters where C's are 32-bit.
from pythonbpf import bpf, section, bpfglobal, compile
from vmlinux import struct_pt_regs
from ctypes import c_int32
@bpf
@section("raw_tracepoint/kfree_skb")
def nested_loops(ctx: struct_pt_regs) -> c_int32:
total: c_int32 = 0
m: c_int32 = 0
for j in range(300):
for i in range(j):
if j & 1:
m = ctx.ax
else:
m = j
total += i * m
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,57 @@
# Ported from Linux tools/testing/selftests/bpf/progs/loop2.c
#
# A verifier-scale test (prog_tests/bpf_verif_scale.c, test_verif_scale_loop2):
# an unbounded-looking `while (true)` that only terminates through a `break`,
# with a step that depends on the context. Upstream:
#
# SEC("raw_tracepoint/consume_skb")
# int while_true(volatile struct pt_regs* ctx)
# {
# int i = 0;
#
# while (true) {
# if (PT_REGS_RC(ctx) & 1)
# i += 3;
# else
# i += 7;
# if (i > 40)
# break;
# }
#
# return i;
# }
#
# PT_REGS_RC is ctx->ax on x86.
#
# NOTE: this port does not test what upstream tests. `volatile` has no
# PythonBPF spelling yet, so ctx->ax is loaded once and LLVM sees that both
# paths end at 42 (3 * 14 and 7 * 6): the program compiles to `return 42` and
# the verifier never sees a loop. Clang does the same to the C with `volatile`
# removed. Revisit when volatile reads land.
from pythonbpf import bpf, section, bpfglobal, compile
from vmlinux import struct_pt_regs
from ctypes import c_int32
@bpf
@section("raw_tracepoint/consume_skb")
def while_true(ctx: struct_pt_regs) -> c_int32:
i: c_int32 = 0
while True:
if ctx.ax & 1:
i += 3
else:
i += 7
if i > 40:
break
return i
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,47 @@
# Ported from Linux tools/testing/selftests/bpf/progs/loop4.c
#
# A verifier-scale test (prog_tests/bpf_verif_scale.c, test_verif_scale_loop4):
# a 20-iteration loop whose body branches on a context field, so the verifier
# sees 2^20 paths unless it prunes states. Upstream:
#
# SEC("socket")
# int combinations(volatile struct __sk_buff* skb)
# {
# int ret = 0, i;
#
# __pragma_loop_no_unroll
# for (i = 0; i < 20; i++)
# if (skb->len)
# ret |= 1 << i;
# return ret;
# }
#
# NOTE: this port does not test what upstream tests. `volatile` and the
# no-unroll pragma have no PythonBPF spelling, so skb->len is loaded once and
# LLVM fully unrolls the loop (97 instructions against upstream's 14): the
# verifier walks straight-line code instead of pruning states across a loop.
# Clang does the same to the C with `volatile` and the pragma removed. Revisit
# when volatile reads land.
from pythonbpf import bpf, section, bpfglobal, compile
from vmlinux import struct___sk_buff
from ctypes import c_int32
@bpf
@section("socket")
def combinations(skb: struct___sk_buff) -> c_int32:
ret: c_int32 = 0
for i in range(20):
if skb.len:
ret |= 1 << i
return ret
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,68 @@
# Ported from Linux tools/testing/selftests/bpf/progs/loop5.c
#
# A verifier-scale test (prog_tests/bpf_verif_scale.c, test_verif_scale_loop5):
# `while (1)` with several exits, where whether an exit is ever reached depends
# on a context field. Upstream:
#
# SEC("socket")
# int while_true(volatile struct __sk_buff* skb)
# {
# int i = 0;
#
# while (1) {
# if (skb->len)
# i += 3;
# else
# i += 7;
# if (i == 9)
# break;
# barrier();
# if (i == 10)
# break;
# barrier();
# if (i == 13)
# break;
# barrier();
# if (i == 14)
# break;
# }
# return i;
# }
#
# barrier() is an empty `asm volatile("" ::: "memory")` that stops clang from
# merging the exits; PythonBPF has no compiler barrier, and LLVM merges the four
# exits into one bitmask test. The loop survives, so the verifier still has to
# prove it terminates.
from pythonbpf import bpf, section, bpfglobal, compile
from vmlinux import struct___sk_buff
from ctypes import c_int32
@bpf
@section("socket")
def while_true(skb: struct___sk_buff) -> c_int32:
i: c_int32 = 0
while True:
if skb.len:
i += 3
else:
i += 7
if i == 9:
break
if i == 10:
break
if i == 13:
break
if i == 14:
break
return i
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,17 @@
# No LICENSE: the program gets "GPL", with a warning. `print` lowers to
# bpf_trace_printk, which is GPL-only, so the verifier only accepts this
# program if the default license reaches the kernel.
from pythonbpf import compile, bpf, section
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_getpid")
def sometag(ctx: c_void_p) -> c_int64:
a = 1 + 2
print(f"{a}")
return c_int64(0)
compile()

View File

@ -19,7 +19,7 @@
"failing_tests/return_struct.py" = {reason = "Returning a struct value from an integer function is a type error (nothing to dereference to an integer)", level = "ir"}
"failing_tests/license.py" = {reason = "Missing LICENSE global produces IR that llc rejects — should be caught earlier with a clear error message", level = "llc"}
"failing_tests/license_non_gpl.py" = {reason = "Negative fixture: a non-GPL license may not call the GPL-only bpf_trace_printk that print lowers to", level = "verifier", match = "cannot call GPL-restricted function from non-GPL compatible program"}
"failing_tests/undeclared_values.py" = {reason = "Undeclared variable used in f-string — should raise SyntaxError (correct behaviour, test documents it)", level = "ir"}

42
tests/test_license_ir.py Normal file
View File

@ -0,0 +1,42 @@
"""
The license section: a program without LICENSE gets "GPL", with a warning,
and an explicit LICENSE is emitted as written, with no warning.
"""
import logging
from pathlib import Path
from tests.framework.compiler import run_ir_generation
TESTS_DIR = Path(__file__).parent
def _license_global(text):
"""The LICENSE global as compile_to_ir emits it: NUL-terminated bytes."""
data = text.encode() + b"\x00"
elems = ", ".join(f"i8 {b}" for b in data)
return (
f'@"LICENSE" = dso_local global [{len(data)} x i8] [{elems}], section "license"'
)
def _license_ir(name, tmp_path, caplog):
ll_path = tmp_path / "output.ll"
with caplog.at_level(logging.WARNING, logger="pythonbpf.license_pass"):
run_ir_generation(TESTS_DIR / name, ll_path)
warnings = [
r.getMessage() for r in caplog.records if r.name == "pythonbpf.license_pass"
]
return ll_path.read_text(), warnings
def test_missing_license_defaults_to_gpl(tmp_path, caplog):
ir, warnings = _license_ir("passing_tests/license_default.py", tmp_path, caplog)
assert _license_global("GPL") in ir
assert any('defaulting to "GPL"' in w for w in warnings), warnings
def test_explicit_license_is_kept(tmp_path, caplog):
ir, warnings = _license_ir("failing_tests/license_non_gpl.py", tmp_path, caplog)
assert _license_global("Proprietary") in ir
assert not warnings, warnings

View File

@ -2,7 +2,7 @@
Level 3 — Kernel verifier tests.
For every passing BPF test file, compiles to a .o and runs:
sudo bpftool prog load -d <file.o> /sys/fs/bpf/bpf_prog_test_<id>
sudo bpftool prog load <file.o> /sys/fs/bpf/bpf_prog_test_<id>
These tests are opt-in: they require sudo and kernel access, and are gated
behind the `verifier` pytest mark. Run with:

View File

@ -15,7 +15,7 @@ negatives in both directions, and the envelope it encodes (the helper, map and
construct lists below) must be kept in step with the compiler by hand. Re-run
it after a feature lands to see what the feature unlocked. The lists were last
reconciled against pythonbpf/helper and pythonbpf/maps when scalar @bpfglobal
support and integer signedness merged.
support, integer signedness and loops merged.
"""
import argparse
@ -70,7 +70,10 @@ NOT_HELPERS = {
# cost a careful rewrite can absorb). Order does not matter.
PATTERNS = [
# control flow
("loop", "hard", r"\b(for|while)\s*\(|\bbpf_for\b|\bbpf_repeat\b|\bbpf_loop\s*\("),
# plain for/while lower since loops landed (#106); `do { } while (0)` is a
# macro idiom, not a loop. Iterator loops and the bpf_loop helper are not.
("open_coded_loop", "hard", r"\bbpf_for(_each)?\b|\bbpf_repeat\b|\bbpf_loop\s*\("),
("do_while", "soft", r"\}\s*while\s*\((?!\s*0\s*\))"),
("goto", "hard", r"\bgoto\s+\w+"),
("switch", "hard", r"\bswitch\s*\("),
("ternary", "soft", r"\?[^?:]*:"),