Compare commits

..

16 Commits

Author SHA1 Message Date
37fe5d7a9a Tests: Derive the map-value pointer-depth check from a clang reference
tests/c-form/map_update_from_lookup.bpf.c mirrors the two programs the
check covers. At -O0 clang passes bpf_map_update_elem the result of
`load ptr, ptr <prev's slot>`, in both copy() and rebind().

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

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 05:31:38 +05:30
f5eb809f4b Tests: Move tests that pass out of failing_tests
retype, helper_cond, direct_assign and globals had no xfail entry and have
been passing at every level; their NOTE headers describe limits that have
since been lifted, so they are rewritten. xdp_pass was an xfail only because
it used the old count().lookup() spelling of a map call; in the current
syntax it compiles.

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 01:54:13 +05:30
ec5d72fdbe Bump version to 0.2.0 2026-09-26 01:05:13 +05:30
40aad02d73 loops (#106)
* Core: Lower annotated assignment (x: c_int32 = 0)

The annotation types the slot, so `x: c_int32 = 0` is an i32 where the
literal alone would give an i64; the store goes through the same
handle_variable_assignment plain assignment uses. A bare `x: T` makes the
slot and binds nothing.

The already-bound and global-shadowing bookkeeping that Assign allocation did
inline moves into _bind_name, which both statements now call.

* Tests: Annotated assignment passes now

* Core: Lower if-branches in the function's return type

handle_if processed its branches without passing ret_type down, so a
return inside an if fell back to process_stmt's i64 default: a -> c_int32
function got `ret i64 7`, which llc rejects. The branches now go through
process_block, which threads ret_type and stops at a statement that ends
the block instead of emitting after its terminator.

* Core: Lower for-over-range and while loops, with break and continue

`for i in range(...)` steps a hidden induction counter, allocated in the
entry block next to the loop variable, and copies it into the variable each
iteration, so rebinding the variable in the body leaves the trip count alone
as in Python (and the loop stays visibly bounded for the verifier). The
counter is 64-bit, signed unless the bounds make C's arithmetic unsigned.
Bounds are evaluated once, before the loop; the step must be a nonzero
integer literal, because its sign picks the loop test.

`while` re-evaluates its test at the top of each iteration. `break` and
`continue` branch through a loop-target stack on the compilation context;
outside a loop they are a SyntaxError, as in Python. A loop's else-branch
runs on normal exit only. Anything but range() as the iterable is rejected
with NotImplementedError.

The allocation pass now descends into loop bodies and counts helper temps in
loop headers. Checked against clang -O2 on tests/c-form/loops.bpf.c: the
constant-bound cases fold to the same ret, and a helper-bounded loop gets the
same rotated loop.

* Tests: Loops pass now, plus the cases the lowering promises

- passing_tests/loops/: the seven range/while/break/continue/nested tests
  move over from failing_tests/, joined by rebinding the loop variable, a
  negative step, loop else-branches, and a helper-bounded loop over a
  @bpfglobal that survives -O2 as a real loop for the verifier.
- failing_tests/loops/: break outside a loop, and a non-literal range step.
- for_map_items stays xfail: map iteration needs its own design.
- c-form/loops.bpf.c: the clang reference the lowering was checked against.

* Tests: Indent the loop C reference with spaces

The remove-tabs pre-commit hook rejects tab indentation outside docs/ and
Makefiles, which failed the Format job.

* Core: Fix loop edge cases the lowering got wrong

- `pass` is accepted as a statement, the natural body of a loop run for its
  side effects.
- Falling off the end of a function returns 0 in the function's own return
  type. After `while True` that block is unreachable, but a c_int32 function
  still emitted `ret i64 0`, which llc rejected.
- A range() step other than 1 could wrap the counter past INT64_MAX or
  UINT64_MAX back inside the range and loop forever. The step block now ends
  the loop when the distance left to stop, exact as an unsigned number, is
  no longer than the step. That is a normal exit, so the else-branch runs.
  Steps of 1 cannot overshoot and keep the plain loop, so the helper-bounded
  loop the verifier walks is unchanged.
- A step of 2**64 or more no longer truncates to 0: it is a compile error,
  since it does not fit the counter. Steps from 2**63 up are emitted by
  their bits.
- The counter's signedness folds each bound into a signed 64-bit type rather
  than joining the bounds alone, so only a c_uint64 bound makes it unsigned:
  range(-1, n) over a c_uint32 n runs 4 times, as in C with an __s64 counter.

* Tests: Run loop programs on the host, plus adversarial loop cases

Levels 1 and 2 only prove a loop compiles; one can still run the wrong
number of times, or forever. test_loops_run.py JIT-compiles each
helper-free passing_tests/loops case on the host (framework/host_jit.py,
in a subprocess with a timeout) and checks its return value against what
CPython returns for the same body.

- passing_tests/loops/: pass bodies, `while True` exited by a return in a
  c_int32 function, step overflow past INT64_MAX, INT64_MIN and UINT64_MAX,
  a c_uint32 stop with a negative start, and loop variables that must stay
  one local (a nested same-name loop, a read after the loop).
- failing_tests/loops/range_step_too_wide.py: a 2**64 step is a compile error.
- reuse_loop_var_signedness.py is xfail in test_loops_run.py: every local
  gets one slot typed by its first binding, so a second loop's `i` inherits
  the first loop's unsigned type. `x = n_u64; x = -3` does the same, so the
  fix is general, not loop-specific.
2026-09-26 01:00:45 +05:30
4662fe63b5 Merge pull request #105 from pythonbpf/claude/pythonbpf-state-replication-g23gij
Add kernel selftest equivalent roadmap tests
2026-09-25 22:29:04 +05:30
a5eeaafdf3 Tests: Context fields into slots of every width, and c_bool
ctx_field_into_slots.py stores 8-, 32- and 64-bit sk_buff fields into
locals declared at every width and into struct fields of every width,
with IR assertions on the slot widths and the truncation before each
store. It is the compact form of a 52-case matrix (four field widths,
nine local and four struct-field destinations) compiled on master and
here: every case compiles, nothing sign-extends a field on the way in,
and where master compiled the IR is identical except where master put a
narrow local in a 64-bit slot. c_bool.py covers the local, struct field,
map value and global.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 22:20:09 +05:30
20a1e2f3a1 Core: Accept c_bool as a ctypes type
c_bool was missing from the ctypes table, so c_bool(5) was an unknown
call, its slot was never allocated, and the error read "Undefined
variable". It is C's _Bool: one bit, like the True/False locals, never
negative, and a value narrows to it by comparing with zero, which the
signedness rules already apply to 1-bit types. It works as a local, a
struct field, a map value and a global; in BTF it is a one-byte _Bool.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 22:20:07 +05:30
4e8f767e6d Core: Size and describe integers by their real width
Two places took an integer's width as 32 or 64 bits. Ten sites computed
byte sizes as width // 8 (alignment, struct layout, globals), which is
zero for a 1-bit type; they now share byte_size(), which rounds up to
whole bytes. And debug info described every map key or value, and every
struct field, that was not 32 bits wide as unsigned long long: a c_uint8
or c_uint16 map value was declared 8 bytes wide in BTF, so the kernel
copied 8 bytes from a smaller slot. get_int_type() now gives the real
width and sign everywhere, globals included.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 22:20:05 +05:30
d3fa7d7e42 Core: Print integers of any width in f-strings
The printk formatter accepted 64- and 32-bit integers only and raised for
anything else. That went unnoticed while c_uint16(0) and friends silently
made 64-bit slots; with those slots now their declared width, printing
any 8- or 16-bit local failed. Every integer argument is already widened
to 64 bits per its sign before the call, so the 64-bit format fits every
width, and the sign now chooses %lld or %llu (an unsigned value above
INT_MAX printed as negative before).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 22:20:00 +05:30
55 changed files with 1070 additions and 840 deletions

View File

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

View File

@ -1,462 +0,0 @@
# Snake, with the game in the kernel.
#
# A port of bpfsnake (github.com/amiremohamadi/bpfsnake), a bpftrace script.
# The eBPF side keeps the whole game state in maps and runs the game logic:
# steering, moving, collisions, eating and growing. Python only feeds it the
# arrow key and draws what the kernel left in the maps, in a pygame window or,
# with --terminal, in the terminal.
#
# bpftrace's `interval:ms:120` would be a perf_event program, which pylibbpf
# cannot attach yet. Instead Python drives the clock: every tick it calls
# getppid(), and a kprobe on that syscall, filtered to this process, advances
# the game one step.
#
# The original steered from a kprobe on pty_write, reading the byte a terminal
# echoes for each key. That cannot see keys typed into a pygame window, so
# Python writes the key's code into the `state` map instead, in both modes,
# using the original's codes: 'A' up, 'B' down, 'C' right, 'D' left.
#
# Run from the repository root:
# sudo -E env PYTHONPATH=. /path/to/python examples/snake.py # pygame
# sudo env PYTHONPATH=. /path/to/python examples/snake.py --terminal
# The pygame window needs pygame (pip install pygame), and -E keeps your display
# in the environment. The terminal draws the original's board, and like the
# original the game ends when the snake dies.
# Arrows or WASD steer, Space pauses, R restarts, Esc or Q quits.
# x86_64 only (the syscall name in the kprobe).
import argparse
import math
import os
import select
import sys
import termios
import time
import tty
from collections import deque
from ctypes import c_int64, c_uint64, c_void_p
from pythonbpf import BPF, bpf, bpfglobal, map, section
from pythonbpf.helper import pid, random
from pythonbpf.maps import HashMap
MAX_LENGTH = 32
WIDTH = 50 # columns, walls included
HEIGHT = 12 # rows, walls included
TICK_MS = 120
# Slots in the `state` map. The eBPF function spells them as literals: module
# constants are not visible inside it.
FOODX, FOODY, GAME_OVER, PLAYER, KEY = 0, 1, 2, 3, 4
UP, DOWN, RIGHT, LEFT = 65, 66, 67, 68
# Body segment i sits at row snakex[i], column snakey[i]; segment 0 is the head.
# A missing key reads as 0, which is a wall, so the body ends at the first 0.
@bpf
@map
def snakex() -> HashMap:
return HashMap(key=c_uint64, value=c_uint64, max_entries=32)
@bpf
@map
def snakey() -> HashMap:
return HashMap(key=c_uint64, value=c_uint64, max_entries=32)
@bpf
@map
def state() -> HashMap:
return HashMap(key=c_uint64, value=c_uint64, max_entries=5)
@bpf
@section("kprobe/__x64_sys_getppid")
def tick(ctx: c_void_p) -> c_int64:
if pid() != state.lookup(3): # PLAYER
return c_int64(0)
if state.lookup(2) != 0: # GAME_OVER
return c_int64(0)
# Move: every segment takes the place of the one ahead of it
i = 0
while i < 32 and snakex.lookup(i) != 0 and snakey.lookup(i) != 0:
i += 1
i -= 1
while i > 0:
snakex.update(i, snakex.lookup(i - 1))
snakey.update(i, snakey.lookup(i - 1))
i -= 1
key = state.lookup(4) # KEY
headx = snakex.lookup(0)
heady = snakey.lookup(0)
if key == 65: # up
snakex.update(0, headx - 1)
elif key == 66: # down
snakex.update(0, headx + 1)
elif key == 68: # left
snakey.update(0, heady - 1)
else: # right
snakey.update(0, heady + 1)
# Game over when the head hits a wall ...
x = snakex.lookup(0)
y = snakey.lookup(0)
if x == 0 or x == 11 or y == 0 or y == 49:
state.update(2, 1) # GAME_OVER
# ... or the snake's own body
i = 1
while i < 32 and snakex.lookup(i) != 0 and snakey.lookup(i) != 0:
if x == snakex.lookup(i) and y == snakey.lookup(i):
state.update(2, 1) # GAME_OVER
i += 1
# Eat: new food somewhere inside the walls, and the tail grows by one
if x == state.lookup(0) and y == state.lookup(1): # FOODX, FOODY
state.update(0, random() % 10 + 1)
state.update(1, random() % 48 + 1)
i = 2
while i < 32 and snakex.lookup(i) != 0 and snakey.lookup(i) != 0:
i += 1
snakex.update(i, snakex.lookup(i - 1))
snakey.update(i, snakey.lookup(i - 1))
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
# ---------------------------------------------------------------- userspace
OPPOSITE = {UP: DOWN, DOWN: UP, LEFT: RIGHT, RIGHT: LEFT}
def read(m, k):
return m.lookup(k) or 0
class Game:
"""The userspace half: queue turns, drive the kernel's tick, read it back."""
def __init__(self, b):
self.b = b
self.restart()
def restart(self):
b = self.b
for i in range(MAX_LENGTH):
for m in (b["snakex"], b["snakey"]):
try:
m.delete_elem(i)
except Exception:
pass # the key was never set
# BEGIN, as in the original
b["snakex"][0], b["snakey"][0] = 1, 1
b["snakex"][1], b["snakey"][1] = 1, 2
b["state"][FOODX], b["state"][FOODY] = 4, 4
b["state"][GAME_OVER] = 0
b["state"][KEY] = RIGHT
b["state"][PLAYER] = os.getpid()
self.heading, self.turns = RIGHT, deque(maxlen=3)
self.ticks, self.paused = 0, False
self.last_tick = time.monotonic()
self.snapshot()
def turn(self, code):
self.turns.append(code)
def toggle_pause(self):
if not self.over:
self.paused = not self.paused
def due(self):
return time.monotonic() - self.last_tick >= TICK_MS / 1000
def tick(self):
"""One step of the game, run by the kernel."""
self.last_tick = time.monotonic()
if self.over or self.paused:
return
# One queued turn per tick; reversing onto your own neck is ignored
while self.turns:
turn = self.turns.popleft()
if turn not in (self.heading, OPPOSITE[self.heading]):
self.heading = turn
break
self.b["state"][KEY] = self.heading
os.getppid() # interval:ms:120
self.ticks += 1
self.snapshot()
def snapshot(self):
b, body = self.b, []
for i in range(MAX_LENGTH):
x, y = read(b["snakex"], i), read(b["snakey"], i)
if x == 0 or y == 0:
break
if not body or body[-1] != (x, y): # a fresh tail sits on the last one
body.append((x, y))
self.body = body
self.food = (read(b["state"], FOODX), read(b["state"], FOODY))
self.over = bool(read(b["state"], GAME_OVER))
def status(self):
n = len(self.body)
return f"length {n}/{MAX_LENGTH} score {n - 2} ticks {self.ticks}"
# ----------------------------------------------------------------- terminal
# Bytes a terminal sends: an arrow is ESC [ A..D (or ESC O A..D), and its last
# byte happens to be the code the kernel expects.
T_KEYS = {b"w": UP, b"s": DOWN, b"a": LEFT, b"d": RIGHT}
def terminal_frame(game):
"""The board exactly as the bpftrace script prints it."""
body = set(game.body)
rows = []
for x in range(HEIGHT):
row = []
for y in range(WIDTH):
if x == 0 or y == 0 or x == HEIGHT - 1 or y == WIDTH - 1:
row.append("#")
elif (x, y) == game.food:
row.append("$")
elif (x, y) in body:
row.append("@")
else:
row.append(" ")
rows.append("".join(row) + "\n")
return "\033[H" + "".join(rows) # move cursor to top left
def terminal_keys(data, game):
"""Apply a burst of bytes read from the terminal. False means quit."""
i = 0
while i < len(data):
ch = data[i : i + 1]
if ch == b"\x1b" and data[i + 1 : i + 2] in (b"[", b"O"):
code = data[i + 2 : i + 3]
if code in (b"A", b"B", b"C", b"D"):
game.turn(code[0])
i += 3
continue
ch = ch.lower()
if ch in (b"q", b"\x03"):
return False
if ch == b" ":
game.toggle_pause()
elif ch == b"r":
game.restart()
elif ch in T_KEYS:
game.turn(T_KEYS[ch])
i += 1
return True
def run_terminal(game):
fd = sys.stdin.fileno()
saved = termios.tcgetattr(fd)
out = sys.stdout
try:
tty.setcbreak(fd) # keys arrive at once and are not echoed
out.write("\033[H\033[2J") # clear screen
while True:
out.write(terminal_frame(game))
out.flush()
if game.over:
return # exit(), as in the original
wait = max(0.0, TICK_MS / 1000 - (time.monotonic() - game.last_tick))
if select.select([fd], [], [], wait)[0]:
if not terminal_keys(os.read(fd, 64), game):
return
if game.due():
game.tick()
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, saved)
# ------------------------------------------------------------------- pygame
CELL = 24
HUD = 56
BG = (15, 23, 42)
TILE = (22, 32, 54)
WALL = (51, 65, 85)
WALL_EDGE = (71, 85, 105)
HEAD = (74, 222, 128)
TAIL = (21, 128, 61)
FOOD = (244, 63, 94)
LEAF = (132, 204, 22)
TEXT = (226, 232, 240)
MUTED = (148, 163, 184)
ACCENT = (56, 189, 248)
def cell_rect(x, y, inset=0):
return pygame.Rect(
y * CELL + inset, HUD + x * CELL + inset, CELL - 2 * inset, CELL - 2 * inset
)
def mix(a, b, t):
return tuple(round(a[i] + (b[i] - a[i]) * t) for i in range(3))
def draw_board(screen):
screen.fill(BG)
for x in range(HEIGHT):
for y in range(WIDTH):
if x in (0, HEIGHT - 1) or y in (0, WIDTH - 1):
pygame.draw.rect(screen, WALL, cell_rect(x, y, 1), border_radius=5)
pygame.draw.rect(
screen, WALL_EDGE, cell_rect(x, y, 1), width=1, border_radius=5
)
elif (x + y) % 2:
pygame.draw.rect(screen, TILE, cell_rect(x, y))
def draw_food(screen, food, now):
pulse = (math.sin(now / 180) + 1) / 2
r = cell_rect(*food)
glow = pygame.Surface((CELL * 2, CELL * 2), pygame.SRCALPHA)
pygame.draw.circle(
glow, (*FOOD, int(40 + 50 * pulse)), (CELL, CELL), int(CELL * 0.7 + 4 * pulse)
)
screen.blit(glow, (r.centerx - CELL, r.centery - CELL))
pygame.draw.circle(screen, FOOD, r.center, CELL // 2 - 4)
pygame.draw.circle(screen, (255, 160, 180), (r.centerx - 3, r.centery - 3), 3)
pygame.draw.ellipse(screen, LEAF, (r.centerx, r.top + 1, 8, 5))
def draw_snake(screen, body):
n = len(body)
for i in range(n - 1, -1, -1):
color = mix(HEAD, TAIL, i / max(n - 1, 1))
# Bridge to the segment behind so the body reads as one piece
if i + 1 < n:
a, b = cell_rect(*body[i], 3), cell_rect(*body[i + 1], 3)
pygame.draw.rect(screen, color, a.union(b), border_radius=8)
inset = 2 if i == 0 else 3
pygame.draw.rect(screen, color, cell_rect(*body[i], inset), border_radius=8)
if n >= 2:
(hx, hy), (nx, ny) = body[0], body[1]
dx, dy = hx - nx, hy - ny # rows, columns
else:
dx, dy = 0, 1
cx, cy = cell_rect(*body[0]).center
for side in (-1, 1):
# Eyes sit ahead of centre, spread across the direction of travel.
# Screen x follows columns (dy) and screen y follows rows (dx).
ex = cx + dy * 3 + dx * side * 5
ey = cy + dx * 3 + dy * side * 5
pygame.draw.circle(screen, (255, 255, 255), (ex, ey), 4)
pygame.draw.circle(screen, BG, (ex + dy, ey + dx), 2)
def draw_hud(screen, fonts, game):
big, small = fonts
screen.blit(big.render("bpfsnake", True, TEXT), (16, 12))
screen.blit(small.render("game logic runs in eBPF", True, MUTED), (160, 22))
s = small.render(game.status(), True, ACCENT)
screen.blit(s, (WIDTH * CELL - s.get_width() - 16, 22))
def draw_overlay(screen, fonts, title, hint):
big, small = fonts
shade = pygame.Surface(screen.get_size(), pygame.SRCALPHA)
shade.fill((2, 6, 23, 170))
screen.blit(shade, (0, 0))
t = big.render(title, True, TEXT)
h = small.render(hint, True, MUTED)
cx, cy = screen.get_width() // 2, screen.get_height() // 2
screen.blit(t, (cx - t.get_width() // 2, cy - 30))
screen.blit(h, (cx - h.get_width() // 2, cy + 12))
def run_pygame(game):
pygame.init()
pygame.display.set_caption("bpfsnake")
screen = pygame.display.set_mode((WIDTH * CELL, HUD + HEIGHT * CELL))
fonts = (
pygame.font.SysFont("dejavusansmono,monospace", 26, bold=True),
pygame.font.SysFont("dejavusansmono,monospace", 15),
)
keys = {
pygame.K_UP: UP,
pygame.K_w: UP,
pygame.K_DOWN: DOWN,
pygame.K_s: DOWN,
pygame.K_LEFT: LEFT,
pygame.K_a: LEFT,
pygame.K_RIGHT: RIGHT,
pygame.K_d: RIGHT,
}
clock = pygame.time.Clock()
try:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
if event.type != pygame.KEYDOWN:
continue
if event.key in (pygame.K_ESCAPE, pygame.K_q):
return
if event.key == pygame.K_SPACE:
game.toggle_pause()
elif event.key == pygame.K_r:
game.restart()
elif event.key in keys:
game.turn(keys[event.key])
if game.due():
game.tick()
draw_board(screen)
draw_food(screen, game.food, pygame.time.get_ticks())
draw_snake(screen, game.body)
draw_hud(screen, fonts, game)
if game.over:
hint = f"length {len(game.body)} · R restart · Esc quit"
draw_overlay(screen, fonts, "game over", hint)
elif game.paused:
draw_overlay(screen, fonts, "paused", "Space resume")
pygame.display.flip()
clock.tick(60)
finally:
pygame.quit()
parser = argparse.ArgumentParser(description="Snake, with the game in eBPF.")
parser.add_argument(
"--terminal",
action="store_true",
help="draw in this terminal instead of a pygame window (no pygame needed)",
)
args = parser.parse_args()
if not args.terminal:
try:
import pygame
except ImportError:
sys.exit("snake.py: pygame is not installed; pip install pygame, or --terminal")
b = BPF()
b.load()
b.attach_all()
try:
if args.terminal:
run_terminal(Game(b))
else:
run_pygame(Game(b))
except KeyboardInterrupt:
pass

View File

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

View File

@ -6,7 +6,7 @@ from .symbols import LocalSymbol
from pythonbpf.helper import HelperHandlerRegistry
from pythonbpf.vmlinux_parser.dependency_node import Field
from .expr import VmlinuxHandlerRegistry
from pythonbpf.type_deducer import ctypes_to_ir, is_ctypes, IntTy, signedness
from pythonbpf.type_deducer import ctypes_to_ir, is_ctypes, IntTy, signedness, byte_size
from pythonbpf.expr.type_inference import infer_int_type
from pythonbpf.expr.operators import usual_arithmetic_conversions
from pythonbpf.maps import BPFMapType
@ -102,7 +102,10 @@ def handle_for_allocation(compilation_context, builder, stmt, local_sym_tab):
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.
# 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)
@ -110,8 +113,8 @@ def handle_for_allocation(compilation_context, builder, stmt, local_sym_tab):
]
signed = True
if all(ty is not None for ty in bound_types):
common = bound_types[0]
for ty in bound_types[1:]:
common = IntTy(64, True)
for ty in bound_types:
common = usual_arithmetic_conversions(common, ty)
signed = signedness(common)
if not signed and step < 0:
@ -191,6 +194,11 @@ def parse_range(stmt):
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
@ -282,7 +290,7 @@ def _allocate_for_call(builder, var_name, rval, local_sym_tab, compilation_conte
# slot of that width; the value is converted into it at the store.
ir_type = ctypes_to_ir(call_type)
var = builder.alloca(ir_type, name=var_name)
var.align = ir_type.width // 8
var.align = byte_size(ir_type)
local_sym_tab[var_name] = LocalSymbol(var, ir_type)
logger.info(f"Pre-allocated {var_name} as {call_type}")
@ -639,7 +647,7 @@ def _allocate_for_attribute(
tmp_name = f"{struct_var}_{field_name}_tmp"
tmp_ir_type = ir.IntType(field_size_bits)
tmp_var = builder.alloca(tmp_ir_type, name=tmp_name)
tmp_var.align = tmp_ir_type.width // 8
tmp_var.align = byte_size(tmp_ir_type)
local_sym_tab[tmp_name] = LocalSymbol(tmp_var, tmp_ir_type)
logger.info(
f"Pre-allocated temp {tmp_name} (i{field_size_bits}) for vmlinux field read {vmlinux_struct_name}.{field_name}"
@ -694,8 +702,8 @@ def _allocate_with_type(builder, var_name, ir_type):
def _get_alignment(ir_type):
"""Get appropriate alignment for IR type."""
if isinstance(ir_type, ir.IntType):
return ir_type.width // 8
return byte_size(ir_type)
elif isinstance(ir_type, ir.ArrayType) and isinstance(ir_type.element, ir.IntType):
return ir_type.element.width // 8
return byte_size(ir_type.element)
else:
return 8 # Default: pointer size

View File

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

View File

@ -4,7 +4,6 @@ Provides utilities for generating DWARF/BTF debug information
"""
from . import dwarf_constants as dc
from llvmlite.ir.values import DIValue
from typing import Any, List
@ -50,6 +49,27 @@ class DebugInfoGenerator:
)
return self._type_cache[key]
def get_int_type(self, ty) -> Any:
"""Debug type for an integer IR type, by width and sign (read from the
IntTy descriptor, signed for a plain ir.IntType). A 1-bit type is C's
_Bool, which occupies one byte. BTF, and so a map's key and value
sizes, come from this, so the width must be the real one."""
from pythonbpf.type_deducer import signedness
width, signed = ty.width, signedness(ty)
if width == 1:
return self.get_basic_type("_Bool", 8, dc.DW_ATE_boolean)
base = {8: "char", 16: "short", 32: "int", 64: "long long"}.get(width)
if base is None:
raise ValueError(f"no debug type for a {width}-bit integer")
if width == 8:
encoding = dc.DW_ATE_signed_char if signed else dc.DW_ATE_unsigned_char
else:
encoding = dc.DW_ATE_signed if signed else dc.DW_ATE_unsigned
return self.get_basic_type(
base if signed else f"unsigned {base}", width, encoding
)
def get_uint8_type(self) -> Any:
"""Get debug info for signed 8-bit integer"""
return self.get_basic_type("char", 8, dc.DW_ATE_unsigned)
@ -228,25 +248,14 @@ class DebugInfoGenerator:
Example:
!DILocalVariable(name: "ctx", arg: 1, file: !3, line: 20, type: !7)
"""
# Not through add_debug_info, which returns a cached node for equal
# operands: a second function with the same parameter name would get
# the first one's node, already scoped to the first function by
# add_scope_to_local_variable. Scoping it again makes a metadata cycle
# that llvmlite recurses on forever when it hashes the next node.
operands = self.module._fix_di_operands(
return self.module.add_debug_info(
"DILocalVariable",
{
"name": name,
"arg": arg,
"file": self.module._file_metadata,
"type": var_type,
}.items()
)
return DIValue(
self.module,
False,
"DILocalVariable",
sorted(operands),
name=str(len(self.module.metadata)),
},
)
def add_scope_to_local_variable(self, local_variable_debug_info, scope_value):

View File

@ -383,57 +383,12 @@ def _handle_ctypes_call(
return value, expected_type
def _is_map_int_value(operand, compilation_context, local_sym_tab):
"""Whether the operand is an integer held in a map: a `m.lookup(k)` call on
a map with an integer value, or a local bound to one. Both evaluate to a
pointer into the map, and comparing one means comparing the value."""
if isinstance(operand, ast.Name):
sym = local_sym_tab.get(operand.id)
if sym is None or not isinstance(sym.var.type, ir.PointerType):
return False
_, depth = get_base_type_and_depth(sym.var.type)
return depth == 2 and isinstance(sym.metadata, str) and is_ctypes(sym.metadata)
if (
isinstance(operand, ast.Call)
and isinstance(operand.func, ast.Attribute)
and operand.func.attr == "lookup"
and isinstance(operand.func.value, ast.Name)
):
map_sym = compilation_context.map_sym_tab.get(operand.func.value.id)
if map_sym is None:
return False
value_type = map_sym.params.get("value")
return isinstance(value_type, str) and is_ctypes(value_type)
return False
def _handle_compare(func, compilation_context, builder, cond, local_sym_tab):
"""Handle ast.Compare expressions."""
if len(cond.ops) != 1 or len(cond.comparators) != 1:
logger.error("Only single comparisons are supported")
return None
if any(
_is_map_int_value(operand, compilation_context, local_sym_tab)
for operand in (cond.left, cond.comparators[0])
):
# A map value compares by what it holds (null-checked, 0 when the key
# is absent), never by address: `x == m.lookup(i)` with both sides
# pointers would otherwise compare two map slots' addresses.
lhs, lhs_ty = get_typed_operand(
func, compilation_context, cond.left, builder, local_sym_tab
)
rhs, rhs_ty = get_typed_operand(
func, compilation_context, cond.comparators[0], builder, local_sym_tab
)
cmp_ty = usual_arithmetic_conversions(lhs_ty, rhs_ty)
lhs = to_promoted(builder, lhs, lhs_ty, cmp_ty)
rhs = to_promoted(builder, rhs, rhs_ty, cmp_ty)
return handle_comparator(
func, builder, cond.ops[0], lhs, rhs, signed=signedness(cmp_ty)
)
lhs = eval_expr(
func,
compilation_context,
@ -887,5 +842,13 @@ def handle_expr(
call,
local_sym_tab,
)
elif any(isinstance(node, ast.Call) for node in ast.walk(call)):
# A docstring or a bare name has no effect and can be dropped; an
# expression with a call in it (`f() if c else g()`, `a() or b()`)
# does, and dropping it would silently lose the call.
raise NotImplementedError(
f"Unsupported expression statement on line {expr.lineno}: "
f"{type(call).__name__}; write it as an if statement or assignment"
)
else:
logger.info("Unsupported expression type")
logger.debug(f"Dropping expression statement without effect: {ast.dump(call)}")

View File

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

View File

@ -491,7 +491,22 @@ def handle_for(func, compilation_context, builder, stmt, local_sym_tab, ret_type
)
builder.position_at_end(inc_block)
next_idx = builder.add(builder.load(counter.var), ir.Constant(loop_ty, step))
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)
@ -509,6 +524,13 @@ def handle_for(func, compilation_context, builder, stmt, local_sym_tab, ret_type
)
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."""
@ -581,6 +603,8 @@ def process_stmt(
handle_for(func, compilation_context, builder, stmt, local_sym_tab, ret_type)
elif isinstance(stmt, (ast.Break, ast.Continue)):
handle_loop_jump(compilation_context, builder, stmt)
elif isinstance(stmt, ast.Pass):
pass
elif isinstance(stmt, ast.Return):
did_return = handle_return(
func, builder, stmt, local_sym_tab, ret_type, compilation_context
@ -720,7 +744,11 @@ def process_func_body(
)
if not did_return:
builder.ret(ir.Constant(ir.IntType(64), 0))
# Falling off the end returns 0, in the function's own return type:
# after `while True` this block is unreachable, but it still has to
# type-check.
default_ty = ret_type if isinstance(ret_type, ir.IntType) else ir.IntType(64)
builder.ret(ir.Constant(default_ty, 0))
def process_bpf_chunk(func_node, compilation_context, return_type):

View File

@ -3,16 +3,13 @@ import ast
from logging import Logger
import logging
from .type_deducer import ctypes_to_ir, is_signed_ctype
from .type_deducer import ctypes_to_ir, byte_size
from .symbols import BpfGlobalSymbol
from .debuginfo import DebugInfoGenerator
from .expr import VmlinuxHandlerRegistry
from .debuginfo import dwarf_constants as dc
logger: Logger = logging.getLogger(__name__)
_C_NAME_BY_WIDTH = {8: "char", 16: "short", 32: "int", 64: "long long"}
def populate_global_symbol_table(tree, compilation_context):
"""
@ -78,7 +75,7 @@ def _emit_global(module: ir.Module, node, name):
# (align 4 for i32, align 8 for i64). llc derives the BTF DATASEC layout
# from these symbols, so the alignment should mirror the C reference in
# tests/c-form/global_vars.bpf.c.
gvar.align = ty.width // 8 if isinstance(ty, ir.IntType) else 8
gvar.align = byte_size(ty) if isinstance(ty, ir.IntType) else 8
gvar.linkage = "dso_local"
gvar.global_constant = False
return gvar
@ -93,15 +90,7 @@ def _emit_global_debug_info(compilation_context, gvar, name, ctype_name):
future skeleton can tell which variable lives at which offset.
"""
generator = DebugInfoGenerator(compilation_context.module)
width = gvar.value_type.width
signed = is_signed_ctype(ctype_name)
base = _C_NAME_BY_WIDTH[width]
if width == 8:
encoding = dc.DW_ATE_signed_char if signed else dc.DW_ATE_unsigned_char
else:
encoding = dc.DW_ATE_signed if signed else dc.DW_ATE_unsigned
cname = base if signed else f"unsigned {base}"
di_type = generator.get_basic_type(cname, width, encoding)
di_type = generator.get_int_type(ctypes_to_ir(ctype_name))
dv = generator.create_global_var_debug_info(name, di_type, is_local=False)
gvar.set_metadata("dbg", dv)

View File

@ -11,7 +11,6 @@ from .helpers import (
deref,
comm,
probe_read_str,
probe_read_kernel,
random,
probe_read,
smp_processor_id,
@ -79,7 +78,6 @@ __all__ = [
"deref",
"comm",
"probe_read_str",
"probe_read_kernel",
"random",
"probe_read",
"smp_processor_id",

View File

@ -651,21 +651,10 @@ def bpf_probe_read_kernel_emitter(
f"probe_read_kernel expects 2 args (dst, src), got {len(call.args)}"
)
# Destination: a char array reads its length, a scalar reads its width
dst = get_or_create_ptr_from_arg(
# Get destination buffer (char array -> i8*)
dst_ptr, dst_size = get_or_create_ptr_from_arg(
func, compilation_context, call.args[0], builder, local_sym_tab
)
if isinstance(dst, tuple):
dst_ptr, dst_size = dst
else:
dst_ptr = dst
pointee = dst_ptr.type.pointee
if not isinstance(pointee, ir.IntType):
raise ValueError(
f"probe_read_kernel destination must be a char array or an "
f"integer, got {pointee}"
)
dst_size = pointee.width // 8
# Get source pointer (evaluate expression)
src_ptr, src_type = get_ptr_from_arg(

View File

@ -67,6 +67,11 @@ def get_or_create_ptr_from_arg(
else:
# Stack space is already allocated
ptr = get_var_ptr_from_name(arg.id, local_sym_tab)
if symbol is not None and isinstance(symbol.ir_type, ir.PointerType):
# The slot holds a pointer (a map lookup result, or a local
# rebound to point at a temporary): the helper wants that
# pointer, not the address of the slot it is kept in.
ptr = builder.load(ptr)
elif isinstance(arg, ast.Constant) and isinstance(arg.value, int):
int_width = 64 # Default to i64
if expected_type and isinstance(expected_type, ir.IntType):
@ -341,12 +346,6 @@ def get_ptr_from_arg(arg, func, compilation_context, builder, local_sym_tab):
val, val_type = result
# An address held in a 64-bit integer, such as a pt_regs register field:
# the C spelling is (void *)ctx->si
if isinstance(val.type, ir.IntType) and val.type.width == 64:
ptr_type = ir.PointerType(ir.IntType(8))
return builder.inttoptr(val, ptr_type), ptr_type
if not isinstance(val_type, ir.PointerType):
raise ValueError(f"Expected pointer type, got {val_type}")

View File

@ -27,11 +27,6 @@ def probe_read_str(dst, src):
return ctypes.c_int64(0)
def probe_read_kernel(dst, src):
"""Safely read sizeof(dst) bytes from kernel memory"""
return ctypes.c_int64(0)
def random():
"""get a pseudorandom u32 number"""
return ctypes.c_int32(0)

View File

@ -1,5 +1,6 @@
import ast
import logging
from pythonbpf.type_deducer import signedness
from llvmlite import ir
from pythonbpf.expr import eval_expr, get_base_type_and_depth, deref_to_depth, convert
@ -155,17 +156,10 @@ def _process_attr_in_fval(attr_node, fmt_parts, exprs, local_sym_tab, struct_sym
def _populate_fval(ftype, node, fmt_parts, exprs):
"""Populate format parts and expressions based on field type."""
if isinstance(ftype, ir.IntType):
# TODO: We print as signed integers only for now
if ftype.width == 64:
fmt_parts.append("%lld")
exprs.append(node)
elif ftype.width == 32:
fmt_parts.append("%d")
exprs.append(node)
else:
raise NotImplementedError(
f"Unsupported integer width in f-string: {ftype.width}"
)
# Every integer argument is widened to 64 bits (per its sign) before
# the call, so the 64-bit format fits any width; the sign picks it.
fmt_parts.append("%lld" if signedness(ftype) else "%llu")
exprs.append(node)
elif isinstance(ftype, ir.PointerType):
target, depth = get_base_type_and_depth(ftype)
if isinstance(target, ir.IntType):

View File

@ -1,3 +1,4 @@
from pythonbpf.type_deducer import ctypes_to_ir, is_ctypes
import logging
from llvmlite import ir
from pythonbpf.debuginfo import DebugInfoGenerator
@ -122,11 +123,12 @@ def _get_key_val_dbg_type(name, generator, structs_sym_tab):
# Fallback to basic types
logger.info(f"No struct named {name}, falling back to basic type")
# NOTE: Only handling int and long for now
if name in ["c_int32", "c_uint32"]:
return generator.get_uint32_type()
# A ctypes integer: its real width and sign, so the map's key or value
# size in BTF matches what the program stores (a c_uint8 value is 1 byte).
if is_ctypes(name):
return generator.get_int_type(ctypes_to_ir(name))
# Default fallback for now
logger.warning(f"No debug type for map key/value {name}, defaulting to u64")
return generator.get_uint64_type()
@ -136,11 +138,7 @@ def _get_struct_debug_type(struct_obj, generator, structs_sym_tab):
for fld in struct_obj.fields.keys():
fld_type = struct_obj.field_type(fld)
if isinstance(fld_type, ir.IntType):
if fld_type.width == 32:
fld_dbg_type = generator.get_uint32_type()
else:
# NOTE: Assuming 64-bit for all other int types
fld_dbg_type = generator.get_uint64_type()
fld_dbg_type = generator.get_int_type(fld_type)
elif isinstance(fld_type, ir.ArrayType):
# NOTE: Array types have u8 elements only for now
# Debug info generation should fail for other types

View File

@ -1,3 +1,4 @@
from pythonbpf.type_deducer import byte_size
from llvmlite import ir
@ -24,9 +25,9 @@ class StructType:
def field_size(self, field_name):
fld = self.fields[field_name]
if isinstance(fld, ir.ArrayType):
return fld.count * (fld.element.width // 8)
return fld.count * byte_size(fld.element)
elif isinstance(fld, ir.IntType):
return fld.width // 8
return byte_size(fld)
elif isinstance(fld, ir.PointerType):
return 8

View File

@ -1,7 +1,7 @@
import ast
import logging
from llvmlite import ir
from pythonbpf.type_deducer import ctypes_to_ir
from pythonbpf.type_deducer import ctypes_to_ir, byte_size
from .struct_type import StructType
logger = logging.getLogger(__name__)
@ -79,11 +79,11 @@ def calc_struct_size(field_types):
curr_offset = 0
for ftype in field_types:
if isinstance(ftype, ir.IntType):
fsize = ftype.width // 8
fsize = byte_size(ftype)
alignment = fsize
elif isinstance(ftype, ir.ArrayType):
fsize = ftype.count * (ftype.element.width // 8)
alignment = ftype.element.width // 8
fsize = ftype.count * byte_size(ftype.element)
alignment = byte_size(ftype.element)
elif isinstance(ftype, ir.PointerType):
# We won't encounter this rn, but for the future
fsize = 8

View File

@ -41,6 +41,12 @@ class IntTy(ir.IntType):
return f"{'i' if self.signed else 'u'}{self.width}"
def byte_size(ty) -> int:
"""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."""
return (ty.width + 7) // 8
def int_literal_type(value: int) -> IntTy:
"""C's type for an integer constant: `int` if the value fits, else
`long long`. Literals and enum constants alike; an enum constant is an
@ -107,6 +113,9 @@ _INT_CTYPE_WIDTHS = {
"c_longlong": 64,
# A pointer-sized integer; treated as unsigned like uintptr_t.
"c_void_p": 64,
# C's _Bool: one bit to LLVM (as True/False locals already are). It is
# never negative, and a value narrows to it by comparing with zero.
"c_bool": 1,
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,33 +0,0 @@
# A comparison with a map value compares what the map holds, on either side:
# `head == body.lookup(1)` with both sides map lookups used to compare the two
# entries' addresses.
from ctypes import c_int64, c_uint64, c_void_p
from pythonbpf import bpf, map, section, bpfglobal, compile
from pythonbpf.maps import HashMap
@bpf
@map
def body() -> HashMap:
return HashMap(key=c_uint64, value=c_uint64, max_entries=10)
@bpf
@section("tracepoint/syscalls/sys_enter_getppid")
def prog(ctx: c_void_p) -> c_int64:
head = body.lookup(0)
if head == body.lookup(1):
return c_int64(1)
k = 3
if body.lookup(2) == body.lookup(k):
return c_int64(2)
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,49 @@
# c_bool is C's _Bool: a value narrows to it by comparing with zero (5 is
# true), and it widens to 0 or 1 (zero-extended, never sign-extended), as a
# local, a struct field, a map value and a global. In BTF it is a one-byte
# _Bool, so the map's value size is 1.
from ctypes import c_bool, c_int64, c_uint32, c_void_p
from pythonbpf import bpf, map, struct, section, bpfglobal, compile
from pythonbpf.maps import HashMap
@bpf
@struct
class flags:
on: c_bool
n: c_uint32
@bpf
@map
def seen() -> HashMap:
return HashMap(key=c_uint32, value=c_bool, max_entries=4)
@bpf
@bpfglobal
def armed() -> c_bool:
return c_bool(1)
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def prog(ctx: c_void_p) -> c_int64:
global armed
b = c_bool(5)
f = flags()
f.on = 2
k = c_uint32(1)
seen.update(k, c_bool(1))
armed = 7
print(f"{b} {f.on} {armed}")
return c_int64(b)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,47 @@
# A context field stored into a slot of any integer width: the field is loaded
# at its declared width, zero-extended (all of these are unsigned), then cut to
# the slot's width, as C's `__u8 x = skb->len` does. Covers locals declared
# with every width and struct fields of every width.
from ctypes import c_int8, c_uint16, c_int32, c_uint64, c_uint8, c_uint32, c_int64
from pythonbpf import bpf, struct, section, bpfglobal, compile
from vmlinux import struct___sk_buff
@bpf
@struct
class rec:
f8: c_uint8
f16: c_uint16
f32: c_uint32
f64: c_uint64
@bpf
@section("tc")
def prog(ctx: struct___sk_buff) -> c_int64:
a8 = c_int8(0)
a8 = ctx.len # u32 -> i8
b16 = c_uint16(0)
b16 = ctx.len # u32 -> u16
c32 = c_int32(0)
c32 = ctx.tstamp # u64 -> i32
d64 = c_uint64(0)
d64 = ctx.tstamp_type # u8 -> u64
e = ctx.len # undeclared: a 64-bit slot
r = rec()
r.f8 = ctx.len
r.f16 = ctx.tstamp
r.f32 = ctx.tstamp
r.f64 = ctx.tstamp_type
print(f"{a8} {b16} {c32}")
print(f"{d64} {e}")
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

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

View File

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

View File

@ -1,34 +0,0 @@
# probe_read_kernel into a scalar reads the scalar's width, and the source may
# be an address held in a register field (C: (void *)ctx->si). bpfsnake reads
# one typed byte this way: `@key = *((int8*)arg1)`.
from ctypes import c_int8, c_int64
from pythonbpf import bpf, section, bpfglobal, compile
from pythonbpf.helper import probe_read_kernel
from vmlinux import struct_pt_regs
@bpf
@bpfglobal
def last() -> c_int64:
return c_int64(0)
# pty_write(struct tty_struct *tty, const u8 *buf, size_t c)
@bpf
@section("kprobe/pty_write")
def prog(ctx: struct_pt_regs) -> c_int64:
global last
if ctx.dx == 1:
byte = c_int8(0)
probe_read_kernel(byte, ctx.si)
last = byte
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -1,27 +0,0 @@
# Two programs whose context parameters share a name and a vmlinux type. Their
# debug info used to share one cached DILocalVariable, scoped to both
# functions, and llvmlite recursed forever hashing the resulting cycle.
from ctypes import c_int64
from pythonbpf import bpf, section, bpfglobal, compile
from vmlinux import struct_pt_regs
@bpf
@section("kprobe/do_unlinkat")
def first(ctx: struct_pt_regs) -> c_int64:
return c_int64(0)
@bpf
@section("kprobe/do_rmdir")
def second(ctx: struct_pt_regs) -> c_int64:
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

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

View File

@ -15,7 +15,9 @@
[xfail]
"failing_tests/conditionals/struct_ptr.py" = {reason = "Struct pointer used directly as boolean condition not supported", level = "ir"}
"failing_tests/conditionals/struct_value.py" = {reason = "A struct value has no truth value (C rejects `if (s)`): a compile error naming the struct", level = "ir"}
"failing_tests/conditionals/oneline.py" = {reason = "A conditional expression used as a statement (`f() if c else g()`) is not lowered: a compile error rather than silently dropping both calls; write it as an if statement", level = "ir"}
"failing_tests/return_struct.py" = {reason = "Returning a struct value from an integer function is a type error (nothing to dereference to an integer)", level = "ir"}
@ -26,7 +28,6 @@
"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"}
@ -44,6 +45,8 @@
"failing_tests/loops/range_variable_step.py" = {reason = "range() step must be an integer literal: its sign decides the loop test", level = "ir"}
"failing_tests/loops/range_step_too_wide.py" = {reason = "range() step must fit the 64-bit counter: 2**64 truncates to 0 and never terminates", level = "ir"}
"kernel_selftest_equivalent/ringbuf/reserve_submit_discard.py" = {reason = "RingBuffer reserve/typed record/discard workflow is planned but not implemented yet", level = "ir"}
"kernel_selftest_equivalent/vmlinux/perf_skip.py" = {reason = "Nested struct field access (ctx.regs.ip) not supported; one level such as ctx.sample_period works", level = "ir"}

71
tests/test_loops_run.py Normal file
View File

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

View File

@ -19,6 +19,13 @@ from tests.framework.compiler import run_ir_generation
PASSING_DIR = Path(__file__).parent / "passing_tests"
HAVE_VMLINUX = importlib.util.find_spec("vmlinux") is not None
# The value argument of a map update is the very SSA value loaded from prev's
# slot, not merely some load of prev elsewhere in the function.
UPDATE_WITH_LOADED_PREV = (
r'(%"[^"]+") = load i64\*, i64\*\* %"prev"\n(?:.*\n)*?'
r'.*call i64 %"[^"]+"\(\{[^}]*\}\* @"count", i64\* %"[^"]+", i64\* \1, i64 0\)'
)
# path under passing_tests -> (patterns that must appear, patterns that must not)
CASES = {
"signedness/widen_unsigned.py": (
@ -74,6 +81,25 @@ CASES = {
[r'%"queue" = alloca i16', r"trunc i64 .* to i16"],
[r'%"queue" = alloca i64'],
),
# A context field into slots of every width: loaded, zero-extended,
# truncated to the slot; nothing sign-extended on the way in.
"vmlinux/ctx_field_into_slots.py": (
[
r'%"a8" = alloca i8',
r'%"b16" = alloca i16',
r'%"c32" = alloca i32',
r'%"d64" = alloca i64',
r'trunc i64 %[^\n]* to i8\n\s*store i8 [^\n]*%"a8"',
r'trunc i64 %[^\n]* to i16\n\s*store i16 [^\n]*%"b16"',
r'trunc i64 %[^\n]* to i32\n\s*store i32 [^\n]*%"c32"',
],
[r'alloca i64[^\n]*\n[^\n]*%"a8"'],
),
# c_bool: narrowing is != 0, widening is zext; never trunc to i1 or sext.
"signedness/c_bool.py": (
[r"icmp ne i64 5, 0", r"icmp ne i64 2, 0", r"icmp ne i64 7, 0", r"zext i1"],
[r"sext i1 ", r"trunc i64 [^\n]* to i1"],
),
# A bool widens with zext and an integer narrows to it by != 0, never by
# trunc; sext of an i1 would return -1 for True.
"signedness/bool_int.py": (
@ -93,17 +119,19 @@ CASES = {
[r"deref_0_not_null", r"ret i64 %"],
[r"ret i64\*"],
),
# One byte, sized from the c_int8 destination, read from the address in
# a register field.
"vmlinux/probe_read_kernel_scalar.py": (
[r'%"byte" = alloca i8', r"inttoptr i64 .* to i8\*", r"i32 1, i8\*"],
[],
# 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\)'],
),
# Both sides of each comparison are loaded before the compare; the
# pointers into the map are never compared themselves.
"assign/map_value_compare.py": (
[r"icmp eq i64 %"],
[r"icmp (eq|ne) i64\* %\S+, %"],
"vmlinux/named_arg.py": (
[UPDATE_WITH_LOADED_PREV],
[r'i64\*\* %"prev", i64 0\)'],
),
}

View File

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

View File

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