Compare commits

..

24 Commits

Author SHA1 Message Date
32c1afff36 Tests: Make the integer properties cover every type on every run
Review of the first version of the suite found four holes.

- The conversion sites returned the converted value, which shows its
  bits but not the type it was stored as. The untyped_local site passed
  over a real bug that way. Each site now reads the value back through
  an expression whose result depends on its sign and width.
- With the type drawn at random, 25 examples per site left a single type
  with about 3. A deliberately broken c_bool conversion went undetected
  under some seeds. The conversion property is now parametrized by
  destination type and the operator property by left operand type, a
  sixteenth of the profile's examples each.
- The global_init site was a strict xfail. Hypothesis shrank its
  expected failures, which took 115 of the property's 187 seconds. Its
  two bugs are now pinned in test_known_gaps.py, and the site steps
  around them.
- Gaps are now stepped around by drawing only inputs that avoid them,
  not by assume(). Filtering tripped Hypothesis's filter_too_much health
  check.

untyped-copy-keeps-narrow-type is renamed untyped-copy-keeps-source-type.
`t = a` keeps a's type for any source that is not 64-bit, c_uint32 and
c_int32 included, not only narrow ones.

Under the ci profile, each of these deliberate compiler bugs fails a
property:
- >> always logical
- % always unsigned
- / always unsigned
- equal-width mixed signs going signed
- promotion keeping an unsigned sign
- widening always by zero-extension
- c_bool conversion by truncation

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 21:55:59 +05:30
7b328fb9b7 Tests: Property-test integer arithmetic and conversions against clang
tests/property generates integer programs, prints each as PythonBPF and
as C, and runs both on the host. clang's result is the specification:
- clang compiles the C (-O0 -fwrapv) to a native object.
- PythonBPF's IR is retargeted to the host.
- Both are JIT-run in a worker process, so a miscompile that traps
  cannot end the pytest run.

cints.py models C's promotions, usual arithmetic conversions and
operators. It discards programs that would be undefined in C, and it is
checked against clang on every example, so a model bug is never blamed
on the compiler.

Three properties:
- test_int_expressions: random nested expressions over every ctypes
  integer type and c_bool, with typed and untyped temporaries. The
  worked examples of integers.md are pinned.
- test_int_operators: every binary operator on every pair of types.
- test_int_conversions: every (source type, destination type, site)
  triple. The sites are constructor, declaration, reassignment, untyped
  local, global store, return, global initialiser and each augmented
  assignment.

Deliberately breaking >>, %, /, the usual arithmetic conversions,
promotion, sign extension or c_bool conversion fails a property each
time, shrunk to a program of two or three lines.

Divergences found and not yet fixed are in known_gaps.py, each pinned as
a strict xfail in test_known_gaps.py:
- negated-literal-rank: -2147483648 is ranked int, not long long.
- untyped-local-unary-or-compare: `t = -x`, `t = not x` and `t = a < b`
  give "Undefined variable".
- shift-result-type: a shift is typed by both operands, not by its
  promoted left operand. This includes <<= and >>=.
- untyped-copy-keeps-narrow-type: `t = a` keeps a's narrow type, where
  integers.md says an undeclared local is 64 bits.
- The global_init site: a negative @bpfglobal initialiser becomes 0, and
  c_bool(2) becomes 0.

tests/README.md documents the suite and the plan for what comes next.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 21:05:37 +05:30
ed5bc46793 Tests: Add Hypothesis, with dev, ci and thorough profiles
hypothesis joins the test extra. conftest.py registers three profiles,
chosen with HYPOTHESIS_PROFILE:
- dev (the default): 100 examples.
- ci: 100 examples, derandomized, so a CI failure always reproduces.
- thorough: 3000 examples, for bug hunting.
None of them has a deadline: an example compiles a program twice.

CI runs the suite with the ci profile. The example database
(.hypothesis/) is ignored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 21:05:25 +05:30
7e69e7b23e Tests: Let host_jit read a function's result as any ctypes type
run_function took the return type from the IR and read only i32 and i64,
as signed. It now takes an optional ctypes type, so a caller can read an
unsigned or narrow result the way C would see it. Without one, it does
what it did before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 21:05:23 +05:30
b076ef4f2b Revise project status note in README
Updated note about project readiness for production use.
2026-10-16 19:20:10 +05:30
ad7a8567b1 Merge pull request #112 from pythonbpf/docs/readme-logo-center
Docs: Center the README logo
2026-10-16 19:19:18 +05:30
c308704dc5 Docs: Center the README logo
The <picture> sat outside any centered block, so GitHub drew the logo at
the left edge. Wrap it in <p align="center"> like the badges below it
(GitHub strips style attributes but keeps align). Also drop the alt on
<source>, which ignores it, and give the <img> a real description.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-16 19:07:25 +05:30
f2e6fba645 Merge pull request #111 from pythonbpf/fix/trivial-xfails
Fix stale XFAILs that can now PASS
2026-10-09 06:10:18 +05:30
37fe5d7a9a Tests: Derive the map-value pointer-depth check from a clang reference
tests/c-form/map_update_from_lookup.bpf.c mirrors the two programs the
check covers. At -O0 clang passes bpf_map_update_elem the result of
`load ptr, ptr <prev's slot>`, in both copy() and rebind().

The old expected pattern only asked for some load of prev, and `if prev`
already does one, so it matched the buggy IR too. The check now requires
the value loaded from prev's slot to be the helper's value argument. It
fails on the code before dde720f and passes on this branch.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 05:31:38 +05:30
d093516c1d Merge pull request #110 from pythonbpf/fix/default-gpl-license
Add default GPL license if not specified in the program
2026-10-09 05:19:41 +05:30
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
f5eb809f4b Tests: Move tests that pass out of failing_tests
retype, helper_cond, direct_assign and globals had no xfail entry and have
been passing at every level; their NOTE headers describe limits that have
since been lifted, so they are rewritten. xdp_pass was an xfail only because
it used the old count().lookup() spelling of a map call; in the current
syntax it compiles.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 03:13:51 +05:30
28536c2c07 Core: Refuse an expression statement whose calls would be dropped
handle_expr lowered a statement only when it was a call, and dropped any
other expression with an INFO log. So `print(a) if c else print(b)` compiled
to nothing at all, and failing_tests/conditionals/oneline.py passed. An
expression statement that contains a call is now a compile error; one
without (a docstring, a bare name) is still dropped. oneline.py becomes an
IR-level xfail.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 03:13:50 +05:30
4c57a4e834 Core: Reject a struct value as a condition with a clear error
`if dat:` on a local struct built Constant(struct_type, 0) in
convert_to_bool, and llvmlite failed later, while printing the module, with
"'int' object is not iterable". A struct has no truth value (C rejects
`if (s)`; Python would call any object true), so it is now a TypeError
that says to test a field. A pointer to a struct is unaffected.

The xfail was named struct_ptr but tests a struct value; it is renamed to
struct_value.py and becomes a negative test.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 03:13:49 +05:30
dde720f46e Core: Pass helpers the pointer a local holds, not its slot's address
A local bound to a map lookup holds a pointer, and get_or_create_ptr_from_arg
handed a helper the address of that local's stack slot instead. So
count.update(k, prev) stored the kernel address of the map value, not the
value, and after prev = prev + 1 it stored the address of the temporary.
The verifier accepts both when loading as root, so nothing failed: the
failing_tests/vmlinux/named_arg.py example has been passing all along while
storing the wrong thing. The slot is now loaded when it holds a pointer.

named_arg.py moves to passing_tests, and both it and a new
map_update_from_lookup.py are pinned by IR assertions.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 03:13:47 +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
ec5d72fdbe Bump version to 0.2.0 2026-09-26 01:05:13 +05:30
40aad02d73 loops (#106)
* 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.
2026-09-26 01:00:45 +05:30
4662fe63b5 Merge pull request #105 from pythonbpf/claude/pythonbpf-state-replication-g23gij
Add kernel selftest equivalent roadmap tests
2026-09-25 22:29:04 +05:30
78 changed files with 3109 additions and 265 deletions

View File

@ -72,6 +72,9 @@ jobs:
run: uv pip install --system -e ".[test]"
- name: Run test suite
env:
# tests/property: derandomized, so a failure always reproduces
HYPOTHESIS_PROFILE: ci
run: make test
- name: Check whether sudo is usable

1
.gitignore vendored
View File

@ -14,3 +14,4 @@ vmlinux.h
# Documentation build artifacts
docs/_build/
docs/_templates/
.hypothesis/

View File

@ -1,14 +1,15 @@
<picture>
<source
media="(prefers-color-scheme: light)"
srcset="https://github.com/user-attachments/assets/f3738131-d7cb-4b5c-8699-c7010295a159"
width="450"
alt="Light‐mode image">
<img
src="https://github.com/user-attachments/assets/b175bf39-23cb-475d-a6e1-7b5c99a1ed72"
width="450"
alt="Dark‐mode image">
</picture>
<p align="center">
<picture>
<source
media="(prefers-color-scheme: light)"
srcset="https://github.com/user-attachments/assets/f3738131-d7cb-4b5c-8699-c7010295a159"
width="450">
<img
src="https://github.com/user-attachments/assets/b175bf39-23cb-475d-a6e1-7b5c99a1ed72"
width="450"
alt="PythonBPF logo">
</picture>
</p>
<!-- Badges -->
<p align="center">
<!-- PyPI -->
@ -28,7 +29,7 @@
Python-BPF is an LLVM IR generator for eBPF programs written in Python. It uses [llvmlite](https://github.com/numba/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.
> **Note**: This project is under active development.
---

View File

@ -15,8 +15,8 @@ sys.path.insert(0, os.path.abspath(".."))
project = "PythonBPF"
copyright = "2026, Pragyansh Chaturvedi, Varun Mallya"
author = "Pragyansh Chaturvedi, Varun Mallya"
release = "0.1.9"
version = "0.1.9"
release = "0.2.0"
version = "0.2.0"
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration

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

@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "pythonbpf"
version = "0.1.9"
version = "0.2.0"
description = "Reduced Python frontend for eBPF"
authors = [
{ name = "r41k0u", email="pragyanshchaturvedi18@gmail.com" },
@ -42,6 +42,7 @@ docs = [
test = [
"pytest>=8.0",
"pytest-cov>=5.0",
"hypothesis>=6.100",
"ctypeslib2",
# Pinned rather than left to ctypeslib2's own (unpinned) dependency: pip
# installs the latest release by default, and its libclang API surface

View File

@ -8,6 +8,7 @@ from pythonbpf.vmlinux_parser.dependency_node import Field
from .expr import VmlinuxHandlerRegistry
from pythonbpf.type_deducer import ctypes_to_ir, is_ctypes, IntTy, signedness, byte_size
from pythonbpf.expr.type_inference import infer_int_type
from pythonbpf.expr.operators import usual_arithmetic_conversions
from pythonbpf.maps import BPFMapType
logger = logging.getLogger(__name__)
@ -49,57 +50,231 @@ def handle_assign_allocation(compilation_context, builder, stmt, local_sym_tab):
)
continue
var_name = target.id
# Already bound in this scope: a parameter, an earlier assignment, or a
# `global` declaration (whose slot is the GlobalVariable). No slot needed.
if var_name in local_sym_tab:
logger.debug(f"'{var_name}' already bound, no allocation needed")
continue
# Not declared `global`, yet named like one: Python creates a local
# that shadows the global for the whole function body, and leaves the
# global untouched. Do the same.
shadows_global = var_name in compilation_context.bpf_globals
if shadows_global:
logger.info(
f"'{var_name}' is assigned without a 'global' declaration, so it "
f"is a local shadowing the @bpfglobal of the same name"
)
# Determine type and allocate based on rval
if isinstance(rval, ast.Call):
_allocate_for_call(
_bind_name(
compilation_context,
stmt,
target,
local_sym_tab,
lambda var_name: _allocate_for_value(
builder, var_name, rval, local_sym_tab, compilation_context
)
elif isinstance(rval, ast.Constant):
_allocate_for_constant(builder, var_name, rval, local_sym_tab)
elif isinstance(rval, ast.BinOp):
_allocate_for_binop(
builder, var_name, rval, local_sym_tab, compilation_context
)
elif isinstance(rval, ast.Name):
# Variable-to-variable assignment (b = a)
_allocate_for_name(
builder, var_name, rval, local_sym_tab, compilation_context
)
elif isinstance(rval, ast.Attribute):
# Struct field-to-variable assignment (a = dat.fld)
_allocate_for_attribute(
builder, var_name, rval, local_sym_tab, compilation_context
)
else:
logger.warning(
f"Unsupported assignment value type for {var_name}: {type(rval).__name__}"
)
),
)
if shadows_global and var_name in local_sym_tab:
# Where the binding ends, so that a read above it is reported the
# way Python reports it. end_lineno, not lineno, so a read on a
# continuation line of a multi-line binding counts as above it too.
local_sym_tab[var_name].shadows_global_from = (
getattr(stmt, "end_lineno", None) or target.lineno
)
def handle_ann_assign_allocation(compilation_context, builder, stmt, local_sym_tab):
"""Handle memory allocation for annotated assignment (`x: c_int32 = 0`).
The annotation, not the value, types the slot: `x: c_int32 = 0` is an i32
even though the literal alone would give an i64. With no value
(`x: c_int64`) the slot is still made, and the name stays unbound until
something assigns it, as in Python.
"""
logger.info(f"Handling annotated assignment for allocation: {ast.dump(stmt)}")
if not isinstance(stmt.target, ast.Name):
raise SyntaxError(
f"annotated assignment on line {stmt.lineno} must target a plain "
f"name, got {type(stmt.target).__name__}"
)
ir_type = annotation_to_ir(stmt.annotation, stmt.lineno)
_bind_name(
compilation_context,
stmt,
stmt.target,
local_sym_tab,
lambda var_name: local_sym_tab.__setitem__(
var_name,
LocalSymbol(_allocate_with_type(builder, var_name, ir_type), ir_type),
),
)
def handle_for_allocation(compilation_context, builder, stmt, local_sym_tab):
"""Handle memory allocation for `for <name> in range(...)`.
Two slots, both in the entry block so a loop never grows the stack: the
loop variable, and a hidden induction counter the loop actually steps.
Keeping them apart is what makes rebinding the loop variable in the body
leave the trip count alone, as in Python -- and a counter the body cannot
touch is what keeps the loop visibly bounded for the verifier.
"""
start, stop, step = parse_range(stmt)
# range() yields Python ints; like any undeclared local they are 64-bit,
# signed unless the bounds make C's arithmetic unsigned. That arithmetic
# is the counter's against each bound, so it starts from a signed 64-bit
# counter, and only an unsigned 64-bit bound turns it unsigned: every
# narrower unsigned bound fits in the signed counter, as in C.
bound_types = [
infer_int_type(bound, local_sym_tab, compilation_context)
for bound in (start, stop)
if bound is not None
]
signed = True
if all(ty is not None for ty in bound_types):
common = IntTy(64, True)
for ty in bound_types:
common = usual_arithmetic_conversions(common, ty)
signed = signedness(common)
if not signed and step < 0:
raise SyntaxError(
f"range() on line {stmt.lineno} counts down over unsigned bounds; "
f"the counter would wrap instead of stopping"
)
loop_ty = IntTy(64, signed)
counter = range_counter_name(stmt)
local_sym_tab[counter] = LocalSymbol(
_allocate_with_type(builder, counter, loop_ty), loop_ty
)
_bind_name(
compilation_context,
stmt,
stmt.target,
local_sym_tab,
lambda var_name: local_sym_tab.__setitem__(
var_name,
LocalSymbol(_allocate_with_type(builder, var_name, loop_ty), loop_ty),
),
)
def range_counter_name(stmt):
"""Symbol-table name of a range loop's hidden induction counter, unique per
loop so nested loops each get their own."""
return f"__range_idx_{stmt.lineno}_{stmt.col_offset}"
def parse_range(stmt):
"""Split `for <name> in range(...)` into (start, stop, step): start is an
expression or None (meaning 0), stop an expression, step a nonzero int.
step has to be known at compile time, because its sign decides whether the
loop runs while the counter is below stop or above it.
"""
it = stmt.iter
if not (
isinstance(it, ast.Call)
and isinstance(it.func, ast.Name)
and it.func.id == "range"
):
raise NotImplementedError(
f"for loop on line {stmt.lineno}: only range(...) can be iterated "
f"so far, got {ast.unparse(it)}"
)
if not isinstance(stmt.target, ast.Name):
raise NotImplementedError(
f"for loop on line {stmt.lineno}: only a plain name can be the loop "
f"variable, got {ast.unparse(stmt.target)}"
)
if it.keywords or not 1 <= len(it.args) <= 3:
raise SyntaxError(
f"range() on line {stmt.lineno} takes 1 to 3 positional arguments"
)
if len(it.args) == 1:
return None, it.args[0], 1
start, stop = it.args[0], it.args[1]
if len(it.args) == 2:
return start, stop, 1
step_node = it.args[2]
negate = isinstance(step_node, ast.UnaryOp) and isinstance(step_node.op, ast.USub)
literal = step_node.operand if negate else step_node
if not (
isinstance(literal, ast.Constant)
and isinstance(literal.value, int)
and not isinstance(literal.value, bool)
):
raise SyntaxError(
f"range() step on line {stmt.lineno} must be an integer literal, "
f"got {ast.unparse(step_node)}"
)
step = -literal.value if negate else literal.value
if step == 0:
raise ValueError(f"range() arg 3 must not be zero (line {stmt.lineno})")
if abs(step) >= 1 << 64:
raise ValueError(
f"range() step on line {stmt.lineno} does not fit the 64-bit "
f"loop counter: {ast.unparse(step_node)}"
)
return start, stop, step
def annotation_to_ir(annotation, lineno):
"""IR type for a ctypes annotation, written `c_int32` or `ctypes.c_int32`."""
if isinstance(annotation, ast.Name):
name = annotation.id
elif isinstance(annotation, ast.Attribute):
name = annotation.attr
else:
name = None
if name is None or not is_ctypes(name):
raise SyntaxError(
f"unsupported annotation on line {lineno}: {ast.unparse(annotation)} "
f"(annotate locals with a ctypes integer type such as c_int64)"
)
return ctypes_to_ir(name)
def _bind_name(compilation_context, stmt, target, local_sym_tab, allocate):
"""What every statement that binds a bare name shares, around the
statement-specific `allocate(var_name)` that makes the slot.
A name already bound needs no new slot. A name that is also a @bpfglobal
but was not declared `global` becomes a local shadowing it, and records
where its binding ends so a read above it is reported as Python would.
"""
var_name = target.id
# Already bound in this scope: a parameter, an earlier assignment, or a
# `global` declaration (whose slot is the GlobalVariable). No slot needed.
if var_name in local_sym_tab:
logger.debug(f"'{var_name}' already bound, no allocation needed")
return
# Not declared `global`, yet named like one: Python creates a local
# that shadows the global for the whole function body, and leaves the
# global untouched. Do the same.
shadows_global = var_name in compilation_context.bpf_globals
if shadows_global:
logger.info(
f"'{var_name}' is assigned without a 'global' declaration, so it "
f"is a local shadowing the @bpfglobal of the same name"
)
allocate(var_name)
if shadows_global and var_name in local_sym_tab:
# Where the binding ends, so that a read above it is reported the
# way Python reports it. end_lineno, not lineno, so a read on a
# continuation line of a multi-line binding counts as above it too.
local_sym_tab[var_name].shadows_global_from = (
getattr(stmt, "end_lineno", None) or target.lineno
)
def _allocate_for_value(builder, var_name, rval, local_sym_tab, compilation_context):
"""Allocate a slot for `var_name = rval`, typed from the value."""
if isinstance(rval, ast.Call):
_allocate_for_call(builder, var_name, rval, local_sym_tab, compilation_context)
elif isinstance(rval, ast.Constant):
_allocate_for_constant(builder, var_name, rval, local_sym_tab)
elif isinstance(rval, ast.BinOp):
_allocate_for_binop(builder, var_name, rval, local_sym_tab, compilation_context)
elif isinstance(rval, ast.Name):
# Variable-to-variable assignment (b = a)
_allocate_for_name(builder, var_name, rval, local_sym_tab, compilation_context)
elif isinstance(rval, ast.Attribute):
# Struct field-to-variable assignment (a = dat.fld)
_allocate_for_attribute(
builder, var_name, rval, local_sym_tab, compilation_context
)
else:
logger.warning(
f"Unsupported assignment value type for {var_name}: {type(rval).__name__}"
)
def _allocate_for_call(builder, var_name, rval, local_sym_tab, compilation_context):

View File

@ -27,7 +27,7 @@ import re
logger: Logger = logging.getLogger(__name__)
VERSION = "v0.1.9"
VERSION = "v0.2.0"
def finalize_module(original_str):

View File

@ -82,7 +82,12 @@ class CompilationContext:
# Current function context (optional, if needed globally during function processing)
self.current_func = None
# Enclosing loops of the statement being lowered, innermost last, as
# (continue target, break target) blocks.
self.loop_stack: list[tuple[ir.Block, ir.Block]] = []
def reset(self):
"""Reset state between functions if necessary, though new context per compile is preferred."""
self.scratch_pool.reset()
self.current_func = None
self.loop_stack = []

View File

@ -842,5 +842,13 @@ def handle_expr(
call,
local_sym_tab,
)
elif any(isinstance(node, ast.Call) for node in ast.walk(call)):
# A docstring or a bare name has no effect and can be dropped; an
# expression with a call in it (`f() if c else g()`, `a() or b()`)
# does, and dropping it would silently lose the call.
raise NotImplementedError(
f"Unsupported expression statement on line {expr.lineno}: "
f"{type(call).__name__}; write it as an if statement or assignment"
)
else:
logger.info("Unsupported expression type")
logger.debug(f"Dropping expression statement without effect: {ast.dump(call)}")

View File

@ -113,6 +113,14 @@ def convert_to_bool(builder, val):
"""Convert a value to boolean."""
if val.type == ir.IntType(1):
return val
if not isinstance(val.type, (ir.IntType, ir.PointerType)):
# C rejects `if (s)` on a struct, and Python would call any object
# true; either way it is never what was meant.
kind = "struct" if isinstance(val.type, ir.BaseStructType) else "value"
raise TypeError(
f"a {kind} of type {val.type} has no truth value: test one of its "
"fields instead"
)
if isinstance(val.type, ir.PointerType):
zero = ir.Constant(val.type, None)
else:

View File

@ -25,6 +25,10 @@ from pythonbpf.assign_pass import (
)
from pythonbpf.allocation_pass import (
handle_assign_allocation,
handle_ann_assign_allocation,
handle_for_allocation,
parse_range,
range_counter_name,
allocate_temp_pool,
create_targets_and_rvals,
LocalSymbol,
@ -81,10 +85,11 @@ def count_temps_in_call(call_node, local_sym_tab):
return count
def handle_if_allocation(
def handle_block_allocation(
compilation_context, builder, stmt, func, ret_type, local_sym_tab
):
"""Recursively handle allocations in if/else branches."""
"""Recursively handle allocations in the body and else-branch of an
if, for or while statement."""
if stmt.body:
allocate_mem(
compilation_context,
@ -116,15 +121,23 @@ def allocate_mem(compilation_context, builder, body, func, ret_type, local_sym_t
def update_max_temps_for_stmt(stmt):
nonlocal max_temps_needed
if isinstance(stmt, ast.If):
if isinstance(stmt, (ast.If, ast.For, ast.While)):
# A loop header is evaluated like a statement of its own: range()
# bounds once before the loop, a while test on every iteration.
header = {ast.For: "iter", ast.While: "test"}.get(type(stmt))
if header is not None:
count_temps_in_tree(getattr(stmt, header))
for s in stmt.body:
update_max_temps_for_stmt(s)
for s in stmt.orelse:
update_max_temps_for_stmt(s)
return
count_temps_in_tree(stmt)
def count_temps_in_tree(tree):
stmt_temps = {}
for node in ast.walk(stmt):
for node in ast.walk(tree):
if isinstance(node, ast.Call):
call_temps = count_temps_in_call(node, local_sym_tab)
for typ, cnt in call_temps.items():
@ -135,8 +148,10 @@ def allocate_mem(compilation_context, builder, body, func, ret_type, local_sym_t
update_max_temps_for_stmt(stmt)
# Handle allocations
if isinstance(stmt, ast.If):
handle_if_allocation(
if isinstance(stmt, ast.For):
handle_for_allocation(compilation_context, builder, stmt, local_sym_tab)
if isinstance(stmt, (ast.If, ast.For, ast.While)):
handle_block_allocation(
compilation_context,
builder,
stmt,
@ -146,6 +161,10 @@ def allocate_mem(compilation_context, builder, body, func, ret_type, local_sym_t
)
elif isinstance(stmt, ast.Assign):
handle_assign_allocation(compilation_context, builder, stmt, local_sym_tab)
elif isinstance(stmt, ast.AnnAssign):
handle_ann_assign_allocation(
compilation_context, builder, stmt, local_sym_tab
)
allocate_temp_pool(builder, max_temps_needed, local_sym_tab)
@ -195,6 +214,24 @@ def handle_assign(func, compilation_context, builder, stmt, local_sym_tab):
logger.error(f"Unsupported assignment target: {ast.dump(target)}")
def handle_ann_assign(func, compilation_context, builder, stmt, local_sym_tab):
"""Handle `x: T = v`. The allocation pass already made x's slot with the
annotated type, so what is left is an ordinary store of v into it, through
the same helper plain assignment uses (which converts v to the slot's type).
A bare `x: T` binds nothing and emits nothing."""
if stmt.value is None:
return
if not handle_variable_assignment(
func,
compilation_context,
builder,
stmt.target.id,
stmt.value,
local_sym_tab,
):
logger.error(f"Failed to handle annotated assignment to {stmt.target.id}")
def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab):
"""Handle `x += v` and friends by direct lowering: resolve the target's
slot, load it, apply the operator, store back.
@ -295,7 +332,7 @@ def handle_cond(func, compilation_context, builder, cond, local_sym_tab):
return convert_to_bool(builder, val)
def handle_if(func, compilation_context, builder, stmt, local_sym_tab):
def handle_if(func, compilation_context, builder, stmt, local_sym_tab, ret_type):
"""Handle if statements in the function body."""
logger.info("Handling if statement")
# start = builder.block.parent
@ -313,28 +350,197 @@ def handle_if(func, compilation_context, builder, stmt, local_sym_tab):
builder.cbranch(cond, then_block, merge_block)
builder.position_at_end(then_block)
for s in stmt.body:
process_stmt(func, compilation_context, builder, s, local_sym_tab, False)
process_block(
func, compilation_context, builder, stmt.body, local_sym_tab, ret_type
)
if not builder.block.is_terminated:
builder.branch(merge_block)
if else_block:
builder.position_at_end(else_block)
for s in stmt.orelse:
process_stmt(
func,
compilation_context,
builder,
s,
local_sym_tab,
False,
)
process_block(
func, compilation_context, builder, stmt.orelse, local_sym_tab, ret_type
)
if not builder.block.is_terminated:
builder.branch(merge_block)
builder.position_at_end(merge_block)
def _lower_loop(
func,
compilation_context,
builder,
stmt,
local_sym_tab,
ret_type,
body_block,
continue_block,
end_block,
else_block,
):
"""What for and while share once their header is emitted: the body, with
`continue` and `break` bound to this loop, falling through to
continue_block; then the else-branch, which runs only when the loop ends
without a break, so it sits between the exit test and end_block."""
builder.position_at_end(body_block)
compilation_context.loop_stack.append((continue_block, end_block))
try:
process_block(
func, compilation_context, builder, stmt.body, local_sym_tab, ret_type
)
finally:
compilation_context.loop_stack.pop()
if not builder.block.is_terminated:
builder.branch(continue_block)
if else_block is not None:
# Outside this loop's scope: a break here leaves the enclosing loop.
builder.position_at_end(else_block)
process_block(
func, compilation_context, builder, stmt.orelse, local_sym_tab, ret_type
)
if not builder.block.is_terminated:
builder.branch(end_block)
builder.position_at_end(end_block)
def handle_while(func, compilation_context, builder, stmt, local_sym_tab, ret_type):
"""Handle `while test: body [else: orelse]`. The test is re-evaluated at
the top of every iteration, and is where `continue` goes."""
cond_block = func.append_basic_block(name="while.cond")
body_block = func.append_basic_block(name="while.body")
else_block = func.append_basic_block(name="while.else") if stmt.orelse else None
end_block = func.append_basic_block(name="while.end")
builder.branch(cond_block)
builder.position_at_end(cond_block)
cond = handle_cond(func, compilation_context, builder, stmt.test, local_sym_tab)
builder.cbranch(cond, body_block, else_block or end_block)
_lower_loop(
func,
compilation_context,
builder,
stmt,
local_sym_tab,
ret_type,
body_block,
cond_block,
end_block,
else_block,
)
def handle_for(func, compilation_context, builder, stmt, local_sym_tab, ret_type):
"""Handle `for name in range(...): body [else: orelse]`.
The allocation pass made a hidden induction counter (typed from the
bounds) next to the loop variable. The bounds are evaluated once, before
the loop, as Python does; each iteration copies the counter into the loop
variable, and `continue` goes to the step, not straight back to the test.
"""
start, stop, step = parse_range(stmt)
counter = local_sym_tab[range_counter_name(stmt)]
loop_ty = counter.ir_type
def bound(expr):
val, ty = get_typed_operand(
func, compilation_context, expr, builder, local_sym_tab
)
if val is None or not isinstance(ty, ir.IntType):
raise SyntaxError(
f"range() bound on line {stmt.lineno} must be an integer: "
f"{ast.unparse(expr)}"
)
return convert(builder, val, ty, loop_ty)
start_val = ir.Constant(loop_ty, 0) if start is None else bound(start)
stop_val = bound(stop)
builder.store(start_val, counter.var)
target = local_sym_tab[stmt.target.id]
if target.var is None:
raise SyntaxError(
f"cannot use '{stmt.target.id}' as a loop variable: it is the "
f"context parameter"
)
cond_block = func.append_basic_block(name="for.cond")
body_block = func.append_basic_block(name="for.body")
inc_block = func.append_basic_block(name="for.inc")
else_block = func.append_basic_block(name="for.else") if stmt.orelse else None
end_block = func.append_basic_block(name="for.end")
builder.branch(cond_block)
builder.position_at_end(cond_block)
idx = builder.load(counter.var)
# Counting up runs while below stop, counting down while above it.
predicate = "<" if step > 0 else ">"
compare = builder.icmp_signed if signedness(loop_ty) else builder.icmp_unsigned
builder.cbranch(
compare(predicate, idx, stop_val), body_block, else_block or end_block
)
# The loop variable is bound to the counter's value, per iteration.
builder.position_at_end(body_block)
builder.store(
convert(builder, builder.load(counter.var), loop_ty, target.ir_type),
target.var,
)
builder.position_at_end(inc_block)
idx = builder.load(counter.var)
if abs(step) > 1:
# The body only runs with the counter strictly inside the range, so
# the distance left to stop is exact as an unsigned number. A step no
# shorter than that distance ends the loop here, before the add can
# wrap the counter back inside the range (a step of 1 cannot
# overshoot stop, so it keeps the plain loop).
left = builder.sub(stop_val, idx) if step > 0 else builder.sub(idx, stop_val)
step_in_range = func.append_basic_block(name="for.step")
builder.cbranch(
builder.icmp_unsigned(">", left, ir.Constant(loop_ty, _wrap64(abs(step)))),
step_in_range,
else_block or end_block,
)
builder.position_at_end(step_in_range)
next_idx = builder.add(idx, ir.Constant(loop_ty, _wrap64(step)))
builder.store(next_idx, counter.var)
builder.branch(cond_block)
_lower_loop(
func,
compilation_context,
builder,
stmt,
local_sym_tab,
ret_type,
body_block,
inc_block,
end_block,
else_block,
)
def _wrap64(value):
"""`value` modulo 2**64, as the signed Python int LLVM parses for an i64:
a step of 2**63 or more (or its negation) is written by its bits."""
value %= 1 << 64
return value - (1 << 64) if value >= 1 << 63 else value
def handle_loop_jump(compilation_context, builder, stmt):
"""Handle `break` and `continue`: branch to the innermost loop's exit or
next-iteration block."""
keyword = "break" if isinstance(stmt, ast.Break) else "continue"
if not compilation_context.loop_stack:
raise SyntaxError(f"'{keyword}' outside loop (line {stmt.lineno})")
continue_block, break_block = compilation_context.loop_stack[-1]
builder.branch(break_block if keyword == "break" else continue_block)
def handle_return(
func, builder, stmt, local_sym_tab, ret_type, compilation_context=None
):
@ -383,12 +589,22 @@ def process_stmt(
)
elif isinstance(stmt, ast.Assign):
handle_assign(func, compilation_context, builder, stmt, local_sym_tab)
elif isinstance(stmt, ast.AnnAssign):
handle_ann_assign(func, compilation_context, builder, stmt, local_sym_tab)
elif isinstance(stmt, ast.AugAssign):
handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab)
elif isinstance(stmt, ast.Global):
logger.debug(f"global declaration of {', '.join(stmt.names)} already bound")
elif isinstance(stmt, ast.If):
handle_if(func, compilation_context, builder, stmt, local_sym_tab)
handle_if(func, compilation_context, builder, stmt, local_sym_tab, ret_type)
elif isinstance(stmt, ast.While):
handle_while(func, compilation_context, builder, stmt, local_sym_tab, ret_type)
elif isinstance(stmt, ast.For):
handle_for(func, compilation_context, builder, stmt, local_sym_tab, ret_type)
elif isinstance(stmt, (ast.Break, ast.Continue)):
handle_loop_jump(compilation_context, builder, stmt)
elif isinstance(stmt, ast.Pass):
pass
elif isinstance(stmt, ast.Return):
did_return = handle_return(
func, builder, stmt, local_sym_tab, ret_type, compilation_context
@ -403,6 +619,19 @@ def process_stmt(
return did_return
def process_block(func, compilation_context, builder, stmts, local_sym_tab, ret_type):
"""Process a nested statement list (an if-branch or loop body). Stops at
the first statement that ends the block -- break, continue or return --
because whatever follows it in the same list can never run, and would
otherwise be emitted after a terminator."""
for s in stmts:
if builder.block.is_terminated:
break
process_stmt(
func, compilation_context, builder, s, local_sym_tab, False, ret_type
)
# ============================================================================
# SECTION 3: Function Body Processing
# ============================================================================
@ -515,7 +744,11 @@ def process_func_body(
)
if not did_return:
builder.ret(ir.Constant(ir.IntType(64), 0))
# Falling off the end returns 0, in the function's own return type:
# after `while True` this block is unreachable, but it still has to
# type-check.
default_ty = ret_type if isinstance(ret_type, ir.IntType) else ir.IntType(64)
builder.ret(ir.Constant(default_ty, 0))
def process_bpf_chunk(func_node, compilation_context, return_type):

View File

@ -67,6 +67,11 @@ def get_or_create_ptr_from_arg(
else:
# Stack space is already allocated
ptr = get_var_ptr_from_name(arg.id, local_sym_tab)
if symbol is not None and isinstance(symbol.ir_type, ir.PointerType):
# The slot holds a pointer (a map lookup result, or a local
# rebound to point at a temporary): the helper wants that
# pointer, not the address of the slot it is kept in.
ptr = builder.load(ptr)
elif isinstance(arg, ast.Constant) and isinstance(arg.value, int):
int_width = 64 # Default to i64
if expected_type and isinstance(expected_type, ir.IntType):

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

@ -133,6 +133,72 @@ Anything importing from `vmlinux` belongs in `vmlinux/`, which is registered in
`VMLINUX_TEST_DIRS_PASSING` so it is skipped rather than failed where no
`vmlinux.py` has been generated.
## Property-based tests (`tests/property/`)
The integer rules in `docs/user-guide/integers.md` are tested with
[Hypothesis](https://hypothesis.readthedocs.io): instead of hand-picked cases,
programs are generated, and each one is compiled two ways and run.
* **The oracle is clang.** Every generated program is printed twice, as
PythonBPF and as the equivalent C. clang compiles the C (`-O0 -fwrapv`) to a
native object; PythonBPF's IR is retargeted to the host. Both are JIT-run
in a worker process (a miscompile can trap or abort inside LLVM, which must
not take pytest down with it) and must return the same value.
* **A model keeps undefined behaviour out.** `cints.py` implements C's
promotions, usual arithmetic conversions and operators. Programs where C
would be undefined (division by zero, `MIN / -1`, shift counts out of
range) are discarded before anything runs. The model is also checked
against clang on every example, so a disagreement is reported as a model
bug, never blamed on PythonBPF.
| File | Property |
|---|---|
| `test_int_expressions.py` | Random straight-line programs over every ctypes integer type and `c_bool`: `+ - * / // % << >> & \| ^`, comparisons as values, unary `-`, `not`, constructor casts, typed and untyped temporaries, nested. The worked examples of `integers.md` are pinned with `@example`. |
| `test_int_operators.py` | Every binary operator, parametrized by the left operand's type, with the right type and both values drawn (edge values first). Random trees rarely reach a negative dividend under a signed `%` and return it undisturbed; this property always does. |
| `test_int_conversions.py` | Every conversion site, parametrized by the destination type: constructor call, declaration, reassignment, untyped local, global store, `return`, global initialiser, and each augmented assignment. The converted value is read back through an expression whose result depends on its sign and width, not just returned, so a value stored with the right bits but the wrong type is caught too. |
| `test_known_gaps.py` | Each known divergence's smallest program, as a strict xfail. |
### Known gaps
`known_gaps.py` lists the divergences from C the suite has found and not yet
had fixed. Each has a predicate, so the properties step around it and keep
finding *new* bugs, and a pinned program that `test_known_gaps.py` runs as a
strict xfail. A fix makes that test XPASS, failing the run until the gap is
deleted, at which point the properties cover that ground again. The
operator and conversion properties step around a gap by drawing only what
avoids it (not by filtering, which Hypothesis rightly complains about), with
a comment naming the gap.
### Running
```bash
pytest tests/property # dev profile: 100 examples
HYPOTHESIS_PROFILE=thorough pytest tests/property # 3000 examples, for bug hunting
```
CI uses the `ci` profile (100 examples, derandomized, so a failure always
reproduces): about two and a half minutes on a 16-core machine. The
operator and conversion properties are parametrized by type, so every type
is tested on every run, and run a sixteenth of the profile's count per
parameter. Profiles are registered in `conftest.py`. A failure prints both programs and the model's value;
Hypothesis shrinks it to the smallest program that still fails.
### Plan
1. **Integers and conversions** (done): the three properties above. A
mutation check (deliberately breaking `>>`, `%`, `/`, the usual arithmetic
conversions, integer promotion, sign extension and `c_bool` conversion in
the compiler) is caught every time, each shrunk to a program of two or
three lines.
2. **Fix the known gaps**, each on its own branch; its strict xfail flips to
XPASS and the gap is deleted.
3. **Widen the sites**: struct field stores and vmlinux field reads; map keys
and values, which needs helper calls stubbed with host functions in the
JIT; `range()` loops with random bounds, steps and types against CPython.
4. **Robustness**: every generated program in the supported subset must
also pass `llc` for BPF, and a program outside the subset must be rejected
with a deliberate error, never an internal `KeyError` or `TypeError`.
## Directory structure
```
@ -147,7 +213,13 @@ tests/
│ ├── bpf_test_case.py ← BpfTestCase dataclass
│ ├── collector.py ← discovers test files, reads test_config.toml
│ ├── compiler.py ← wrappers around compile_to_ir() + _run_llc()
│ ├── host_jit.py ← run a helper-free program's IR on the host
│ └── verifier.py ← bpftool subprocess wrapper
├── property/ ← Hypothesis property tests (integers, conversions)
│ ├── cints.py ← reference model of C's integer rules
│ ├── programs.py ← generated programs, printed as PythonBPF and C
│ ├── harness.py ← compile both, JIT-run in a worker, compare
│ └── known_gaps.py ← divergences found and not yet fixed
├── passing_tests/ ← programs that should compile and verify cleanly
├── failing_tests/ ← programs with known issues (declared in test_config.toml)
└── kernel_selftest_equivalent/ ← ports of kernel selftests + feature roadmap tests

97
tests/c-form/loops.bpf.c Normal file
View File

@ -0,0 +1,97 @@
/* Reference for loops. One program per shape the Python tests use, written
* the way PythonBPF lowers them: a `for i in range(...)` keeps a hidden
* induction counter separate from `i`, so rebinding `i` in the body cannot
* change the trip count. The constant-bound cases fold to a `ret` at -O2;
* `dyn_helper` reads its bound from a .data global and calls a helper per
* iteration, so a real loop (and the verifier's bounded-loop check) survives.
* (A helper-free sum over a runtime bound folds to a closed form that needs
* the __multi3 libcall, which BPF lacks -- so it is not a useful reference.) */
#define SEC(name) __attribute__((section(name), used))
typedef unsigned int __u32;
typedef unsigned long long __u64;
typedef long long __s64;
char LICENSE[] SEC("license") = "GPL";
__s64 n = 10;
/* for i in range(10): total = total + 1 */
SEC("tracepoint/syscalls/sys_enter_execve")
__s64 range_sum(void *ctx)
{
__s64 total = 0;
for (__s64 idx = 0; idx < 10; idx += 1) {
__s64 i = idx;
total = total + 1;
}
return total;
}
/* for i in range(0, 10, 2): total = total + i */
SEC("tracepoint/syscalls/sys_enter_execve")
__s64 range_step(void *ctx)
{
__s64 total = 0;
for (__s64 idx = 0; idx < 10; idx += 2) {
__s64 i = idx;
total = total + i;
}
return total;
}
/* while i < 10: i = i + 1 */
SEC("tracepoint/syscalls/sys_enter_execve")
__s64 while_basic(void *ctx)
{
__s64 i = 0;
while (i < 10)
i = i + 1;
return i;
}
/* while True: total += 1; if total == 10: break */
SEC("tracepoint/syscalls/sys_enter_execve")
__s64 while_true_break(void *ctx)
{
__s64 total = 0;
while (1) {
total = total + 1;
if (total == 10)
break;
}
return total;
}
/* for i in range(10): if i % 2 == 0: continue; total = total + i */
SEC("tracepoint/syscalls/sys_enter_execve")
__s64 for_continue(void *ctx)
{
__s64 total = 0;
for (__s64 idx = 0; idx < 10; idx += 1) {
__s64 i = idx;
if (i % 2 == 0)
continue;
total = total + i;
}
return total;
}
static __u32 (*bpf_get_prandom_u32)(void) = (void *)7;
/* for i in range(stop): total = total + random() -- a helper call per
* iteration keeps the loop from folding, so the verifier sees a real loop.
* The clamp is what makes it bounded: n is writable from userspace, so
* unclamped the verifier walks iterations until E2BIG. */
SEC("tracepoint/syscalls/sys_enter_execve")
__s64 dyn_helper(void *ctx)
{
__s64 total = 0;
__s64 stop = n;
if (stop > 64)
stop = 64;
for (__s64 idx = 0; idx < stop; idx += 1) {
__s64 i = idx;
total = total + bpf_get_prandom_u32();
}
return total;
}

View File

@ -0,0 +1,60 @@
/* Reference for passing a map lookup result to a helper. `prev` is a local
* holding the pointer bpf_map_lookup_elem returned; bpf_map_update_elem gets
* that pointer (the map value), loaded from prev's slot. It never gets &prev,
* the slot's own address, which would make the map store a stack address.
* The clang -O0 IR for this file is the specification for the pointer depth
* that tests/test_signedness_ir.py checks:
* copy() mirrors passing_tests/helpers/map_update_from_lookup.py
* rebind() mirrors passing_tests/vmlinux/named_arg.py, where `prev = prev + 1`
* rebinds prev to a stack temporary holding the sum; the helper
* still gets the pointer loaded from prev's slot. */
#define SEC(name) __attribute__((section(name), used))
#define __uint(name, val) int (*name)[val]
#define __type(name, val) typeof(val) *name
typedef long long __s64;
#define BPF_MAP_TYPE_HASH 1
#define BPF_ANY 0
#define XDP_PASS 2
static void *(*bpf_map_lookup_elem)(void *map, const void *key) = (void *)1;
static long (*bpf_map_update_elem)(void *map, const void *key,
const void *value, __s64 flags) = (void *)2;
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 2);
__type(key, __s64);
__type(value, __s64);
} count SEC(".maps");
SEC("tracepoint/syscalls/sys_enter_getpid")
__s64 copy(void *ctx)
{
__s64 key = 0;
__s64 *prev = bpf_map_lookup_elem(&count, &key);
if (prev) {
key = 1;
bpf_map_update_elem(&count, &key, prev, BPF_ANY);
}
return 0;
}
SEC("xdp")
__s64 rebind(void *ctx)
{
__s64 key = 0;
__s64 tmp;
__s64 *prev = bpf_map_lookup_elem(&count, &key);
if (prev) {
tmp = *prev + 1;
prev = &tmp;
bpf_map_update_elem(&count, &key, prev, BPF_ANY);
return XDP_PASS;
}
tmp = 1;
bpf_map_update_elem(&count, &key, &tmp, BPF_ANY);
return XDP_PASS;
}
char LICENSE[] SEC("license") = "GPL";

View File

@ -116,3 +116,22 @@ def pytest_collection_modifyitems(items):
def set_log_level(caplog):
with caplog.at_level(logging.ERROR, logger="pythonbpf"):
yield
# ── Hypothesis profiles (tests/property) ────────────────────────────────────
# dev (default) for local runs, ci for GitHub Actions (derandomized, so a PR
# never fails on an example nobody can reproduce), thorough for bug hunting:
# HYPOTHESIS_PROFILE=thorough pytest tests/property
try:
import os
from hypothesis import HealthCheck, settings
_common = dict(deadline=None, suppress_health_check=[HealthCheck.too_slow])
settings.register_profile("dev", max_examples=100, **_common)
settings.register_profile("ci", max_examples=100, derandomize=True, **_common)
settings.register_profile("thorough", max_examples=3000, **_common)
settings.load_profile(os.environ.get("HYPOTHESIS_PROFILE", "dev"))
except ImportError:
pass

View File

@ -1,10 +1,10 @@
from pythonbpf import bpf, struct, section, bpfglobal, compile
from ctypes import c_void_p, c_int64, c_uint64
# NOTE: Decided against fixing this
# as one workaround is to just check any field of the struct
# in the if statement. Ugly but works.
# Might fix in future.
# Negative test: `dat` is a struct value, and a struct has no truth value
# (C rejects `if (s)`; Python would call any object true). It is a compile
# error that says to test one of the struct's fields instead. A *pointer* to
# a struct, such as a map lookup result, is a valid condition (non-null).
@bpf

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

@ -0,0 +1,20 @@
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
total: c_int64 = 0
if total == 0:
break # noqa: F701 -- the point of the test
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,23 @@
# A step of 2**64 is a valid Python range() step (it yields just 0), but it
# does not fit the 64-bit counter: it truncates to 0 and the loop never ends.
# It should be a compile error.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
total: c_int64 = 0
for i in range(0, 10, 18446744073709551616):
total = total + 1
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,21 @@
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
total: c_int64 = 0
step: c_int64 = 2
for i in range(0, 10, step):
total = total + i
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -1,45 +0,0 @@
from pythonbpf import bpf, map, section, bpfglobal, compile
from vmlinux import XDP_PASS
from pythonbpf.maps import HashMap
from ctypes import c_void_p, c_int64
# NOTE: I have decided to not fix this example for now.
# The issue is in line 31, where we are passing an expression.
# The update helper expects a pointer type. But the problem is
# that we must allocate the space for said pointer in the first
# basic block. As that usage is in a different basic block, we
# are unable to cast the expression to a pointer type. (as we never
# allocated space for it).
# Shall we change our space allocation logic? That allows users to
# spam the same helper with the same args, and still run out of
# stack space. So we consider this usage invalid for now.
# Might fix it later.
@bpf
@map
def count() -> HashMap:
return HashMap(key=c_int64, value=c_int64, max_entries=1)
@bpf
@section("xdp")
def hello_world(ctx: c_void_p) -> c_int64:
prev = count.lookup(0)
if prev:
count.update(0, prev + 1)
return XDP_PASS
else:
count.update(0, 1)
return XDP_PASS
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -1,54 +0,0 @@
from pythonbpf import bpf, map, section, bpfglobal, compile_to_ir
from pythonbpf.maps import HashMap
from vmlinux import XDP_PASS
from vmlinux import TASK_COMM_LEN # noqa: F401
from vmlinux import struct_qspinlock # noqa: F401
# from vmlinux import struct_trace_event_raw_sys_enter # noqa: F401
# from vmlinux import struct_posix_cputimers # noqa: F401
from vmlinux import struct_xdp_md
# from vmlinux import struct_trace_event_raw_sys_enter # noqa: F401
# from vmlinux import struct_ring_buffer_per_cpu # noqa: F401
# from vmlinux import struct_request # noqa: F401
from ctypes import c_int64
# Instructions to how to run this program
# 1. Install PythonBPF: pip install pythonbpf
# 2. Run the program: python examples/xdp_pass.py
# 3. Run the program with sudo: sudo tools/check.sh run examples/xdp_pass.o
# 4. Attach object file to any network device with something like ./check.sh xdp examples/xdp_pass.o tailscale0
# 5. send traffic through the device and observe effects
@bpf
@map
def count() -> HashMap:
return HashMap(key=c_int64, value=c_int64, max_entries=1)
@bpf
@section("xdp")
def hello_world(ctx: struct_xdp_md) -> c_int64:
key = 0
one = 1
prev = count().lookup(key)
if prev:
prevval = prev + 1
print(f"count: {prevval}")
count().update(key, prevval)
return XDP_PASS
else:
count().update(key, one)
return XDP_PASS
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile_to_ir("xdp_pass.py", "xdp_pass.ll")

View File

@ -0,0 +1,59 @@
"""Run a BPF function's IR on the host, to check what it computes.
Only for helper-free programs: the IR is retargeted to the host and JIT
compiled, and the function is called with a NULL ctx. A helper call is an
inttoptr to a BPF helper id, which on the host would jump to a bogus address.
Run as a script (`python -m tests.framework.host_jit file.ll func`), so the
caller can put a timeout on a program that never terminates.
"""
import ctypes
import re
import subprocess
import sys
from pathlib import Path
import llvmlite.binding as llvm
def run_function(ll_text: str, func_name: str, restype=None) -> int:
"""Call func_name(NULL) and return its result. restype is the ctypes type
to read the result as; by default the IR's i32 or i64, read as signed."""
ll_text = re.sub(r'^target (triple|datalayout) = ".*"$', "", ll_text, flags=re.M)
llvm.initialize_native_target()
llvm.initialize_native_asmprinter()
mod = llvm.parse_assembly(ll_text)
mod.verify()
tm = llvm.Target.from_default_triple().create_target_machine()
engine = llvm.create_mcjit_compiler(mod, tm)
engine.finalize_object()
if restype is None:
ret = re.search(
rf'define [^\n]*?\bi(\d+) @"?{re.escape(func_name)}"?\(', ll_text
)
restype = {64: ctypes.c_int64, 32: ctypes.c_int32}[int(ret.group(1))]
func = ctypes.CFUNCTYPE(restype, ctypes.c_void_p)(
engine.get_function_address(func_name)
)
return int(func(None))
def run_in_subprocess(ll_path, func_name: str, timeout: float) -> int:
"""Return value of func_name(NULL). Raises subprocess.TimeoutExpired if it
does not return within timeout, CalledProcessError if it fails to run."""
out = subprocess.run(
[sys.executable, "-m", "tests.framework.host_jit", str(ll_path), func_name],
cwd=Path(__file__).parents[2],
capture_output=True,
text=True,
timeout=timeout,
check=True,
)
return int(out.stdout.strip())
if __name__ == "__main__":
with open(sys.argv[1]) as f:
print(run_function(f.read(), sys.argv[2]))

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

@ -3,13 +3,9 @@ from ctypes import c_void_p, c_int64, c_uint64
from pythonbpf.maps import HashMap
# NOTE: This example tries to reinterpret the variable `x` to a different type.
# We do not allow this for now, as stack allocations are typed and have to be
# done in the first basic block. Allowing re-interpretation would require
# re-allocation of stack space (possibly in a new basic block), which is not
# supported in eBPF yet.
# We can allow bitcasts in cases where the width of the types is the same in
# the future. But for now, we do not allow any re-interpretation of variables.
# `x` is first bound to a map lookup (a pointer) and then rebound to an integer,
# as Python allows; the comparison sees the integer. This was once refused
# because stack slots are typed, and now works.
@bpf

View File

@ -2,10 +2,8 @@ from pythonbpf import bpf, map, section, bpfglobal, compile
from ctypes import c_void_p, c_int64, c_uint64
from pythonbpf.maps import HashMap
# NOTE: Decided against fixing this
# as a workaround is assigning the result of lookup to a variable
# and then using that variable in the if statement.
# Might fix in future.
# A map lookup used directly in a comparison: the value is null-checked and
# dereferenced, and a missing key takes the else branch.
@bpf

View File

@ -0,0 +1,31 @@
# A map lookup result passed straight to map.update(): the helper gets the
# pointer the local holds (the map value), as bpf_map_update_elem(&m, &k, prev, 0)
# would in C, not the address of the local's slot.
from pythonbpf import bpf, map, section, bpfglobal, compile
from pythonbpf.maps import HashMap
from ctypes import c_void_p, c_int64
@bpf
@map
def count() -> HashMap:
return HashMap(key=c_int64, value=c_int64, max_entries=2)
@bpf
@section("tracepoint/syscalls/sys_enter_getpid")
def copy(ctx: c_void_p) -> c_int64:
prev = count.lookup(0)
if prev:
count.update(1, prev)
return c_int64(0)
@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

@ -0,0 +1,32 @@
# A loop's else-branch runs when the loop ends without a break: the for loop
# never breaks, so its else adds 100; the while loop breaks, so its else is
# skipped. Returns 3 + 100 + 1 = 104.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
total: c_int64 = 0
for i in range(3):
if i == 7:
break
total = total + 1
else:
total = total + 100
while total < 1000:
total = total + 1
break
else:
total = total + 1000
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,29 @@
# Where a loop variable is visible outside its loop it stays one local, as in
# Python: the outer body reads the `i` the inner loop left behind, and the
# return reads the last loop's final `i`. Each outer iteration adds 0 + 1 from
# the inner loop and 1 after it, the last loop adds 50, and the return adds 4:
# 6 + 50 + 4 = 60.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
total: c_int64 = 0
for i in range(3):
for i in range(2):
total = total + i
total = total + i
for i in range(5):
total = total + 10
return total + i
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,25 @@
# `pass` is the natural body of a loop run only for its side effects, or of an
# else-branch kept for symmetry. Returns 3: the loop variable keeps its last
# value after the loop, as in Python.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
i: c_int64 = 0
for i in range(4):
pass
else:
pass
return i
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,37 @@
# The bound is a @bpfglobal and the body calls a helper, so opt cannot fold
# the loop away: this is the case that puts a real bounded loop in front of
# the verifier. Reference: dyn_helper in tests/c-form/loops.bpf.c.
#
# The clamp is required, in C as here: userspace can write any value to a
# .data global, so without it the verifier assumes a bound up to 2**63 and
# walks iterations until it hits its 1M-instruction limit (E2BIG).
from pythonbpf import bpf, section, bpfglobal, compile
from pythonbpf.helper import random
from ctypes import c_void_p, c_int64
@bpf
@bpfglobal
def n() -> c_int64:
return c_int64(10)
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
total: c_int64 = 0
stop = n
if stop > 64:
stop = 64
for i in range(stop):
total = total + random()
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,21 @@
# Counting down: 10 + 7 + 4 + 1 = 22.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
total: c_int64 = 0
for i in range(10, 0, -3):
total = total + i
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,31 @@
# range() stops once the next value would pass stop; it never wraps. Here the
# first step overshoots INT64_MAX, so the counter must not wrap to a negative
# value that is still below stop; the second loop does the same below
# INT64_MIN. Leaving that way is a normal exit, so each else-branch runs.
# Returns 1 + 10 + 1 + 10 = 22.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
total: c_int64 = 0
for i in range(9223372036854775806, 9223372036854775807, 2):
total = total + 1
else:
total = total + 10
for j in range(-9223372036854775807, -9223372036854775808, -3):
total = total + 1
else:
total = total + 10
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,23 @@
# The unsigned version of range_step_overflow_signed: the step goes past
# UINT64_MAX, and the counter must not wrap to 0, which is below stop. Returns 1.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64, c_uint64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
stop: c_uint64 = 18446744073709551615
total: c_int64 = 0
for i in range(18446744073709551614, stop, 2):
total = total + 1
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,25 @@
# The counter is 64-bit, and a 64-bit signed value holds every u32, so by
# C's own rules a u32 stop does not make the loop unsigned: in
# `for (__s64 idx = -1; idx < n; idx++)` n widens to __s64. Returns 4, as
# range(-1, 3) does in Python.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64, c_uint32
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
n: c_uint32 = 3
total: c_int64 = 0
for i in range(-1, n):
total = total + 1
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,23 @@
# Rebinding the loop variable does not change the trip count: range() steps a
# counter of its own, as in Python. Returns 10.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
total: c_int64 = 0
for i in range(10):
total = total + 1
i = 100 # noqa: F841 -- rebinding is the point of the test
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,28 @@
# Two unrelated loops that reuse `i`. The first counts over an unsigned
# bound, the second over a signed one. The second loop's `i < 0` has to see
# -3, -2 and -1, not the unsigned slot the first loop left behind.
# Returns 3 + 3 * 100 = 303.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64, c_uint64
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int64:
n: c_uint64 = 3
total: c_int64 = 0
for i in range(n):
total = total + 1
for i in range(-3, 3):
if i < 0:
total = total + 100
return total
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,24 @@
# The only way out of `while True` is the return in its body, so the block
# after the loop is unreachable. Whatever closes it off has to match the
# function's c_int32 return type. Returns 6.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int32
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int32:
i: c_int32 = 0
while True:
i = i + 1
if i > 5:
return i
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,22 @@
# A return inside an if-branch is lowered in the function's declared return
# type (i32 here), not a default i64 that llc rejects.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int32
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def hello(ctx: c_void_p) -> c_int32:
x = 1
if x == 1:
return 7
return 0
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,37 @@
from pythonbpf import bpf, map, section, bpfglobal, compile
from vmlinux import XDP_PASS
from pythonbpf.maps import HashMap
from ctypes import c_void_p, c_int64
# An expression (`prev + 1`) passed straight to map.update(): it is evaluated
# into a scratch slot and the helper gets that slot's address. This was once
# refused for want of a slot allocated up front, and now works.
@bpf
@map
def count() -> HashMap:
return HashMap(key=c_int64, value=c_int64, max_entries=1)
@bpf
@section("xdp")
def hello_world(ctx: c_void_p) -> c_int64:
prev = count.lookup(0)
if prev:
count.update(0, prev + 1)
return XDP_PASS
else:
count.update(0, 1)
return XDP_PASS
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -4,12 +4,11 @@ from pythonbpf.maps import HashMap
from ctypes import c_void_p, c_int64
# NOTE: This example exposes the problems with our typing system.
# We can't do steps on line 25 and 27.
# prev is of type i64**. For prev + 1, we deref it down to i64
# To assign it back to prev, we need to go back to i64**.
# We cannot allocate space for the intermediate type now.
# We probably need to track the ref/deref chain for each variable.
# `prev` starts as a map lookup result (a pointer) and is rebound to
# `prev + 1`, which lives in a temporary that `prev` then points at. The update
# must store the incremented value: the helper gets the pointer the local
# holds, not the address of the local's own slot (that used to store a kernel
# stack address into the map).
@bpf

View File

@ -0,0 +1,41 @@
# Counts packets in a one-entry map and lets every packet through. It used to
# be an xfail, but the only thing failing was the old `count().lookup(...)`
# spelling of a map call; `count.lookup(...)` is the current one.
from pythonbpf import bpf, map, section, bpfglobal, compile
from pythonbpf.maps import HashMap
from vmlinux import XDP_PASS
from vmlinux import struct_xdp_md
from ctypes import c_int64
@bpf
@map
def count() -> HashMap:
return HashMap(key=c_int64, value=c_int64, max_entries=1)
@bpf
@section("xdp")
def hello_world(ctx: struct_xdp_md) -> c_int64:
key = 0
one = 1
prev = count.lookup(key)
if prev:
prevval = prev + 1
print(f"count: {prevval}")
count.update(key, prevval)
return XDP_PASS
else:
count.update(key, one)
return XDP_PASS
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

182
tests/property/cints.py Normal file
View File

@ -0,0 +1,182 @@
"""
A reference model of C's integer rules, as docs/user-guide/integers.md states
them for PythonBPF.
clang is the specification; this model is not. It exists for two reasons:
* To keep undefined behaviour out of the generated programs. Division by zero,
INT_MIN / -1 and out-of-range shift counts are undefined in C (and the first
two trap on the host), so a program that would hit them is discarded before
anything is compiled. Signed overflow is left in: the C reference is built
with -fwrapv, which defines it as wrapping, as BPF does.
* To give a third opinion when PythonBPF and clang disagree. If the model
disagrees with clang, the model is wrong; the property tests report that
separately from a compiler bug.
Values are plain Python ints holding the value as the type reads it (so a
c_int8 holding 0xff is -1), and every operation returns (value, type).
"""
from dataclasses import dataclass
class UndefinedBehaviour(Exception):
"""The C program would be undefined here, so the example is discarded."""
@dataclass(frozen=True)
class IntType:
name: str # the ctypes name, as written in PythonBPF source
c_name: str # the C type, as written in the reference program
bits: int
signed: bool
@property
def is_bool(self) -> bool:
return self.name == "c_bool"
@property
def min(self) -> int:
return -(1 << (self.bits - 1)) if self.signed else 0
@property
def max(self) -> int:
if self.is_bool:
return 1
return (1 << (self.bits - 1)) - 1 if self.signed else (1 << self.bits) - 1
def __repr__(self) -> str:
return self.name
C_INT8 = IntType("c_int8", "signed char", 8, True)
C_INT16 = IntType("c_int16", "short", 16, True)
C_INT32 = IntType("c_int32", "int", 32, True)
C_INT64 = IntType("c_int64", "long long", 64, True)
C_UINT8 = IntType("c_uint8", "unsigned char", 8, False)
C_UINT16 = IntType("c_uint16", "unsigned short", 16, False)
C_UINT32 = IntType("c_uint32", "unsigned int", 32, False)
C_UINT64 = IntType("c_uint64", "unsigned long long", 64, False)
C_BOOL = IntType("c_bool", "_Bool", 8, False)
INTEGER_TYPES = [
C_INT8,
C_INT16,
C_INT32,
C_INT64,
C_UINT8,
C_UINT16,
C_UINT32,
C_UINT64,
]
ALL_TYPES = INTEGER_TYPES + [C_BOOL]
def convert(value: int, ty: IntType) -> int:
"""C's conversion of `value` to `ty`: _Bool is `value != 0`; otherwise the
low `bits` bits, read with ty's sign (truncation, or reinterpretation at
the same width; widening is the identity on the value)."""
if ty.is_bool:
return int(value != 0)
value &= (1 << ty.bits) - 1
if ty.signed and value >> (ty.bits - 1):
value -= 1 << ty.bits
return value
def literal_type(value: int) -> IntType:
"""A non-negative decimal literal is an `int` if it fits, else 64-bit
signed (C's `long`/`long long`, the same on BPF and LP64 hosts)."""
assert 0 <= value <= C_INT64.max, value
return C_INT32 if value <= C_INT32.max else C_INT64
def promote(ty: IntType) -> IntType:
"""Integer promotion: anything narrower than int (and _Bool) becomes int."""
return C_INT32 if ty.bits < 32 else ty
def common_type(a: IntType, b: IntType) -> IntType:
"""C's usual arithmetic conversions, as integers.md lists them."""
a, b = promote(a), promote(b)
if a.signed == b.signed:
return a if a.bits >= b.bits else b
unsigned, signed = (a, b) if not a.signed else (b, a)
return unsigned if unsigned.bits >= signed.bits else signed
def untyped_local_type(ty: IntType) -> IntType:
"""An undeclared local is a 64-bit slot with the sign of its expression."""
return C_INT64 if ty.signed else C_UINT64
ARITH_OPS = ["+", "-", "*", "&", "|", "^"]
DIV_OPS = ["/", "//", "%"]
SHIFT_OPS = ["<<", ">>"]
COMPARE_OPS = ["<", "<=", ">", ">=", "==", "!="]
def binary_type(op: str, a: IntType, b: IntType) -> IntType:
if op in SHIFT_OPS:
return promote(a) # a shift has the type of its promoted left operand
if op in COMPARE_OPS:
return C_INT32
return common_type(a, b)
def _trunc_div(a: int, b: int) -> int:
q = abs(a) // abs(b)
return q if (a < 0) == (b < 0) else -q
def binary(op: str, a: int, a_ty: IntType, b: int, b_ty: IntType) -> int:
"""Value of `a op b` in C, given each operand's value and type."""
if op in SHIFT_OPS:
ty = promote(a_ty)
if not 0 <= b < ty.bits:
raise UndefinedBehaviour(f"shift count {b} for a {ty.bits}-bit value")
a = convert(a, ty)
# Python's >> on a negative int is arithmetic, as C's is on a signed
# type; an unsigned value is never negative, so it shifts in zeros.
return convert(a << b if op == "<<" else a >> b, ty)
ty = common_type(a_ty, b_ty)
a, b = convert(a, ty), convert(b, ty)
if op in COMPARE_OPS:
return int(
{
"<": a < b,
"<=": a <= b,
">": a > b,
">=": a >= b,
"==": a == b,
"!=": a != b,
}[op]
)
if op in DIV_OPS:
if b == 0:
raise UndefinedBehaviour("division by zero")
if ty.signed and a == ty.min and b == -1:
raise UndefinedBehaviour(f"{ty.name} minimum divided by -1")
q = _trunc_div(a, b)
return convert(q if op != "%" else a - q * b, ty)
return convert(
{
"+": a + b,
"-": a - b,
"*": a * b,
"&": a & b,
"|": a | b,
"^": a ^ b,
}[op],
ty,
)
def negate(a: int, a_ty: IntType) -> int:
ty = promote(a_ty)
return convert(-convert(a, ty), ty)
def logical_not(a: int) -> int:
return int(a == 0)

188
tests/property/harness.py Normal file
View File

@ -0,0 +1,188 @@
"""
Compile a generated Program both ways, run both on the host, and compare.
PythonBPF's IR is JIT compiled on the host (tests/framework/host_jit.py); the
C reference is compiled by clang, with -fwrapv, to a native object file that
the same JIT loads and links. Native code rather than `-target bpf` IR: the
IR a newer clang emits need not parse with llvmlite's LLVM, while an ELF
object always loads, and a fixed-width integer computation means the same on
BPF and on an LP64 host. (An object, not a shared library: linking was 60 of
the 90 ms an example took.)
Both run in a worker process. The model only rules out undefined behaviour
for the *correct* types, so a miscompile can still trap (SIGFPE on a signed
division PythonBPF should not have emitted) or abort inside LLVM; in the
pytest process that would end the whole run.
"""
import atexit
import ctypes
import itertools
import logging
import multiprocessing
import shutil
import subprocess
import tempfile
from concurrent.futures import ProcessPoolExecutor
from concurrent.futures.process import BrokenProcessPool
from pathlib import Path
import llvmlite.binding as llvm
from hypothesis import assume, note
from hypothesis.control import currently_in_test_context
from pythonbpf.codegen import compile_to_ir
from tests.framework.host_jit import run_function
from tests.property.cints import IntType, UndefinedBehaviour
from tests.property.programs import Program
CLANG = shutil.which("clang")
WORKDIR = Path(tempfile.mkdtemp(prefix="pythonbpf-pbt-"))
atexit.register(shutil.rmtree, WORKDIR, ignore_errors=True)
_names = itertools.count()
class PythonBPFCompileError(Exception):
pass
class WorkerCrashed(Exception):
pass
# ── worker side ─────────────────────────────────────────────────────────────
def _run_ir(ll_text: str, restype_name: str) -> int:
return run_function(ll_text, "prog", getattr(ctypes, restype_name))
def _run_object(path: str, restype_name: str) -> int:
llvm.initialize_native_target()
llvm.initialize_native_asmprinter()
tm = llvm.Target.from_default_triple().create_target_machine()
engine = llvm.create_mcjit_compiler(llvm.parse_assembly(""), tm)
engine.add_object_file(path)
engine.finalize_object()
func = ctypes.CFUNCTYPE(getattr(ctypes, restype_name), ctypes.c_void_p)(
engine.get_function_address("prog")
)
return int(func(None))
_pool = None
def _in_worker(fn, *args):
global _pool
if _pool is None:
_pool = ProcessPoolExecutor(
max_workers=1, mp_context=multiprocessing.get_context("forkserver")
)
try:
return _pool.submit(fn, *args).result(timeout=60)
except BrokenProcessPool:
_pool = None
raise WorkerCrashed from None
@atexit.register
def _shutdown():
if _pool is not None:
_pool.shutdown(cancel_futures=True)
# ── compile ─────────────────────────────────────────────────────────────────
class _Errors(logging.Handler):
"""compile_to_ir can log an ERROR and carry on; that is a failure too."""
def __init__(self):
super().__init__(logging.ERROR)
self.messages = []
def emit(self, record):
self.messages.append(record.getMessage())
def compile_pythonbpf(source: str) -> str:
stem = WORKDIR / f"p{next(_names)}"
py, ll = stem.with_suffix(".py"), stem.with_suffix(".ll")
py.write_text(source)
errors = _Errors()
logger = logging.getLogger("pythonbpf")
logger.addHandler(errors)
try:
compile_to_ir(str(py), str(ll), loglevel=logging.WARNING)
except Exception as e:
raise PythonBPFCompileError(f"{type(e).__name__}: {e}") from e
finally:
logger.removeHandler(errors)
if errors.messages:
raise PythonBPFCompileError("; ".join(errors.messages))
return ll.read_text()
def compile_c(source: str) -> Path:
stem = WORKDIR / f"c{next(_names)}"
c, obj = stem.with_suffix(".c"), stem.with_suffix(".o")
c.write_text(source)
subprocess.run(
[CLANG, "-O0", "-fwrapv", "-w", "-c", "-fPIC", str(c), "-o", str(obj)],
check=True,
capture_output=True,
text=True,
)
return obj
# ── the property ────────────────────────────────────────────────────────────
def check_against_clang(program: Program, expected) -> None:
"""Assert PythonBPF computes what clang computes for `program`.
`expected` is a zero-argument callable returning the model's value; if it
raises UndefinedBehaviour the example is discarded before anything runs.
"""
in_hypothesis = currently_in_test_context()
try:
model = expected()
except UndefinedBehaviour:
if not in_hypothesis:
raise
assume(False)
py_source, c_source = program.py_source(), program.c_source()
# Shown with every failure: by note() under Hypothesis (which prints the
# shrunk example's notes), and in the message for a plain test.
shown = (
f"\n\nPythonBPF source:\n{py_source}\nC reference:\n{c_source}\nmodel: {model}"
)
if in_hypothesis:
note(shown)
shown = ""
ret: IntType = program.ret
reference = _in_worker(_run_object, str(compile_c(c_source)), ret.name)
assert reference == model, (
f"the model in tests/property/cints.py says {model}, clang says "
f"{reference}: the model is wrong, not PythonBPF{shown}"
)
try:
ll_text = compile_pythonbpf(py_source)
except PythonBPFCompileError as e:
raise AssertionError(
f"PythonBPF failed to compile the program: {e}{shown}"
) from None
try:
got = _in_worker(_run_ir, ll_text, ret.name)
except WorkerCrashed:
raise AssertionError(
"PythonBPF's code crashed the host JIT (a trap or an LLVM abort); "
f"clang returns {reference}{shown}"
) from None
assert got == reference, (
f"PythonBPF returns {got}, clang returns {reference}{shown}"
)

View File

@ -0,0 +1,133 @@
"""
Known divergences from C that the property tests step around.
Each gap has a predicate that recognises a generated program hitting it, so
the properties keep looking for *new* bugs instead of re-finding this one, and
a pinned program that test_known_gaps.py runs as a strict xfail. When a fix
lands, that test XPASSes and fails the run: delete the gap here then, and the
properties start generating those programs again.
"""
from dataclasses import dataclass
from typing import Callable
from tests.property.cints import (
C_INT8,
C_INT32,
C_INT64,
C_UINT8,
C_UINT32,
C_UINT64,
COMPARE_OPS,
SHIFT_OPS,
common_type,
promote,
untyped_local_type,
)
from tests.property.programs import Bin, ExpressionProgram, Lit, Neg, Not, Var
def walk(expr):
yield expr
for child in ("operand", "left", "right"):
if hasattr(expr, child):
yield from walk(getattr(expr, child))
def nodes(program: ExpressionProgram):
for _, _, expr in program.temps:
yield from walk(expr)
yield from walk(program.result)
@dataclass(frozen=True)
class Gap:
name: str
reason: str
hits: Callable[[ExpressionProgram], bool]
# The smallest program showing it, run by test_known_gaps.py as a strict xfail
example: ExpressionProgram
GAPS: list[Gap] = [
Gap(
"negated-literal-rank",
"`-2147483648` folds to a literal ranked by its negated value (int); "
"C ranks -x by x, and 2147483648 is a long long "
"(pythonbpf/expr/expr_pass.py, the USub constant fold)",
lambda p: any(
isinstance(n, Neg)
and isinstance(n.operand, Lit)
and n.operand.value == 2**31
for n in nodes(p)
),
# C: a 64-bit signed compare, 1. PythonBPF: an unsigned 32-bit one, 0.
ExpressionProgram(
[("a0", C_UINT32, 1)], [], Bin("<", Neg(Lit(2**31)), Var("a0", C_UINT32))
),
),
Gap(
"untyped-local-unary-or-compare",
'`t = -x`, `t = not x` and `t = a < b` fail with "Undefined variable '
't": the allocation pass has no case for a UnaryOp or Compare '
"right-hand side, so the local never gets a slot "
"(pythonbpf/allocation_pass.py, _allocate_for_value)",
lambda p: any(
isinstance(e, (Neg, Not)) or (isinstance(e, Bin) and e.op in COMPARE_OPS)
for _, _, e in p.temps
),
ExpressionProgram(
[("a0", C_INT32, 3)],
[("t0", C_INT64, Neg(Var("a0", C_INT32)))],
Var("t0", C_INT64),
),
),
Gap(
"shift-result-type",
"a shift is typed by the usual arithmetic conversions of both operands; "
"C types it by the promoted left operand alone, so `int << s64` must "
"wrap at 32 bits and `s64 >> u64` must be arithmetic "
"(pythonbpf/expr/expr_pass.py _handle_binary_op_impl, "
"type_inference.py infer_int_type, and for `<<=`/`>>=` "
"functions/functions_pass.py's augmented assignment)",
lambda p: any(
isinstance(n, Bin)
and n.op in SHIFT_OPS
and promote(n.left.ty) != common_type(n.left.ty, n.right.ty)
for n in nodes(p)
),
# C: -8 >> 1 in s64, -4. PythonBPF: a logical shift in u64.
ExpressionProgram(
[("a0", C_INT64, -8), ("a1", C_UINT64, 1)],
[],
Bin(">>", Var("a0", C_INT64), Var("a1", C_UINT64)),
),
),
Gap(
"untyped-copy-keeps-source-type",
"`t = a` gives t a's own type, whatever it is: a c_uint32 copy stays "
"u32 and a c_int8 copy stays narrow and promotes to int, while "
"integers.md says an undeclared local is always 64 bits with the "
"expression's sign. Only a 64-bit source is unaffected. Code or doc: "
"a decision (pythonbpf/allocation_pass.py, _allocate_for_name)",
lambda p: any(
isinstance(e, Var) and e.ty != untyped_local_type(e.ty)
for _, _, e in p.temps
),
# C, by integers.md: -128 + (u64)1 is a u64, so 0 < it holds. PythonBPF:
# t1 stays a u8, the sum is the int -127, and the compare is false.
ExpressionProgram(
[("a0", C_INT8, -128), ("a1", C_UINT8, 1)],
[("t1", untyped_local_type(C_UINT8), Var("a1", C_UINT8))],
Bin(
"<",
Lit(0),
Bin("+", Var("a0", C_INT8), Var("t1", untyped_local_type(C_UINT8))),
),
),
),
]
def gap_of(program: ExpressionProgram) -> "Gap | None":
return next((g for g in GAPS if g.hits(program)), None)

358
tests/property/programs.py Normal file
View File

@ -0,0 +1,358 @@
"""
Generated integer programs, printed twice: as PythonBPF source and as the C
program clang compiles for the same computation.
A program is straight-line: input locals declared with a constructor and a
literal, optional temporaries, and a returned expression. Inputs are locals,
not literals, so neither compiler sees a constant expression; clang at -O0
and PythonBPF both load them from the stack.
What is not generated, and why (bugs PythonBPF has are generated, and stepped
around by tests/property/known_gaps.py instead):
* `~x`: PythonBPF does not support unary invert (a clean error).
* `and` / `or`: not C's integer operators, and not an integer question.
* Literal initialisers of @bpfglobal variables other than 0, outside
test_int_conversions' strict-xfail site: a negative one is silently
emitted as 0 (pythonbpf/globals_pass.py).
"""
from dataclasses import dataclass, field
from hypothesis import strategies as st
from tests.property.cints import (
ALL_TYPES,
ARITH_OPS,
C_INT32,
C_INT64,
COMPARE_OPS,
DIV_OPS,
SHIFT_OPS,
IntType,
binary,
binary_type,
convert,
literal_type,
logical_not,
negate,
promote,
untyped_local_type,
)
INT64_MIN = -(1 << 63)
INT64_MAX = (1 << 63) - 1
def literal_source(value: int) -> str:
"""A decimal literal for `value` in [INT64_MIN, INT64_MAX], valid in both
languages and of a 64-bit-or-narrower signed type in C. Hex is never
used: C gives a hex literal that does not fit `int` an unsigned type."""
if value >= 0:
return str(value)
if value == INT64_MIN:
return "(-9223372036854775807 - 1)"
return f"(-{-value})"
def as_literal(value: int, ty: IntType) -> int:
"""A literal that converts to `value` in `ty` (a u64 above INT64_MAX is
written as the negative number with the same bits)."""
return value - (1 << 64) if value > INT64_MAX else value
# ── expressions ─────────────────────────────────────────────────────────────
@dataclass(frozen=True)
class Var:
name: str
ty: IntType
def py(self) -> str:
return self.name
def c(self) -> str:
return self.name
def eval(self, env: dict) -> int:
return env[self.name]
@dataclass(frozen=True)
class Lit:
value: int # non-negative; a negative constant is Neg(Lit(n)), as in both languages
@property
def ty(self) -> IntType:
return literal_type(self.value)
def py(self) -> str:
return str(self.value)
def c(self) -> str:
return str(self.value)
def eval(self, env: dict) -> int:
return self.value
@dataclass(frozen=True)
class Neg:
operand: object
@property
def ty(self) -> IntType:
return promote(self.operand.ty)
def py(self) -> str:
return f"(-{self.operand.py()})"
def c(self) -> str:
return f"(-{self.operand.c()})"
def eval(self, env: dict) -> int:
return negate(self.operand.eval(env), self.operand.ty)
@dataclass(frozen=True)
class Not:
operand: object
@property
def ty(self) -> IntType:
return C_INT32 # C's `!` is an int
def py(self) -> str:
return f"(not {self.operand.py()})"
def c(self) -> str:
return f"(!{self.operand.c()})"
def eval(self, env: dict) -> int:
return logical_not(self.operand.eval(env))
@dataclass(frozen=True)
class Cast:
ty: IntType
operand: object
def py(self) -> str:
return f"{self.ty.name}({self.operand.py()})"
def c(self) -> str:
return f"(({self.ty.c_name})({self.operand.c()}))"
def eval(self, env: dict) -> int:
return convert(self.operand.eval(env), self.ty)
@dataclass(frozen=True)
class Bin:
op: str
left: object
right: object
@property
def ty(self) -> IntType:
return binary_type(self.op, self.left.ty, self.right.ty)
def py(self) -> str:
return f"({self.left.py()} {self.op} {self.right.py()})"
def c(self) -> str:
op = "/" if self.op == "//" else self.op # both are C's truncating `/`
return f"({self.left.c()} {op} {self.right.c()})"
def eval(self, env: dict) -> int:
return binary(
self.op,
self.left.eval(env),
self.left.ty,
self.right.eval(env),
self.right.ty,
)
# ── programs ────────────────────────────────────────────────────────────────
PY_HEADER = """\
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import (
c_void_p,
c_bool,
c_int8,
c_int16,
c_int32,
c_int64,
c_uint8,
c_uint16,
c_uint32,
c_uint64,
)
"""
PY_FOOTER = """
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()
"""
@dataclass
class Program:
"""One program in both languages. `globals` are (name, type, initial
literal); `py_body` and `c_body` are the statements of `prog`, in order."""
py_body: list[str]
c_body: list[str]
ret: IntType = C_INT64
globals: list[tuple[str, IntType, int]] = field(default_factory=list)
def py_source(self) -> str:
parts = [PY_HEADER]
for name, ty, init in self.globals:
parts.append(
f"\n@bpf\n@bpfglobal\ndef {name}() -> {ty.name}:\n"
f" return {ty.name}({literal_source(init)})\n"
)
body = "".join(f" {line}\n" for line in self.py_body)
parts.append(
'\n@bpf\n@section("tracepoint/syscalls/sys_enter_getpid")\n'
f"def prog(ctx: c_void_p) -> {self.ret.name}:\n{body}"
)
parts.append(PY_FOOTER)
return "".join(parts)
def c_source(self) -> str:
lines = [
f"{ty.c_name} {name} = {literal_source(init)};"
for name, ty, init in self.globals
]
lines.append(f"{self.ret.c_name} prog(void *ctx)\n{{")
lines += [f" {line}" for line in self.c_body]
lines.append("}")
return "\n".join(lines) + "\n"
def input_decl(name: str, ty: IntType, value: int) -> tuple[str, str]:
"""`name = c_T(lit)` and `T name = lit;` for an input holding `value`."""
lit = literal_source(as_literal(value, ty))
return f"{name} = {ty.name}({lit})", f"{ty.c_name} {name} = {lit};"
@dataclass
class ExpressionProgram:
"""Inputs, temporaries and a returned expression; `program()` prints it
and `expected()` is the model's value (raising UndefinedBehaviour)."""
inputs: list[tuple[str, IntType, int]]
temps: list[tuple[str, IntType, object]] # name, declared type, expression
result: object
def program(self) -> Program:
py, c = [], []
for name, ty, value in self.inputs:
p, q = input_decl(name, ty, value)
py.append(p)
c.append(q)
for name, ty, expr in self.temps:
py.append(f"{name} = {expr.py()}")
c.append(f"{ty.c_name} {name} = {expr.c()};")
py.append(f"return {self.result.py()}")
c.append(f"return {self.result.c()};")
return Program(py, c)
def expected(self) -> int:
env = {name: value for name, _, value in self.inputs}
for name, ty, expr in self.temps:
env[name] = convert(expr.eval(env), ty)
return convert(self.result.eval(env), C_INT64)
# ── strategies ──────────────────────────────────────────────────────────────
def edge_values(ty: IntType) -> list[int]:
"""The values where integer bugs live: zero, ±1, the type's limits, and
the limits of every narrower type."""
candidates = {0, 1, -1, 2, ty.min, ty.max, ty.min + 1, ty.max - 1}
for k in (7, 8, 15, 16, 31, 32, 63):
candidates |= {1 << k, (1 << k) - 1, -(1 << k), -(1 << k) + 1}
return sorted(v for v in candidates if ty.min <= v <= ty.max)
def values_of(ty: IntType) -> st.SearchStrategy[int]:
return st.one_of(st.sampled_from(edge_values(ty)), st.integers(ty.min, ty.max))
LITERALS = st.one_of(
st.sampled_from(
[0, 1, 2, 3, 7, 8, 31, 32, 63, 64, 127, 128, 255, 256, 32767, 32768, 65535]
+ [65536, 2**31 - 1, 2**31, 2**32 - 1, 2**32, 2**63 - 1]
),
st.integers(0, INT64_MAX),
)
@st.composite
def expressions(draw, leaves: list[Var], depth: int):
if depth == 0 or draw(st.integers(0, 3)) == 0:
# Mostly inputs: a literal is non-negative and often small, so a
# tree of literals rarely reaches a sign-sensitive case.
if leaves and draw(st.integers(0, 3)) > 0:
return draw(st.sampled_from(leaves))
return Lit(draw(LITERALS))
sub = expressions(leaves, depth - 1)
kind = draw(
st.sampled_from(
["arith", "arith", "div", "shift", "compare", "neg", "not", "cast"]
)
)
if kind == "neg":
return Neg(draw(sub))
if kind == "not":
return Not(draw(sub))
if kind == "cast":
return Cast(draw(st.sampled_from(ALL_TYPES)), draw(sub))
if kind == "shift":
left, right = draw(sub), draw(sub)
# Mask the count into range so the shift is defined; the mask is a
# literal, so `right & mask` is never negative.
mask = Lit(promote(left.ty).bits - 1)
return Bin(draw(st.sampled_from(SHIFT_OPS)), left, Bin("&", right, mask))
op = draw(
st.sampled_from(
{"arith": ARITH_OPS, "div": DIV_OPS, "compare": COMPARE_OPS}[kind]
)
)
return Bin(op, draw(sub), draw(sub))
@st.composite
def expression_programs(
draw, max_inputs: int = 4, max_temps: int = 2, max_depth: int = 4
):
inputs = []
for i in range(draw(st.integers(1, max_inputs))):
ty = draw(st.sampled_from(ALL_TYPES))
inputs.append((f"a{i}", ty, draw(values_of(ty))))
leaves = [Var(name, ty) for name, ty, _ in inputs]
temps = []
for i in range(draw(st.integers(0, max_temps))):
expr = draw(expressions(leaves, draw(st.integers(1, 3))))
# A constructor call declares the local with that type; anything else
# is an undeclared local: 64 bits, with the expression's sign.
ty = expr.ty if isinstance(expr, Cast) else untyped_local_type(expr.ty)
temps.append((f"t{i}", ty, expr))
leaves.append(Var(f"t{i}", ty))
result = draw(expressions(leaves, draw(st.integers(0, max_depth))))
return ExpressionProgram(inputs, temps, result)

View File

@ -0,0 +1,193 @@
"""
Integer conversions at every place PythonBPF converts: PythonBPF computes what
clang computes.
A value of one type is converted to another at each site where integers.md
says a conversion happens (constructor calls, typed and untyped locals,
globals, `return`, augmented assignment). Random expressions reach these sites
only by accident; here every (source type, destination type, site) triple is
tested, with Hypothesis choosing the values, the edge values of each type
first.
"""
import pytest
from hypothesis import given, settings
from hypothesis import strategies as st
from tests.property.cints import (
ALL_TYPES,
ARITH_OPS,
C_INT64,
DIV_OPS,
SHIFT_OPS,
binary,
common_type,
convert,
promote,
untyped_local_type,
)
from tests.property.harness import CLANG, check_against_clang
from tests.property.programs import (
INT64_MAX,
Bin,
Cast,
Lit,
Program,
Var,
as_literal,
input_decl,
literal_source,
values_of,
)
pytestmark = pytest.mark.skipif(CLANG is None, reason="clang is not installed")
# How the converted value is read back. `return x` alone shows the value but
# not the type it was stored as, and a later use depends on that type: these
# read it through an operation whose result changes with its sign and width.
PROBES = {
"value": lambda x: x,
# -1 in x's type (promoted), halved: 0 if signed, and u32 and u64 differ
"sign_and_width": lambda x: Bin("/", Bin("-", Bin("*", x, Lit(0)), Lit(1)), Lit(2)),
# INT_MAX + 1 wraps if x's type promotes to a 32-bit int, not if 64-bit
"int_overflow": lambda x: Bin(
"+", Bin("+", Bin("*", x, Lit(0)), Lit(2**31 - 1)), Lit(1)
),
}
def _site_program(site, src, dst, value, other, probe):
"""(Program, model) for converting `a0`, a `src` holding `value`, to `dst`
at `site`, then returning probe(the converted value). `other` is a second
value, used where a site needs one."""
decl_py, decl_c = input_decl("a0", src, value)
def read_back(name, ty, stored, py, c, globals=()):
"""Finish a program whose statements stored `stored` into `name`."""
expr = probe(Var(name, ty))
program = Program(
py + [f"return {expr.py()}"],
c + [f"return {expr.c()};"],
globals=list(globals),
)
return program, lambda: convert(expr.eval({name: stored()}), C_INT64)
if site == "constructor":
expr = probe(Cast(dst, Var("a0", src)))
return Program(
[decl_py, f"return {expr.py()}"], [decl_c, f"return {expr.c()};"]
), lambda: convert(expr.eval({"a0": value}), C_INT64)
if site == "declare":
return read_back(
"x",
dst,
lambda: convert(value, dst),
[decl_py, f"x = {dst.name}(a0)"],
[decl_c, f"{dst.c_name} x = a0;"],
)
if site == "reassign":
return read_back(
"x",
dst,
lambda: convert(value, dst),
[decl_py, f"x = {dst.name}(0)", "x = a0"],
[decl_c, f"{dst.c_name} x = 0;", "x = a0;"],
)
if site == "untyped_local":
# dst plays no part: an undeclared local is 64 bits with a0's sign
local = untyped_local_type(src)
return read_back(
"x",
local,
lambda: convert(value, local),
[decl_py, "x = a0"],
[decl_c, f"{local.c_name} x = a0;"],
)
if site == "global_store":
return read_back(
"out",
dst,
lambda: convert(value, dst),
[decl_py, "global out", "out = a0"],
[decl_c, "out = a0;"],
globals=[("out", dst, 0)],
)
if site == "return":
# Read through the function's own return type, so no probe.
return Program([decl_py, "return a0"], [decl_c, "return a0;"], ret=dst), (
lambda: convert(value, dst)
)
if site == "global_init":
# `value` is used as the initialiser literal itself
lit = as_literal(value, src)
return read_back("g", dst, lambda: convert(lit, dst), [], [], [("g", dst, lit)])
if site.startswith("augassign"):
op = site.split(" ")[1]
init = as_literal(other, dst)
return read_back(
"x",
dst,
lambda: convert(binary(op, convert(init, dst), dst, value, src), dst),
[decl_py, f"x = {dst.name}({literal_source(init)})", f"x {op}= a0"],
[
decl_c,
f"{dst.c_name} x = {literal_source(init)};",
f"x {'/' if op == '//' else op}= a0;",
],
)
raise ValueError(site)
SITES = [
"constructor",
"declare",
"reassign",
"untyped_local",
"global_store",
"return",
"global_init",
] + [f"augassign {op}" for op in ARITH_OPS + DIV_OPS + SHIFT_OPS]
# Parametrized over the destination type as well as the site, so every type
# gets examples on every run: drawn at random, a type-specific rule (such as
# c_bool's `!= 0`) went untested in some runs. 162 parameters, so a
# sixteenth of the profile's examples each.
@pytest.mark.parametrize("dst", ALL_TYPES, ids=lambda t: t.name)
@pytest.mark.parametrize("site", SITES)
@settings(max_examples=max(5, settings.default.max_examples // 16))
@given(data=st.data())
def test_conversion_matches_clang(site, dst, data):
# Known gaps are stepped around by drawing only what avoids them, not by
# filtering (test_known_gaps.py pins each one):
sources = ALL_TYPES
if site in ("augassign <<", "augassign >>"):
# shift-result-type: `x >>= a` is typed by both operands, so only a
# source that leaves the type at x's own promoted type
sources = [t for t in ALL_TYPES if common_type(dst, t) == promote(dst)]
if site == "untyped_local":
# untyped-copy-keeps-source-type: `x = a0` keeps a0's type, which is
# right only for a 64-bit a0 (and dst plays no part here)
sources = [t for t in ALL_TYPES if untyped_local_type(t) == t]
if site == "global_init" and dst.is_bool:
pytest.skip("known gap global-initialiser: c_bool(2) keeps its low bit")
src = data.draw(st.sampled_from(sources), label="src")
if site in ("augassign <<", "augassign >>"):
# a count out of range is undefined in C
top = min(promote(dst).bits - 1, src.max)
value = data.draw(st.integers(0, top), label="count")
elif site == "global_init":
# global-initialiser: a negative initialiser is emitted as 0. `value`
# is the initialiser literal itself, out-of-range ones included.
value = data.draw(st.integers(0, INT64_MAX), label="initialiser")
else:
value = data.draw(values_of(src), label="value")
other = data.draw(values_of(dst), label="other")
# global_init's gap is the value itself, which the type probes multiply
# away (global_store reads a global's type through them)
probes = ["value"] if site == "global_init" else sorted(PROBES)
probe = data.draw(st.sampled_from(probes), label="probe")
program, expected = _site_program(site, src, dst, value, other, PROBES[probe])
check_against_clang(program, expected)

View File

@ -0,0 +1,93 @@
"""
Integer expressions: PythonBPF computes what clang computes.
Random straight-line programs over every ctypes integer type (and c_bool):
arithmetic, division and remainder, shifts, comparisons used as values, unary
minus, `not`, constructor casts and untyped temporaries, nested. Each one is
printed as PythonBPF and as C, both are run on the host, and the results must
be equal. The rules being exercised are docs/user-guide/integers.md; clang is
their specification.
"""
import pytest
from hypothesis import assume, example, given
from tests.property.cints import (
C_INT8,
C_INT32,
C_INT64,
C_UINT8,
C_UINT16,
C_UINT32,
C_UINT64,
)
from tests.property.harness import CLANG, check_against_clang
from tests.property.known_gaps import gap_of
from tests.property.programs import (
Bin,
Cast,
ExpressionProgram,
Lit,
Neg,
Var,
expression_programs,
)
pytestmark = pytest.mark.skipif(CLANG is None, reason="clang is not installed")
def _p(inputs, result, temps=()):
return ExpressionProgram(list(inputs), list(temps), result)
def _v(name, ty):
return Var(name, ty)
# The worked examples in integers.md, pinned so they always run.
DOC_EXAMPLES = [
# u32 * u32 wraps at 32 bits before any widening
_p(
[("a0", C_UINT32, 0x80000000), ("a1", C_UINT32, 2)],
Bin("*", _v("a0", C_UINT32), _v("a1", C_UINT32)),
),
# mixed signs go unsigned: 10u / -2 is 10 / 0xfffffffe
_p(
[("a0", C_UINT32, 10), ("a1", C_INT32, -2)],
Bin("/", _v("a0", C_UINT32), _v("a1", C_INT32)),
),
# c_uint64(10) > c_int64(-1) is an unsigned compare: false
_p(
[("a0", C_UINT64, 10), ("a1", C_INT64, -1)],
Bin(">", _v("a0", C_UINT64), _v("a1", C_INT64)),
),
# the literal -2 is an int, so count / -2 is a u32 division
_p([("a0", C_UINT32, 10)], Bin("/", _v("a0", C_UINT32), Neg(Lit(2)))),
# narrow operands promote to int: s8 * u16 is a signed 32-bit product
_p(
[("a0", C_INT8, -3), ("a1", C_UINT16, 65535)],
Bin("*", _v("a0", C_INT8), _v("a1", C_UINT16)),
),
# a constructor-typed temporary keeps its width: c_uint8(300) is 44
_p(
[("a0", C_INT32, 300)],
Bin("+", _v("t0", C_UINT8), Lit(0)),
temps=[("t0", C_UINT8, Cast(C_UINT8, _v("a0", C_INT32)))],
),
]
def _pin(*programs):
def wrap(fn):
for program in reversed(programs):
fn = example(program)(fn)
return fn
return wrap
@_pin(*DOC_EXAMPLES)
@given(expression_programs())
def test_integer_expression_matches_clang(program):
assume(gap_of(program) is None)
check_against_clang(program.program(), program.expected)

View File

@ -0,0 +1,55 @@
"""
Every binary operator on every pair of operand types: PythonBPF computes what
clang computes.
test_int_expressions finds bugs in how operations combine, but random trees
rarely put, say, a negative dividend under a signed `%` and then return the
result undisturbed (about 3 programs in 600 did). This property is the
enumerated complement: `a0 op a1` for each operator, left type and right type,
with Hypothesis choosing the operand values, the edge values of each type
first. Shift counts are drawn in range, since an out-of-range count is
undefined in C.
"""
import pytest
from hypothesis import assume, given, settings
from hypothesis import strategies as st
from tests.property.cints import (
ALL_TYPES,
ARITH_OPS,
COMPARE_OPS,
DIV_OPS,
SHIFT_OPS,
promote,
)
from tests.property.harness import CLANG, check_against_clang
from tests.property.known_gaps import gap_of
from tests.property.programs import Bin, ExpressionProgram, Var, values_of
pytestmark = pytest.mark.skipif(CLANG is None, reason="clang is not installed")
TYPES = st.sampled_from(ALL_TYPES)
# Parametrized over the left operand's type as well as the operator, so every
# type gets examples on every run (153 parameters, a sixteenth of the
# profile's examples each).
@pytest.mark.parametrize("left_ty", ALL_TYPES, ids=lambda t: t.name)
@pytest.mark.parametrize("op", ARITH_OPS + DIV_OPS + SHIFT_OPS + COMPARE_OPS)
@settings(max_examples=max(5, settings.default.max_examples // 16))
@given(right_ty=TYPES, data=st.data())
def test_binary_operator_matches_clang(op, left_ty, right_ty, data):
left = data.draw(values_of(left_ty), label="left")
if op in SHIFT_OPS:
count = st.integers(0, min(promote(left_ty).bits - 1, right_ty.max))
right = data.draw(count, label="right")
else:
right = data.draw(values_of(right_ty), label="right")
program = ExpressionProgram(
[("a0", left_ty, left), ("a1", right_ty, right)],
[],
Bin(op, Var("a0", left_ty), Var("a1", right_ty)),
)
assume(gap_of(program) is None)
check_against_clang(program.program(), program.expected)

View File

@ -0,0 +1,64 @@
"""
Each known gap's smallest program, as a strict xfail: when a fix lands it
XPASSes and fails the run, as a reminder to delete the gap from
tests/property/known_gaps.py so the properties cover that ground again.
"""
import pytest
from tests.property.cints import C_BOOL, C_INT64, convert
from tests.property.harness import CLANG, check_against_clang
from tests.property.known_gaps import GAPS
from tests.property.programs import Program
pytestmark = pytest.mark.skipif(CLANG is None, reason="clang is not installed")
@pytest.mark.parametrize(
"gap",
[
pytest.param(
g,
id=g.name,
marks=pytest.mark.xfail(
strict=True, raises=AssertionError, reason=g.reason
),
)
for g in GAPS
],
)
def test_known_gap_still_diverges(gap):
assert gap.hits(gap.example), "the pinned program must hit its own gap"
check_against_clang(gap.example.program(), gap.example.expected)
@pytest.mark.xfail(
strict=True,
raises=AssertionError,
reason="shift-result-type, in augmented assignment: `x >>= a` with x a "
"c_int32 and a a c_uint32 shifts logically in u32; C shifts x's own int",
)
def test_known_gap_augassign_shift():
program = Program(
["a0 = c_uint32(1)", "x = c_int32(-2147483648)", "x >>= a0", "return x"],
["unsigned int a0 = 1;", "int x = -2147483648;", "x >>= a0;", "return x;"],
)
check_against_clang(program, lambda: convert(-(2**31) >> 1, C_INT64))
GLOBAL_INIT_REASON = (
"global-initialiser: a @bpfglobal initialiser that is not a bare constant "
"(c_int64(-5) is not: -5 is a UnaryOp) is emitted as 0, and a constant is "
"not converted to the type, so c_bool(2) keeps the low bit, 0, where C "
"gives 1 (pythonbpf/globals_pass.py, _emit_global). "
"test_int_conversions' global_init site steps around both."
)
@pytest.mark.xfail(strict=True, raises=AssertionError, reason=GLOBAL_INIT_REASON)
@pytest.mark.parametrize(
"ty, literal", [(C_INT64, -5), (C_BOOL, 2)], ids=["negative", "c_bool"]
)
def test_known_gap_global_initialiser(ty, literal):
program = Program(["return g"], ["return g;"], globals=[("g", ty, literal)])
check_against_clang(program, lambda: convert(convert(literal, ty), C_INT64))

View File

@ -15,18 +15,19 @@
[xfail]
"failing_tests/conditionals/struct_ptr.py" = {reason = "Struct pointer used directly as boolean condition not supported", level = "ir"}
"failing_tests/conditionals/struct_value.py" = {reason = "A struct value has no truth value (C rejects `if (s)`): a compile error naming the struct", level = "ir"}
"failing_tests/conditionals/oneline.py" = {reason = "A conditional expression used as a statement (`f() if c else g()`) is not lowered: a compile error rather than silently dropping both calls; write it as an if statement", level = "ir"}
"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"}
"failing_tests/vmlinux/args_test.py" = {reason = "struct_trace_event_raw_sys_enter args field access not supported", level = "ir"}
"failing_tests/vmlinux/xdp_pass.py" = {reason = "XDP program using vmlinux structs (struct_xdp_md) and complex map/struct interaction not yet supported", level = "ir"}
"failing_tests/globals_read_before_shadow.py" = {reason = "Reading a name above the assignment that makes it a local shadowing a global is UnboundLocalError in Python, and a compile error here", level = "ir"}
@ -38,31 +39,13 @@
"failing_tests/globals_parameter_and_global.py" = {reason = "A parameter may not be declared global (Python: name is parameter and global)", level = "ir"}
"failing_tests/assign/annotated_assign.py" = {reason = "Annotated assignment (ast.AnnAssign, e.g. `x: c_int64 = 0`) is not handled by process_stmt", level = "ir"}
"failing_tests/loops/for_map_items.py" = {reason = "Loops iterate range() only: no sugar over bpf_for_each_map_elem() (a callback subprogram plus a way to capture outer locals) exists yet", level = "ir"}
# Loop constructs: ast.For/ast.While are not handled by the statement dispatcher
# (pythonbpf/functions/functions_pass.py process_stmt only matches Expr, Assign,
# AugAssign, If, Return) and the pre-pass variable scan does not descend into
# loop bodies. A loop is silently skipped rather than erroring, so anything
# that reads a variable assigned in/around the loop afterward blows up later
# with "Undefined variable ..." at the `return` statement. These document the
# intended surface for when loops are implemented.
"failing_tests/loops/for_range_sum.py" = {reason = "for/while loops not implemented: ast.For is silently skipped by the statement dispatcher", level = "ir"}
"failing_tests/loops/break_outside_loop.py" = {reason = "`break` outside a loop is a SyntaxError in Python, and a compile error here", level = "ir"}
"failing_tests/loops/for_range_start_stop_step.py" = {reason = "for/while loops not implemented: range() with start/stop/step is not supported", level = "ir"}
"failing_tests/loops/while_basic.py" = {reason = "for/while loops not implemented: ast.While is silently skipped by the statement dispatcher", level = "ir"}
"failing_tests/loops/while_true_break.py" = {reason = "for/while loops not implemented: while True with a break-based exit is not supported", level = "ir"}
"failing_tests/loops/nested_for.py" = {reason = "for/while loops not implemented: nested for loops are not supported", level = "ir"}
"failing_tests/loops/for_break.py" = {reason = "for/while loops not implemented: break is not supported", level = "ir"}
"failing_tests/loops/for_continue.py" = {reason = "for/while loops not implemented: continue is not supported", level = "ir"}
"failing_tests/loops/for_map_items.py" = {reason = "for/while loops not implemented: no sugar over bpf_for_each_map_elem()-style map iteration exists yet", level = "ir"}
"failing_tests/loops/range_variable_step.py" = {reason = "range() step must be an integer literal: its sign decides the loop test", level = "ir"}
"failing_tests/loops/range_step_too_wide.py" = {reason = "range() step must fit the 64-bit counter: 2**64 truncates to 0 and never terminates", level = "ir"}
"kernel_selftest_equivalent/ringbuf/reserve_submit_discard.py" = {reason = "RingBuffer reserve/typed record/discard workflow is planned but not implemented yet", 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

71
tests/test_loops_run.py Normal file
View File

@ -0,0 +1,71 @@
"""
Loops: what they compute.
Levels 1 and 2 only prove the passing_tests/loops cases compile. A loop that
compiles can still run the wrong number of times, or forever, so this test
JIT-compiles each helper-free case on the host and checks the value it returns
against what CPython returns for the same function body. Every expected value
below was checked that way.
"""
import subprocess
from pathlib import Path
import pytest
from tests.framework.compiler import run_ir_generation
from tests.framework.host_jit import run_in_subprocess
LOOPS_DIR = Path(__file__).parent / "passing_tests" / "loops"
# file -> return value of hello(ctx) under CPython
CASES = {
"for_break.py": 5,
"for_continue.py": 25,
"for_range_start_stop_step.py": 20,
"for_range_sum.py": 10,
"loop_else.py": 104,
"nested_for.py": 9,
"range_negative_step.py": 22,
"rebind_loop_var.py": 10,
"while_basic.py": 10,
"while_true_break.py": 10,
"pass_body.py": 3,
"while_true_return_i32.py": 6,
"range_step_overflow_signed.py": 22,
"range_step_overflow_unsigned.py": 1,
"range_u32_stop_negative_start.py": 4,
"reuse_loop_var_signedness.py": 303,
"loop_var_shared.py": 60,
}
# file -> why it returns something else today (strict: a fix shows as XPASS)
XFAIL = {
# Every local gets one slot typed by its first binding, so the second
# loop's `i` is unsigned and `i < 0` never holds. Not a loop bug:
# `x = n_u64; x = -3` does the same, so the fix is general (one variable
# per web of reaching definitions), not anything loop-specific.
"reuse_loop_var_signedness.py": "one slot per name, typed by its first binding",
}
@pytest.mark.parametrize(
"name",
[
pytest.param(name, marks=pytest.mark.xfail(reason=XFAIL[name], strict=True))
if name in XFAIL
else name
for name in CASES
],
)
def test_loop_result(name, tmp_path):
expected = CASES[name]
ll_path = tmp_path / name.replace(".py", ".ll")
run_ir_generation(LOOPS_DIR / name, ll_path)
try:
got = run_in_subprocess(ll_path, "hello", timeout=10)
except subprocess.TimeoutExpired:
pytest.fail(f"{name}: did not terminate (expected to return {expected})")
except subprocess.CalledProcessError as e:
pytest.fail(f"{name}: could not run on the host:\n{e.stderr.strip()}")
assert got == expected, f"{name}: returned {got}, CPython returns {expected}"

View File

@ -19,6 +19,13 @@ from tests.framework.compiler import run_ir_generation
PASSING_DIR = Path(__file__).parent / "passing_tests"
HAVE_VMLINUX = importlib.util.find_spec("vmlinux") is not None
# The value argument of a map update is the very SSA value loaded from prev's
# slot, not merely some load of prev elsewhere in the function.
UPDATE_WITH_LOADED_PREV = (
r'(%"[^"]+") = load i64\*, i64\*\* %"prev"\n(?:.*\n)*?'
r'.*call i64 %"[^"]+"\(\{[^}]*\}\* @"count", i64\* %"[^"]+", i64\* \1, i64 0\)'
)
# path under passing_tests -> (patterns that must appear, patterns that must not)
CASES = {
"signedness/widen_unsigned.py": (
@ -112,6 +119,20 @@ CASES = {
[r"deref_0_not_null", r"ret i64 %"],
[r"ret i64\*"],
),
# A local holding a pointer is passed to a helper as that pointer, loaded
# from its slot; the slot's own address (an i64**) would make the map store
# a kernel address instead of the value. The reference is
# tests/c-form/map_update_from_lookup.bpf.c: at -O0 clang passes
# bpf_map_update_elem the result of `load ptr, ptr <prev's slot>` in both
# copy() and rebind().
"helpers/map_update_from_lookup.py": (
[UPDATE_WITH_LOADED_PREV],
[r'i64\*\* %"prev", i64 0\)'],
),
"vmlinux/named_arg.py": (
[UPDATE_WITH_LOADED_PREV],
[r'i64\*\* %"prev", i64 0\)'],
),
}

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"\?[^?:]*:"),