Compare commits

..

6 Commits

Author SHA1 Message Date
aa612a4151 Core: Let a packet pointer be narrowed on a store, as C does
convert() refused to narrow a packet pointer below 64 bits, on the
premise that the verifier only accepts one at 64 bits. That is true of
arithmetic, not of stores: upstream's cgroup_skb_direct_packet_access
stores skb->data_end into a __u32 global, and CI's verifier level
accepted exactly that on #105. Merging master brought that selftest in
and the refusal rejected it. Narrowing now truncates, and the result is
an ordinary integer. ctx_data_narrow_store.py moves to the passing
tests. Keeping the pointer when a local is declared narrower belongs to
allocation (widest type ever stored), noted for later.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 23:21:12 +05:30
4cb5f01374 Merge origin/master (#105) into fix/packet-pointer-arith
Four keep-both conflicts: PktPtrTy and byte_size added at the same spot
in type_deducer, the allocation pass's type_deducer import, and
neighbouring entries in test_config.toml and test_signedness_ir.py.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 23:09:31 +05:30
db894087a2 Tests: Packet pointers through locals, bounds checks, data_meta, and the refusals
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 13:03:32 +05:30
b9b582a7d8 Core: Carry the packet-pointer kind on the type descriptor
The previous commit recognised a packet-pointer field only where it was
read directly in a binary operation, so d = ctx.data made d an ordinary
integer again and comparisons such as data + 34 > data_end were still
ranked u32 and emitted as 32-bit compares, which the verifier rejects.

PktPtrTy is a 64-bit unsigned IntTy tagged with the verifier's kind
(pkt, pkt_meta, pkt_end). It originates at the field read and travels
as the descriptor does: into a local's slot, through pointer +/- offset
(which yields the same kind), and into comparisons, which compare at
64 bits unsigned whenever either side is a packet pointer. It is handled
before the usual arithmetic conversions, which would re-rank it.

Two rules the verifier enforces become compile errors: a packet-end
pointer takes no offset, and convert() refuses to narrow a packet
pointer below 64 bits.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 13:03:30 +05:30
6a859ac0cd Core: Special-case packet-pointer context fields in arithmetic
xdp_md.data/data_end/data_meta and __sk_buff.data/data_end/data_meta are
u32 in C but packet pointers to the verifier, which rewrites their load
into a pointer load and prohibits 32-bit arithmetic on them. The
signedness rules ranked them as u32, so ctx.data - k lowered to a 32-bit
add (w0 += -1) and was rejected; C code avoids this with a cast through
(void *)(long).

A binary operation with a packet-pointer operand now bypasses the usual
arithmetic conversions: the pointer is used at 64 bits, an offset added
to or subtracted from it is taken as an unsigned 16-bit value (truncated,
zero-extended) because the verifier only tracks packet ranges up to
MAX_PACKET_OFF (0xffff), and the result is a 64-bit value. Pointer minus
pointer is an ordinary 64-bit length. A constant offset outside
0..65535, any other operator, and offset minus pointer are compile
errors rather than code the verifier would reject. Local inference
agrees (64-bit unsigned).

Only direct field reads are recognised; a local copied from one is an
integer again, and comparisons between packet pointers are the next site
of the same rule.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 11:58:42 +05:30
fab456b83d Tests: Pin 32-bit arithmetic on xdp_md.data as a verifier-level xfail
xdp_md.data is u32 in C, so ctx.data - k lowers to a 32-bit add on the
loaded value, exactly as C ranks it, and the verifier rejects it: it
tracks data as a packet pointer and prohibits 32-bit pointer arithmetic
(observed in CI). IR and llc succeed, so the entry is at the verifier
level. It flips to passing when packet-pointer fields get 64-bit
pointer rank (TODO in expr_pass._descriptor).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 11:20:13 +05:30
80 changed files with 737 additions and 1737 deletions

View File

@ -1,9 +1,14 @@
<p align="center"> <picture>
<img <source
src="https://raw.githubusercontent.com/pythonbpf/Python-BPF/master/docs/_static/pythonbpf-logo.svg" media="(prefers-color-scheme: light)"
srcset="https://github.com/user-attachments/assets/f3738131-d7cb-4b5c-8699-c7010295a159"
width="450" width="450"
alt="PythonBPF logo"> alt="Light‐mode image">
</p> <img
src="https://github.com/user-attachments/assets/b175bf39-23cb-475d-a6e1-7b5c99a1ed72"
width="450"
alt="Dark‐mode image">
</picture>
<!-- Badges --> <!-- Badges -->
<p align="center"> <p align="center">
<!-- PyPI --> <!-- PyPI -->

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 408 KiB

View File

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

View File

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

View File

@ -281,10 +281,9 @@ BPF global variables are values that:
### Common Global Variables ### Common Global Variables
#### LICENSE #### LICENSE (Required)
Every BPF program carries a license, which the kernel reads when the program is Every BPF program must declare a license:
loaded. Declare it as a string global:
```python ```python
@bpf @bpf
@ -293,24 +292,14 @@ def LICENSE() -> str:
return "GPL" return "GPL"
``` ```
If a program defines no `LICENSE`, PythonBPF uses `"GPL"`, the kernel's own Valid licenses include:
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"` - GNU General Public License
* `"GPL v2"` - GPL version 2 * `"GPL v2"` - GPL version 2
* `"GPL and additional rights"`
* `"Dual BSD/GPL"` - Dual licensed * `"Dual BSD/GPL"` - Dual licensed
* `"Dual MIT/GPL"` - Dual licensed * `"Dual MIT/GPL"` - Dual licensed
* `"Dual MPL/GPL"` - Dual licensed
```{warning} ```{warning}
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". Many BPF features require a GPL-compatible license. Using a non-GPL license may prevent your program from loading or accessing certain kernel features.
``` ```
#### Custom Global Variables #### Custom Global Variables

View File

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

View File

@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "pythonbpf" name = "pythonbpf"
version = "0.2.0" version = "0.1.9"
description = "Reduced Python frontend for eBPF" description = "Reduced Python frontend for eBPF"
authors = [ authors = [
{ name = "r41k0u", email="pragyanshchaturvedi18@gmail.com" }, { name = "r41k0u", email="pragyanshchaturvedi18@gmail.com" },

View File

@ -6,9 +6,16 @@ from .symbols import LocalSymbol
from pythonbpf.helper import HelperHandlerRegistry from pythonbpf.helper import HelperHandlerRegistry
from pythonbpf.vmlinux_parser.dependency_node import Field from pythonbpf.vmlinux_parser.dependency_node import Field
from .expr import VmlinuxHandlerRegistry from .expr import VmlinuxHandlerRegistry
from pythonbpf.type_deducer import ctypes_to_ir, is_ctypes, IntTy, signedness, byte_size from pythonbpf.type_deducer import (
ctypes_to_ir,
is_ctypes,
IntTy,
signedness,
byte_size,
PktPtrTy,
)
from pythonbpf.expr.packet_pointer import packet_type
from pythonbpf.expr.type_inference import infer_int_type from pythonbpf.expr.type_inference import infer_int_type
from pythonbpf.expr.operators import usual_arithmetic_conversions
from pythonbpf.maps import BPFMapType from pythonbpf.maps import BPFMapType
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -50,231 +57,57 @@ def handle_assign_allocation(compilation_context, builder, stmt, local_sym_tab):
) )
continue continue
_bind_name( var_name = target.id
compilation_context,
stmt, # Already bound in this scope: a parameter, an earlier assignment, or a
target, # `global` declaration (whose slot is the GlobalVariable). No slot needed.
local_sym_tab, if var_name in local_sym_tab:
lambda var_name: _allocate_for_value( 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(
builder, var_name, rval, local_sym_tab, compilation_context 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:
def handle_ann_assign_allocation(compilation_context, builder, stmt, local_sym_tab): # Where the binding ends, so that a read above it is reported the
"""Handle memory allocation for annotated assignment (`x: c_int32 = 0`). # 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.
The annotation, not the value, types the slot: `x: c_int32 = 0` is an i32 local_sym_tab[var_name].shadows_global_from = (
even though the literal alone would give an i64. With no value getattr(stmt, "end_lineno", None) or target.lineno
(`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): def _allocate_for_call(builder, var_name, rval, local_sym_tab, compilation_context):
@ -476,7 +309,10 @@ def _allocate_for_binop(builder, var_name, rval, local_sym_tab, compilation_cont
inferred = infer_int_type(rval, local_sym_tab, compilation_context) inferred = infer_int_type(rval, local_sym_tab, compilation_context)
if inferred is None: if inferred is None:
logger.debug(f"Could not infer a type for {var_name}, assuming signed i64") logger.debug(f"Could not infer a type for {var_name}, assuming signed i64")
ir_type = IntTy(64, signedness(inferred) if inferred is not None else True) if isinstance(inferred, PktPtrTy):
ir_type = inferred # data + 14 is still a packet pointer
else:
ir_type = IntTy(64, signedness(inferred) if inferred is not None else True)
var = builder.alloca(ir_type, name=var_name) var = builder.alloca(ir_type, name=var_name)
var.align = 8 var.align = 8
local_sym_tab[var_name] = LocalSymbol(var, ir_type) local_sym_tab[var_name] = LocalSymbol(var, ir_type)
@ -576,6 +412,13 @@ def _allocate_for_attribute(
# Same discriminator handle_vmlinux_struct_field uses: a context # Same discriminator handle_vmlinux_struct_field uses: a context
# argument has no alloca of its own. # argument has no alloca of its own.
is_context_field = local_sym_tab[struct_var].var is None is_context_field = local_sym_tab[struct_var].var is None
pkt_ty = packet_type(rval, local_sym_tab)
if pkt_ty is not None:
# A packet-pointer field: a 64-bit slot that carries the kind.
var = _allocate_with_type(builder, var_name, pkt_ty)
local_sym_tab[var_name] = LocalSymbol(var, pkt_ty)
logger.info(f"Pre-allocated {var_name} as {pkt_ty.describe()}")
return
if not VmlinuxHandlerRegistry.has_field(vmlinux_struct_name, field_name): if not VmlinuxHandlerRegistry.has_field(vmlinux_struct_name, field_name):
logger.error( logger.error(
f"Field '{field_name}' not found in vmlinux struct '{vmlinux_struct_name}'" f"Field '{field_name}' not found in vmlinux struct '{vmlinux_struct_name}'"

View File

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

View File

@ -82,12 +82,7 @@ class CompilationContext:
# Current function context (optional, if needed globally during function processing) # Current function context (optional, if needed globally during function processing)
self.current_func = None 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): def reset(self):
"""Reset state between functions if necessary, though new context per compile is preferred.""" """Reset state between functions if necessary, though new context per compile is preferred."""
self.scratch_pool.reset() self.scratch_pool.reset()
self.current_func = None self.current_func = None
self.loop_stack = []

View File

@ -9,6 +9,7 @@ from pythonbpf.type_deducer import (
field_int_type, field_int_type,
is_ctypes, is_ctypes,
IntTy, IntTy,
PktPtrTy,
int_literal_type, int_literal_type,
signedness, signedness,
) )
@ -24,6 +25,7 @@ from .type_normalization import (
get_base_type_and_depth, get_base_type_and_depth,
) )
from .vmlinux_registry import VmlinuxHandlerRegistry from .vmlinux_registry import VmlinuxHandlerRegistry
from .packet_pointer import MAX_PACKET_OFF, packet_type
from ..vmlinux_parser.dependency_node import Field from ..vmlinux_parser.dependency_node import Field
logger: Logger = logging.getLogger(__name__) logger: Logger = logging.getLogger(__name__)
@ -122,6 +124,11 @@ def _handle_attribute_expr(
expr, local_sym_tab, None, builder expr, local_sym_tab, None, builder
) )
if vmlinux_result is not None: if vmlinux_result is not None:
pkt_ty = packet_type(expr, local_sym_tab)
if pkt_ty is not None:
# A packet-pointer field: the value is the loaded
# pointer, and the descriptor says so from here on.
return vmlinux_result[0], pkt_ty
return vmlinux_result return vmlinux_result
else: else:
raise RuntimeError("Vmlinux struct did not process successfully") raise RuntimeError("Vmlinux struct did not process successfully")
@ -199,6 +206,8 @@ def _descriptor(val, ty):
value unless the descriptor is itself an integer type, sign from the value unless the descriptor is itself an integer type, sign from the
descriptor (an IntTy, a vmlinux Field, or plain -> signed). None when the descriptor (an IntTy, a vmlinux Field, or plain -> signed). None when the
value is not an integer at all.""" value is not an integer at all."""
if isinstance(ty, PktPtrTy):
return ty # a packet pointer keeps its kind, never re-ranked
if isinstance(ty, ir.IntType): if isinstance(ty, ir.IntType):
return IntTy(ty.width, signedness(ty)) return IntTy(ty.width, signedness(ty))
field = field_int_type(ty) field = field_int_type(ty)
@ -291,6 +300,10 @@ def _handle_binary_op_impl(func, compilation_context, rval, builder, local_sym_t
right, right_ty = get_typed_operand( right, right_ty = get_typed_operand(
func, compilation_context, rval.right, builder, local_sym_tab func, compilation_context, rval.right, builder, local_sym_tab
) )
if isinstance(left_ty, PktPtrTy) or isinstance(right_ty, PktPtrTy):
# Before the usual arithmetic conversions, which would re-rank the
# pointer as an ordinary integer and drop its kind.
return _packet_pointer_binop(builder, rval, left, left_ty, right, right_ty)
result_ty = usual_arithmetic_conversions(left_ty, right_ty) result_ty = usual_arithmetic_conversions(left_ty, right_ty)
logger.info( logger.info(
f"binop {type(op).__name__}: {left_ty.describe()} x {right_ty.describe()} " f"binop {type(op).__name__}: {left_ty.describe()} x {right_ty.describe()} "
@ -302,6 +315,50 @@ def _handle_binary_op_impl(func, compilation_context, rval, builder, local_sym_t
return canonicalise(builder, result, result_ty), result_ty return canonicalise(builder, result, result_ty), result_ty
def _packet_pointer_binop(builder, rval, left, left_ty, right, right_ty):
"""A binary operation with a packet-pointer operand (see packet_pointer.py):
64-bit, never ranked as an ordinary integer, with the offset taken as an
unsigned 16-bit value so the verifier can track the packet range. The
result of pointer +/- offset is a pointer of the same kind; pointer -
pointer is a plain 64-bit length."""
op = rval.op
where = f"line {rval.lineno}: {ast.unparse(rval)}"
left_pkt = isinstance(left_ty, PktPtrTy)
right_pkt = isinstance(right_ty, PktPtrTy)
if left_pkt and right_pkt:
if isinstance(op, ast.Sub):
# data_end - data: a length, an ordinary 64-bit scalar.
return builder.sub(left, right), IntTy(64, False)
raise SyntaxError(
f"only subtraction is defined between packet pointers ({where})"
)
if not isinstance(op, (ast.Add, ast.Sub)):
raise SyntaxError(
f"only + and - with an offset are allowed on a packet pointer ({where})"
)
if right_pkt and isinstance(op, ast.Sub):
raise SyntaxError(f"cannot subtract a packet pointer from an offset ({where})")
ptr, ptr_ty, off = (left, left_ty, right) if left_pkt else (right, right_ty, left)
if ptr_ty.kind == "pkt_end":
# The verifier only compares against the end of the packet.
raise SyntaxError(
f"a packet-end pointer can only be compared, not offset ({where})"
)
if isinstance(off, ir.Constant) and isinstance(off.constant, int):
if not 0 <= off.constant <= MAX_PACKET_OFF:
raise SyntaxError(
f"packet offset {off.constant} is outside 0..{MAX_PACKET_OFF} "
f"({where}); subtract instead of adding a negative offset"
)
# The offset as u16, widened with zero-extension: a value the verifier can
# bound to [0, 0xffff].
off = builder.trunc(off, ir.IntType(16)) if off.type.width > 16 else off
off = builder.zext(off, ir.IntType(64)) if off.type.width < 64 else off
result = builder.add(ptr, off) if isinstance(op, ast.Add) else builder.sub(ptr, off)
return result, PktPtrTy(ptr_ty.kind)
def _handle_binary_op( def _handle_binary_op(
func, func,
compilation_context, compilation_context,
@ -411,6 +468,13 @@ def _handle_compare(func, compilation_context, builder, cond, local_sym_tab):
lhs, lhs_ty = lhs lhs, lhs_ty = lhs
rhs, rhs_ty = rhs rhs, rhs_ty = rhs
lhs_desc, rhs_desc = _descriptor(lhs, lhs_ty), _descriptor(rhs, rhs_ty) lhs_desc, rhs_desc = _descriptor(lhs, lhs_ty), _descriptor(rhs, rhs_ty)
if isinstance(lhs_desc, PktPtrTy) or isinstance(rhs_desc, PktPtrTy):
# A packet bounds check (data + n > data_end): the verifier accepts
# pointer comparisons only at 64 bits, and they are unsigned.
u64 = IntTy(64, False)
lhs = convert(builder, lhs, lhs_desc, u64)
rhs = convert(builder, rhs, rhs_desc, u64)
return handle_comparator(func, builder, cond.ops[0], lhs, rhs, signed=False)
if lhs_desc is not None and rhs_desc is not None: if lhs_desc is not None and rhs_desc is not None:
# Both integers: compare in the promoted type, which also picks the # Both integers: compare in the promoted type, which also picks the
# signed or unsigned predicate (u64 > s64 is an unsigned compare in C). # signed or unsigned predicate (u64 > s64 is an unsigned compare in C).
@ -842,13 +906,5 @@ def handle_expr(
call, call,
local_sym_tab, 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: else:
logger.debug(f"Dropping expression statement without effect: {ast.dump(call)}") logger.info("Unsupported expression type")

View File

@ -0,0 +1,68 @@
"""Packet-pointer context fields.
A few context fields are declared u32 in C but are packet pointers to the
verifier: it rewrites the context load into a 64-bit pointer load. C's
integer rules (which rank them as u32) therefore produce code the verifier
rejects ("32-bit pointer arithmetic prohibited"); C programs dodge that by
casting through (void *)(long). The compiler special-cases them instead, so
users never need the cast:
- the field is used at 64 bits, as the pointer it is;
- an offset added to or subtracted from it is taken as an unsigned 16-bit
value (truncated, then zero-extended), because the verifier only tracks a
packet range whose offset stays within MAX_PACKET_OFF (0xffff);
- pointer - pointer (e.g. data_end - data) is an ordinary 64-bit length.
The field read gives its value a PktPtrTy descriptor (a 64-bit unsigned
IntTy tagged with the verifier's kind), and the rules key on that descriptor,
so they follow the pointer through locals (`d = ctx.data`), through
`d + 14`, and into comparisons (`ctx.data + 34 > ctx.data_end` is a 64-bit
unsigned compare). packet-end pointers take no offset at all.
Storing a packet pointer into a narrower slot truncates it, as C does, and the
result is an ordinary integer: the verifier forbids 32-bit *arithmetic* on a
packet pointer, not a 32-bit store of one (upstream's
cgroup_skb_direct_packet_access stores data_end into a __u32 global). Keeping
the pointer when a local is declared narrower is a job for allocation, which
could give such a slot the widest type ever stored into it.
"""
import ast
from pythonbpf.type_deducer import PktPtrTy
# Context struct -> {field: packet kind}. Taken from the verifier's
# is_valid_access callbacks, restricted to the fields vmlinux declares as
# 32-bit integers.
PACKET_POINTER_FIELDS = {
"struct_xdp_md": {"data": "pkt", "data_meta": "pkt_meta", "data_end": "pkt_end"},
"struct___sk_buff": {
"data": "pkt",
"data_meta": "pkt_meta",
"data_end": "pkt_end",
},
}
MAX_PACKET_OFF = 0xFFFF
def packet_kind(expr, local_sym_tab) -> "str | None":
"""The packet kind of `ctx.<field>` when ctx is a context parameter of one
of the structs above and the field is one of its packet-pointer fields;
None otherwise. This is the only place a PktPtrTy originates: from here it
travels as a descriptor, through locals, binop results and comparisons."""
if not (isinstance(expr, ast.Attribute) and isinstance(expr.value, ast.Name)):
return None
sym = (local_sym_tab or {}).get(expr.value.id)
if sym is None:
return None
meta = sym.metadata
struct_name = meta if isinstance(meta, str) else getattr(meta, "__name__", None)
if not isinstance(struct_name, str):
return None
return PACKET_POINTER_FIELDS.get(struct_name, {}).get(expr.attr)
def packet_type(expr, local_sym_tab) -> "PktPtrTy | None":
kind = packet_kind(expr, local_sym_tab)
return PktPtrTy(kind) if kind is not None else None

View File

@ -13,6 +13,7 @@ import ctypes
from llvmlite import ir from llvmlite import ir
from pythonbpf.type_deducer import ( from pythonbpf.type_deducer import (
PktPtrTy,
IntTy, IntTy,
ctypes_to_ir, ctypes_to_ir,
is_ctypes, is_ctypes,
@ -21,9 +22,12 @@ from pythonbpf.type_deducer import (
) )
from .operators import usual_arithmetic_conversions from .operators import usual_arithmetic_conversions
from .vmlinux_registry import VmlinuxHandlerRegistry from .vmlinux_registry import VmlinuxHandlerRegistry
from .packet_pointer import packet_type
def _as_intty(ty): def _as_intty(ty):
if isinstance(ty, PktPtrTy):
return ty
if isinstance(ty, ir.IntType): if isinstance(ty, ir.IntType):
return IntTy(ty.width, signedness(ty)) return IntTy(ty.width, signedness(ty))
return None return None
@ -48,6 +52,10 @@ def infer_int_type(expr, local_sym_tab, compilation_context):
if isinstance(expr, ast.BinOp): if isinstance(expr, ast.BinOp):
left = infer_int_type(expr.left, local_sym_tab, compilation_context) left = infer_int_type(expr.left, local_sym_tab, compilation_context)
right = infer_int_type(expr.right, local_sym_tab, compilation_context) right = infer_int_type(expr.right, local_sym_tab, compilation_context)
if isinstance(left, PktPtrTy) and isinstance(right, PktPtrTy):
return IntTy(64, False) # pointer - pointer: a length
if isinstance(left, PktPtrTy) or isinstance(right, PktPtrTy):
return left if isinstance(left, PktPtrTy) else right
if left is None or right is None: if left is None or right is None:
return None return None
return usual_arithmetic_conversions(left, right) return usual_arithmetic_conversions(left, right)
@ -83,6 +91,9 @@ def infer_int_type(expr, local_sym_tab, compilation_context):
return None return None
if isinstance(expr, ast.Attribute) and isinstance(expr.value, ast.Name): if isinstance(expr, ast.Attribute) and isinstance(expr.value, ast.Name):
pkt_ty = packet_type(expr, local_sym_tab)
if pkt_ty is not None:
return pkt_ty
base = local_sym_tab.get(expr.value.id) base = local_sym_tab.get(expr.value.id)
if base is None: if base is None:
return None return None

View File

@ -113,14 +113,6 @@ def convert_to_bool(builder, val):
"""Convert a value to boolean.""" """Convert a value to boolean."""
if val.type == ir.IntType(1): if val.type == ir.IntType(1):
return val 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): if isinstance(val.type, ir.PointerType):
zero = ir.Constant(val.type, None) zero = ir.Constant(val.type, None)
else: else:

View File

@ -25,10 +25,6 @@ from pythonbpf.assign_pass import (
) )
from pythonbpf.allocation_pass import ( from pythonbpf.allocation_pass import (
handle_assign_allocation, handle_assign_allocation,
handle_ann_assign_allocation,
handle_for_allocation,
parse_range,
range_counter_name,
allocate_temp_pool, allocate_temp_pool,
create_targets_and_rvals, create_targets_and_rvals,
LocalSymbol, LocalSymbol,
@ -85,11 +81,10 @@ def count_temps_in_call(call_node, local_sym_tab):
return count return count
def handle_block_allocation( def handle_if_allocation(
compilation_context, builder, stmt, func, ret_type, local_sym_tab compilation_context, builder, stmt, func, ret_type, local_sym_tab
): ):
"""Recursively handle allocations in the body and else-branch of an """Recursively handle allocations in if/else branches."""
if, for or while statement."""
if stmt.body: if stmt.body:
allocate_mem( allocate_mem(
compilation_context, compilation_context,
@ -121,23 +116,15 @@ def allocate_mem(compilation_context, builder, body, func, ret_type, local_sym_t
def update_max_temps_for_stmt(stmt): def update_max_temps_for_stmt(stmt):
nonlocal max_temps_needed nonlocal max_temps_needed
if isinstance(stmt, (ast.If, ast.For, ast.While)): if isinstance(stmt, ast.If):
# 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: for s in stmt.body:
update_max_temps_for_stmt(s) update_max_temps_for_stmt(s)
for s in stmt.orelse: for s in stmt.orelse:
update_max_temps_for_stmt(s) update_max_temps_for_stmt(s)
return return
count_temps_in_tree(stmt)
def count_temps_in_tree(tree):
stmt_temps = {} stmt_temps = {}
for node in ast.walk(tree): for node in ast.walk(stmt):
if isinstance(node, ast.Call): if isinstance(node, ast.Call):
call_temps = count_temps_in_call(node, local_sym_tab) call_temps = count_temps_in_call(node, local_sym_tab)
for typ, cnt in call_temps.items(): for typ, cnt in call_temps.items():
@ -148,10 +135,8 @@ def allocate_mem(compilation_context, builder, body, func, ret_type, local_sym_t
update_max_temps_for_stmt(stmt) update_max_temps_for_stmt(stmt)
# Handle allocations # Handle allocations
if isinstance(stmt, ast.For): if isinstance(stmt, ast.If):
handle_for_allocation(compilation_context, builder, stmt, local_sym_tab) handle_if_allocation(
if isinstance(stmt, (ast.If, ast.For, ast.While)):
handle_block_allocation(
compilation_context, compilation_context,
builder, builder,
stmt, stmt,
@ -161,10 +146,6 @@ def allocate_mem(compilation_context, builder, body, func, ret_type, local_sym_t
) )
elif isinstance(stmt, ast.Assign): elif isinstance(stmt, ast.Assign):
handle_assign_allocation(compilation_context, builder, stmt, local_sym_tab) 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) allocate_temp_pool(builder, max_temps_needed, local_sym_tab)
@ -214,24 +195,6 @@ def handle_assign(func, compilation_context, builder, stmt, local_sym_tab):
logger.error(f"Unsupported assignment target: {ast.dump(target)}") 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): def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab):
"""Handle `x += v` and friends by direct lowering: resolve the target's """Handle `x += v` and friends by direct lowering: resolve the target's
slot, load it, apply the operator, store back. slot, load it, apply the operator, store back.
@ -332,7 +295,7 @@ def handle_cond(func, compilation_context, builder, cond, local_sym_tab):
return convert_to_bool(builder, val) return convert_to_bool(builder, val)
def handle_if(func, compilation_context, builder, stmt, local_sym_tab, ret_type): def handle_if(func, compilation_context, builder, stmt, local_sym_tab):
"""Handle if statements in the function body.""" """Handle if statements in the function body."""
logger.info("Handling if statement") logger.info("Handling if statement")
# start = builder.block.parent # start = builder.block.parent
@ -350,197 +313,28 @@ def handle_if(func, compilation_context, builder, stmt, local_sym_tab, ret_type)
builder.cbranch(cond, then_block, merge_block) builder.cbranch(cond, then_block, merge_block)
builder.position_at_end(then_block) builder.position_at_end(then_block)
process_block( for s in stmt.body:
func, compilation_context, builder, stmt.body, local_sym_tab, ret_type process_stmt(func, compilation_context, builder, s, local_sym_tab, False)
)
if not builder.block.is_terminated: if not builder.block.is_terminated:
builder.branch(merge_block) builder.branch(merge_block)
if else_block: if else_block:
builder.position_at_end(else_block) builder.position_at_end(else_block)
process_block( for s in stmt.orelse:
func, compilation_context, builder, stmt.orelse, local_sym_tab, ret_type process_stmt(
) func,
compilation_context,
builder,
s,
local_sym_tab,
False,
)
if not builder.block.is_terminated: if not builder.block.is_terminated:
builder.branch(merge_block) builder.branch(merge_block)
builder.position_at_end(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( def handle_return(
func, builder, stmt, local_sym_tab, ret_type, compilation_context=None func, builder, stmt, local_sym_tab, ret_type, compilation_context=None
): ):
@ -589,22 +383,12 @@ def process_stmt(
) )
elif isinstance(stmt, ast.Assign): elif isinstance(stmt, ast.Assign):
handle_assign(func, compilation_context, builder, stmt, local_sym_tab) 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): elif isinstance(stmt, ast.AugAssign):
handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab) handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab)
elif isinstance(stmt, ast.Global): elif isinstance(stmt, ast.Global):
logger.debug(f"global declaration of {', '.join(stmt.names)} already bound") logger.debug(f"global declaration of {', '.join(stmt.names)} already bound")
elif isinstance(stmt, ast.If): elif isinstance(stmt, ast.If):
handle_if(func, compilation_context, builder, stmt, local_sym_tab, ret_type) handle_if(func, compilation_context, builder, stmt, local_sym_tab)
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): elif isinstance(stmt, ast.Return):
did_return = handle_return( did_return = handle_return(
func, builder, stmt, local_sym_tab, ret_type, compilation_context func, builder, stmt, local_sym_tab, ret_type, compilation_context
@ -619,19 +403,6 @@ def process_stmt(
return did_return 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 # SECTION 3: Function Body Processing
# ============================================================================ # ============================================================================
@ -744,11 +515,7 @@ def process_func_body(
) )
if not did_return: if not did_return:
# Falling off the end returns 0, in the function's own return type: builder.ret(ir.Constant(ir.IntType(64), 0))
# 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): def process_bpf_chunk(func_node, compilation_context, return_type):

View File

@ -67,11 +67,6 @@ def get_or_create_ptr_from_arg(
else: else:
# Stack space is already allocated # Stack space is already allocated
ptr = get_var_ptr_from_name(arg.id, local_sym_tab) 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): elif isinstance(arg, ast.Constant) and isinstance(arg.value, int):
int_width = 64 # Default to i64 int_width = 64 # Default to i64
if expected_type and isinstance(expected_type, ir.IntType): if expected_type and isinstance(expected_type, ir.IntType):

View File

@ -5,11 +5,6 @@ import logging
logger: Logger = logging.getLogger(__name__) 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): def emit_license(module: ir.Module, license_str: str):
license_bytes = license_str.encode("utf8") + b"\x00" license_bytes = license_str.encode("utf8") + b"\x00"
@ -29,10 +24,7 @@ def emit_license(module: ir.Module, license_str: str):
def license_processing(tree, compilation_context): 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 count = 0
for node in tree.body: for node in tree.body:
if isinstance(node, ast.FunctionDef) and node.name == "LICENSE": if isinstance(node, ast.FunctionDef) and node.name == "LICENSE":
@ -60,10 +52,4 @@ def license_processing(tree, compilation_context):
) )
else: else:
raise SyntaxError("ERROR: Multiple LICENSE globals defined") 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

@ -41,6 +41,33 @@ class IntTy(ir.IntType):
return f"{'i' if self.signed else 'u'}{self.width}" return f"{'i' if self.signed else 'u'}{self.width}"
PACKET_KINDS = ("pkt", "pkt_meta", "pkt_end")
class PktPtrTy(IntTy):
"""A packet pointer: 64-bit, unsigned, and tagged with the verifier's kind
for it (packet data, packet metadata, or packet end). It is an IntTy so
every integer path accepts it; the few sites that must treat it as a
pointer check isinstance(ty, PktPtrTy) before the integer rules apply.
See pythonbpf/expr/packet_pointer.py for where kinds come from and the
rules applied to them."""
def __new__(cls, kind: str):
return IntTy.__new__(cls, 64, False)
def __init__(self, kind: str):
if kind not in PACKET_KINDS:
raise ValueError(f"unknown packet pointer kind {kind!r}")
IntTy.__init__(self, 64, False)
self.kind = kind
def __getnewargs__(self): # type: ignore[override]
return (self.kind,)
def describe(self) -> str:
return f"{self.kind}*"
def byte_size(ty) -> int: def byte_size(ty) -> int:
"""Bytes an integer type occupies in memory: its width rounded up to whole """Bytes an integer type occupies in memory: its width rounded up to whole
bytes, so a 1-bit bool still takes one byte, as C's _Bool does.""" bytes, so a 1-bit bool still takes one byte, as C's _Bool does."""

View File

@ -1,97 +0,0 @@
/* 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

@ -1,60 +0,0 @@
/* 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

@ -3,9 +3,13 @@ from ctypes import c_void_p, c_int64, c_uint64
from pythonbpf.maps import HashMap from pythonbpf.maps import HashMap
# `x` is first bound to a map lookup (a pointer) and then rebound to an integer, # NOTE: This example tries to reinterpret the variable `x` to a different type.
# as Python allows; the comparison sees the integer. This was once refused # We do not allow this for now, as stack allocations are typed and have to be
# because stack slots are typed, and now works. # 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.
@bpf @bpf

View File

@ -2,8 +2,10 @@ from pythonbpf import bpf, map, section, bpfglobal, compile
from ctypes import c_void_p, c_int64, c_uint64 from ctypes import c_void_p, c_int64, c_uint64
from pythonbpf.maps import HashMap from pythonbpf.maps import HashMap
# A map lookup used directly in a comparison: the value is null-checked and # NOTE: Decided against fixing this
# dereferenced, and a missing key takes the else branch. # 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.
@bpf @bpf

View File

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

View File

@ -0,0 +1,14 @@
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

@ -1,23 +0,0 @@
# 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

@ -1,20 +0,0 @@
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

@ -1,23 +0,0 @@
# 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

@ -1,21 +0,0 @@
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

@ -0,0 +1,21 @@
# data_end can only be compared against; the verifier rejects arithmetic on
# it, so the compiler refuses it.
from ctypes import c_int64, c_uint32 # noqa: F401
from pythonbpf import bpf, section, bpfglobal, compile
from vmlinux import struct_xdp_md
@bpf
@section("xdp")
def prog(ctx: struct_xdp_md) -> c_int64:
e = ctx.data_end + 1
return c_int64(e)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,21 @@
# 70000 cannot be a packet offset: the verifier tracks packet ranges only
# up to 0xffff. Rejected at compile time rather than silently wrapped.
from ctypes import c_int64
from pythonbpf import bpf, section, bpfglobal, compile
from vmlinux import struct_xdp_md
@bpf
@section("xdp")
def prog(ctx: struct_xdp_md) -> c_int64:
d = ctx.data + 70000
return c_int64(d)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,45 @@
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

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

View File

@ -0,0 +1,54 @@
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

@ -1,54 +0,0 @@
"""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) -> int:
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()
ret = re.search(rf'define [^\n]*?\bi(\d+) @"?{re.escape(func_name)}"?\(', ll_text)
ret_ty = {64: ctypes.c_int64, 32: ctypes.c_int32}[int(ret.group(1))]
func = ctypes.CFUNCTYPE(ret_ty, ctypes.c_void_p)(
engine.get_function_address(func_name)
)
return 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,34 +3,25 @@ import uuid
from collections import namedtuple from collections import namedtuple
from pathlib import Path from pathlib import Path
Output = namedtuple("Output", ["stdout", "stderr"])
def verify_object(obj_path: Path) -> tuple[bool, str]:
def verify_object(obj_path: Path) -> tuple[bool, Output]: """Run bpftool prog load -d to verify a BPF object file against the kernel verifier.
"""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. Pins the program temporarily at /sys/fs/bpf/bpf_prog_test_<uuid>, then removes it.
Returns (success, Output(stdout, stderr)). Requires sudo / root. Returns (success, combined_output). 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]}" pin_path = f"/sys/fs/bpf/bpf_prog_test_{uuid.uuid4().hex[:8]}"
try: try:
result = subprocess.run( result = subprocess.run(
["sudo", "bpftool", "prog", "load", str(obj_path), pin_path], ["sudo", "bpftool", "prog", "load", "-d", str(obj_path), pin_path],
capture_output=True, capture_output=True,
text=True, text=True,
timeout=30, timeout=30,
) )
return result.returncode == 0, Output( Output = namedtuple("Output", ["stdout", "stderr"])
stdout=result.stdout, stderr=result.stderr output = Output(stdout=result.stdout, stderr=result.stderr)
) return result.returncode == 0, output
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired:
return False, Output(stdout="", stderr="bpftool timed out after 30s") return False, "bpftool timed out after 30s"
finally: finally:
subprocess.run(["sudo", "rm", "-f", pin_path], check=False, capture_output=True) subprocess.run(["sudo", "rm", "-f", pin_path], check=False, capture_output=True)

View File

@ -200,41 +200,6 @@ 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*` 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. 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 ## 3. Incidental findings
- **Nested struct field access fails with a misleading error.** `ctx.regs.ip` reports - **Nested struct field access fails with a misleading error.** `ctx.regs.ip` reports

View File

@ -1,56 +0,0 @@
# 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

@ -1,57 +0,0 @@
# 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

@ -1,47 +0,0 @@
# 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

@ -1,68 +0,0 @@
# 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

@ -1,31 +0,0 @@
# 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

@ -1,17 +0,0 @@
# 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

@ -1,32 +0,0 @@
# 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

@ -1,29 +0,0 @@
# 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

@ -1,25 +0,0 @@
# `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

@ -1,37 +0,0 @@
# 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

@ -1,21 +0,0 @@
# 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

@ -1,31 +0,0 @@
# 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

@ -1,23 +0,0 @@
# 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

@ -1,25 +0,0 @@
# 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

@ -1,23 +0,0 @@
# 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

@ -1,28 +0,0 @@
# 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

@ -1,24 +0,0 @@
# 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

@ -1,22 +0,0 @@
# 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,25 @@
# The canonical XDP bounds check, through locals: the packet-pointer type
# travels with data and data_end, so data + 34 > data_end is a 64-bit
# unsigned comparison, which is what the verifier needs to prove the range.
from ctypes import c_int64, c_uint32 # noqa: F401
from pythonbpf import bpf, section, bpfglobal, compile
from vmlinux import struct_xdp_md
@bpf
@section("xdp")
def prog(ctx: struct_xdp_md) -> c_int64:
data = ctx.data
data_end = ctx.data_end
if data + 34 > data_end:
return c_int64(1)
return c_int64(2)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,21 @@
# The same bounds check written on the fields directly.
from ctypes import c_int64, c_uint32 # noqa: F401
from pythonbpf import bpf, section, bpfglobal, compile
from vmlinux import struct_xdp_md
@bpf
@section("xdp")
def prog(ctx: struct_xdp_md) -> c_int64:
if ctx.data + 14 > ctx.data_end:
return c_int64(1)
return c_int64(2)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,26 @@
# xdp_md.data is declared u32, but the verifier treats it as a packet pointer
# and prohibits 32-bit arithmetic on it. C's integer rules would rank
# ctx.data - k as a u32 subtraction (w0 += -1, rejected with "R0 32-bit
# pointer arithmetic prohibited"); the compiler special-cases packet-pointer
# fields instead (pythonbpf/expr/packet_pointer.py): 64-bit arithmetic, the
# offset taken as u16, so this is r0 += -1 and no cast is needed.
from ctypes import c_int32, c_int64
from pythonbpf import bpf, section, bpfglobal, compile
from vmlinux import struct_xdp_md
@bpf
@section("xdp")
def prog(ctx: struct_xdp_md) -> c_int64:
k = c_int32(1)
d = ctx.data - k
return c_int64(d)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,21 @@
# Pointer minus pointer is a length: an ordinary 64-bit subtraction, with no
# 16-bit clamp on either side.
from ctypes import c_int64
from pythonbpf import bpf, section, bpfglobal, compile
from vmlinux import struct_xdp_md
@bpf
@section("xdp")
def prog(ctx: struct_xdp_md) -> c_int64:
n = ctx.data_end - ctx.data
return c_int64(n)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,20 @@
# data_meta is a packet-metadata pointer; offsets are allowed on it too.
from ctypes import c_int64, c_uint32 # noqa: F401
from pythonbpf import bpf, section, bpfglobal, compile
from vmlinux import struct_xdp_md
@bpf
@section("xdp")
def prog(ctx: struct_xdp_md) -> c_int64:
m = ctx.data_meta + 4
return c_int64(m)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,25 @@
# A packet pointer stored into a 32-bit local is truncated, as in C
# (`__u32 x = ctx->data`), and is an ordinary integer from then on. The
# verifier forbids 32-bit arithmetic on a packet pointer, not a narrow store
# of one; upstream's cgroup_skb_direct_packet_access does the same with a
# __u32 global.
from ctypes import c_int64, c_uint32 # noqa: F401
from pythonbpf import bpf, section, bpfglobal, compile
from vmlinux import struct_xdp_md
@bpf
@section("xdp")
def prog(ctx: struct_xdp_md) -> c_int64:
x = c_uint32(0)
x = ctx.data
return c_int64(x)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,21 @@
# Adding a constant to a packet pointer is 64-bit pointer arithmetic
# (r0 += 1), not the u32 addition C's integer rules would give xdp_md.data.
from ctypes import c_int64
from pythonbpf import bpf, section, bpfglobal, compile
from vmlinux import struct_xdp_md
@bpf
@section("xdp")
def prog(ctx: struct_xdp_md) -> c_int64:
d = ctx.data + 1
return c_int64(d)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,24 @@
# A runtime offset added to a packet pointer is taken as an unsigned 16-bit
# value (masked to 0xffff, zero-extended), so the verifier can bound the
# packet range; the addition itself is 64-bit.
from ctypes import c_int64
from pythonbpf import bpf, section, bpfglobal, compile
from pythonbpf.helper import random
from vmlinux import struct_xdp_md
@bpf
@section("xdp")
def prog(ctx: struct_xdp_md) -> c_int64:
off = random()
d = ctx.data + off
return c_int64(d)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,22 @@
# A local copied from a packet-pointer field is still a packet pointer: its
# slot is 64-bit and d + 14 is 64-bit pointer arithmetic.
from ctypes import c_int64, c_uint32 # noqa: F401
from pythonbpf import bpf, section, bpfglobal, compile
from vmlinux import struct_xdp_md
@bpf
@section("xdp")
def prog(ctx: struct_xdp_md) -> c_int64:
data = ctx.data
eth = data + 14
return c_int64(eth)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -1,37 +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
# 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

@ -1,41 +0,0 @@
# 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

@ -15,19 +15,18 @@
[xfail] [xfail]
"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/struct_ptr.py" = {reason = "Struct pointer used directly as boolean condition not supported", 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/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_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/license.py" = {reason = "Missing LICENSE global produces IR that llc rejects — should be caught earlier with a clear error message", level = "llc"}
"failing_tests/undeclared_values.py" = {reason = "Undeclared variable used in f-string — should raise SyntaxError (correct behaviour, test documents it)", level = "ir"} "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/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"} "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"}
@ -39,13 +38,36 @@
"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/globals_parameter_and_global.py" = {reason = "A parameter may not be declared global (Python: name is parameter and global)", 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"} "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/break_outside_loop.py" = {reason = "`break` outside a loop is a SyntaxError in Python, and a compile error here", 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/range_variable_step.py" = {reason = "range() step must be an integer literal: its sign decides the loop test", 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"}
# A packet offset has to fit the verifier's 16-bit packet range.
"failing_tests/vmlinux/ctx_data_offset_too_big.py" = {reason = "A constant packet offset outside 0..65535 is a compile error (the verifier tracks packet ranges up to MAX_PACKET_OFF)", level = "ir"}
"failing_tests/vmlinux/ctx_data_end_offset.py" = {reason = "A packet-end pointer can only be compared, not offset (the verifier rejects arithmetic on it)", 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"} "kernel_selftest_equivalent/ringbuf/reserve_submit_discard.py" = {reason = "RingBuffer reserve/typed record/discard workflow is planned but not implemented yet", level = "ir"}

View File

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

View File

@ -1,71 +0,0 @@
"""
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,13 +19,6 @@ from tests.framework.compiler import run_ir_generation
PASSING_DIR = Path(__file__).parent / "passing_tests" PASSING_DIR = Path(__file__).parent / "passing_tests"
HAVE_VMLINUX = importlib.util.find_spec("vmlinux") is not None 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) # path under passing_tests -> (patterns that must appear, patterns that must not)
CASES = { CASES = {
"signedness/widen_unsigned.py": ( "signedness/widen_unsigned.py": (
@ -75,6 +68,38 @@ CASES = {
[r"\bsub i64", r"trunc i64 .* to i32", r"zext i32 .* to i64"], [r"\bsub i64", r"trunc i64 .* to i32", r"zext i32 .* to i64"],
[], [],
), ),
# Packet-pointer fields: 64-bit arithmetic, never the field's u32 rank,
# offsets as u16 (trunc to i16, zext); pointer - pointer is a plain sub.
# No computed value is cut to 32 bits (constant stores such as
# k = c_int32(1) legitimately are).
"vmlinux/ctx_data_arith.py": (
[r"\bsub i64"],
[r"trunc i64 %.* to i32"],
),
"vmlinux/ctx_data_plus_one.py": (
[r"\badd i64"],
[r"trunc i64 %.* to i32"],
),
"vmlinux/ctx_data_runtime_offset.py": (
[r"trunc i64 .* to i16", r"zext i16 .* to i64", r"\badd i64"],
[r"trunc i64 %.* to i32"],
),
"vmlinux/ctx_data_length.py": (
[r"\bsub i64"],
[r"to i16", r"trunc i64 %.* to i32"],
),
"vmlinux/ctx_bounds_check.py": (
[r"icmp ugt i64", r"\badd i64"],
[r"trunc i64 %.* to i32", r"icmp \w+ i32"],
),
"vmlinux/ctx_bounds_check_direct.py": (
[r"icmp ugt i64"],
[r"trunc i64 %.* to i32", r"icmp \w+ i32"],
),
"vmlinux/ctx_data_via_local.py": (
[r"\badd i64"],
[r"trunc i64 %.* to i32"],
),
# c_uint16(0) declares a 16-bit slot, so a u32 ctx field stored into it # c_uint16(0) declares a 16-bit slot, so a u32 ctx field stored into it
# is truncated to 16 bits (C: __u16 queue = ctx->rx_queue_index). # is truncated to 16 bits (C: __u16 queue = ctx->rx_queue_index).
"vmlinux/ctx_field_narrow_store.py": ( "vmlinux/ctx_field_narrow_store.py": (
@ -119,20 +144,6 @@ CASES = {
[r"deref_0_not_null", r"ret i64 %"], [r"deref_0_not_null", r"ret i64 %"],
[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. Level 3 — Kernel verifier tests.
For every passing BPF test file, compiles to a .o and runs: For every passing BPF test file, compiles to a .o and runs:
sudo bpftool prog load <file.o> /sys/fs/bpf/bpf_prog_test_<id> sudo bpftool prog load -d <file.o> /sys/fs/bpf/bpf_prog_test_<id>
These tests are opt-in: they require sudo and kernel access, and are gated These tests are opt-in: they require sudo and kernel access, and are gated
behind the `verifier` pytest mark. Run with: 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 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 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 reconciled against pythonbpf/helper and pythonbpf/maps when scalar @bpfglobal
support, integer signedness and loops merged. support and integer signedness merged.
""" """
import argparse import argparse
@ -70,10 +70,7 @@ NOT_HELPERS = {
# cost a careful rewrite can absorb). Order does not matter. # cost a careful rewrite can absorb). Order does not matter.
PATTERNS = [ PATTERNS = [
# control flow # control flow
# plain for/while lower since loops landed (#106); `do { } while (0)` is a ("loop", "hard", r"\b(for|while)\s*\(|\bbpf_for\b|\bbpf_repeat\b|\bbpf_loop\s*\("),
# 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+"), ("goto", "hard", r"\bgoto\s+\w+"),
("switch", "hard", r"\bswitch\s*\("), ("switch", "hard", r"\bswitch\s*\("),
("ternary", "soft", r"\?[^?:]*:"), ("ternary", "soft", r"\?[^?:]*:"),