mirror of
https://github.com/varun-r-mallya/Python-BPF.git
synced 2026-12-06 09:58:34 +00:00
Compare commits
11 Commits
feat/bpfsn
...
fix/packet
| Author | SHA1 | Date | |
|---|---|---|---|
| aa612a4151 | |||
| 4cb5f01374 | |||
| 4662fe63b5 | |||
| a5eeaafdf3 | |||
| 20a1e2f3a1 | |||
| 4e8f767e6d | |||
| d3fa7d7e42 | |||
| db894087a2 | |||
| b9b582a7d8 | |||
| 6a859ac0cd | |||
| fab456b83d |
@ -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
|
||||
@ -6,9 +6,16 @@ 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,
|
||||
PktPtrTy,
|
||||
)
|
||||
from pythonbpf.expr.packet_pointer import packet_type
|
||||
from pythonbpf.expr.type_inference import infer_int_type
|
||||
from pythonbpf.expr.operators import usual_arithmetic_conversions
|
||||
from pythonbpf.maps import BPFMapType
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@ -50,223 +57,57 @@ def handle_assign_allocation(compilation_context, builder, stmt, local_sym_tab):
|
||||
)
|
||||
continue
|
||||
|
||||
_bind_name(
|
||||
compilation_context,
|
||||
stmt,
|
||||
target,
|
||||
local_sym_tab,
|
||||
lambda var_name: _allocate_for_value(
|
||||
var_name = target.id
|
||||
|
||||
# Already bound in this scope: a parameter, an earlier assignment, or a
|
||||
# `global` declaration (whose slot is the GlobalVariable). No slot needed.
|
||||
if var_name in local_sym_tab:
|
||||
logger.debug(f"'{var_name}' already bound, no allocation needed")
|
||||
continue
|
||||
|
||||
# Not declared `global`, yet named like one: Python creates a local
|
||||
# that shadows the global for the whole function body, and leaves the
|
||||
# global untouched. Do the same.
|
||||
shadows_global = var_name in compilation_context.bpf_globals
|
||||
if shadows_global:
|
||||
logger.info(
|
||||
f"'{var_name}' is assigned without a 'global' declaration, so it "
|
||||
f"is a local shadowing the @bpfglobal of the same name"
|
||||
)
|
||||
|
||||
# Determine type and allocate based on rval
|
||||
if isinstance(rval, ast.Call):
|
||||
_allocate_for_call(
|
||||
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 handle_ann_assign_allocation(compilation_context, builder, stmt, local_sym_tab):
|
||||
"""Handle memory allocation for annotated assignment (`x: c_int32 = 0`).
|
||||
|
||||
The annotation, not the value, types the slot: `x: c_int32 = 0` is an i32
|
||||
even though the literal alone would give an i64. With no value
|
||||
(`x: c_int64`) the slot is still made, and the name stays unbound until
|
||||
something assigns it, as in Python.
|
||||
"""
|
||||
logger.info(f"Handling annotated assignment for allocation: {ast.dump(stmt)}")
|
||||
|
||||
if not isinstance(stmt.target, ast.Name):
|
||||
raise SyntaxError(
|
||||
f"annotated assignment on line {stmt.lineno} must target a plain "
|
||||
f"name, got {type(stmt.target).__name__}"
|
||||
)
|
||||
|
||||
ir_type = annotation_to_ir(stmt.annotation, stmt.lineno)
|
||||
_bind_name(
|
||||
compilation_context,
|
||||
stmt,
|
||||
stmt.target,
|
||||
local_sym_tab,
|
||||
lambda var_name: local_sym_tab.__setitem__(
|
||||
var_name,
|
||||
LocalSymbol(_allocate_with_type(builder, var_name, ir_type), ir_type),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def handle_for_allocation(compilation_context, builder, stmt, local_sym_tab):
|
||||
"""Handle memory allocation for `for <name> in range(...)`.
|
||||
|
||||
Two slots, both in the entry block so a loop never grows the stack: the
|
||||
loop variable, and a hidden induction counter the loop actually steps.
|
||||
Keeping them apart is what makes rebinding the loop variable in the body
|
||||
leave the trip count alone, as in Python -- and a counter the body cannot
|
||||
touch is what keeps the loop visibly bounded for the verifier.
|
||||
"""
|
||||
start, stop, step = parse_range(stmt)
|
||||
|
||||
# range() yields Python ints; like any undeclared local they are 64-bit,
|
||||
# signed unless the bounds make C's arithmetic unsigned.
|
||||
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 = bound_types[0]
|
||||
for ty in bound_types[1:]:
|
||||
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})")
|
||||
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__}"
|
||||
)
|
||||
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_call(builder, var_name, rval, local_sym_tab, compilation_context):
|
||||
@ -282,7 +123,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}")
|
||||
|
||||
@ -468,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)
|
||||
if inferred is None:
|
||||
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.align = 8
|
||||
local_sym_tab[var_name] = LocalSymbol(var, ir_type)
|
||||
@ -568,6 +412,13 @@ def _allocate_for_attribute(
|
||||
# Same discriminator handle_vmlinux_struct_field uses: a context
|
||||
# argument has no alloca of its own.
|
||||
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):
|
||||
logger.error(
|
||||
f"Field '{field_name}' not found in vmlinux struct '{vmlinux_struct_name}'"
|
||||
@ -639,7 +490,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 +545,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
|
||||
|
||||
@ -82,12 +82,7 @@ class CompilationContext:
|
||||
# Current function context (optional, if needed globally during function processing)
|
||||
self.current_func = None
|
||||
|
||||
# Enclosing loops of the statement being lowered, innermost last, as
|
||||
# (continue target, break target) blocks.
|
||||
self.loop_stack: list[tuple[ir.Block, ir.Block]] = []
|
||||
|
||||
def reset(self):
|
||||
"""Reset state between functions if necessary, though new context per compile is preferred."""
|
||||
self.scratch_pool.reset()
|
||||
self.current_func = None
|
||||
self.loop_stack = []
|
||||
|
||||
@ -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):
|
||||
|
||||
@ -9,6 +9,7 @@ from pythonbpf.type_deducer import (
|
||||
field_int_type,
|
||||
is_ctypes,
|
||||
IntTy,
|
||||
PktPtrTy,
|
||||
int_literal_type,
|
||||
signedness,
|
||||
)
|
||||
@ -24,6 +25,7 @@ from .type_normalization import (
|
||||
get_base_type_and_depth,
|
||||
)
|
||||
from .vmlinux_registry import VmlinuxHandlerRegistry
|
||||
from .packet_pointer import MAX_PACKET_OFF, packet_type
|
||||
from ..vmlinux_parser.dependency_node import Field
|
||||
|
||||
logger: Logger = logging.getLogger(__name__)
|
||||
@ -122,6 +124,11 @@ def _handle_attribute_expr(
|
||||
expr, local_sym_tab, None, builder
|
||||
)
|
||||
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
|
||||
else:
|
||||
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
|
||||
descriptor (an IntTy, a vmlinux Field, or plain -> signed). None when the
|
||||
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):
|
||||
return IntTy(ty.width, signedness(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(
|
||||
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)
|
||||
logger.info(
|
||||
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
|
||||
|
||||
|
||||
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(
|
||||
func,
|
||||
compilation_context,
|
||||
@ -383,57 +440,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,
|
||||
@ -456,6 +468,13 @@ def _handle_compare(func, compilation_context, builder, cond, local_sym_tab):
|
||||
lhs, lhs_ty = lhs
|
||||
rhs, rhs_ty = rhs
|
||||
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:
|
||||
# Both integers: compare in the promoted type, which also picks the
|
||||
# signed or unsigned predicate (u64 > s64 is an unsigned compare in C).
|
||||
|
||||
68
pythonbpf/expr/packet_pointer.py
Normal file
68
pythonbpf/expr/packet_pointer.py
Normal 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
|
||||
@ -13,6 +13,7 @@ import ctypes
|
||||
from llvmlite import ir
|
||||
|
||||
from pythonbpf.type_deducer import (
|
||||
PktPtrTy,
|
||||
IntTy,
|
||||
ctypes_to_ir,
|
||||
is_ctypes,
|
||||
@ -21,9 +22,12 @@ from pythonbpf.type_deducer import (
|
||||
)
|
||||
from .operators import usual_arithmetic_conversions
|
||||
from .vmlinux_registry import VmlinuxHandlerRegistry
|
||||
from .packet_pointer import packet_type
|
||||
|
||||
|
||||
def _as_intty(ty):
|
||||
if isinstance(ty, PktPtrTy):
|
||||
return ty
|
||||
if isinstance(ty, ir.IntType):
|
||||
return IntTy(ty.width, signedness(ty))
|
||||
return None
|
||||
@ -48,6 +52,10 @@ def infer_int_type(expr, local_sym_tab, compilation_context):
|
||||
if isinstance(expr, ast.BinOp):
|
||||
left = infer_int_type(expr.left, 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:
|
||||
return None
|
||||
return usual_arithmetic_conversions(left, right)
|
||||
@ -83,6 +91,9 @@ def infer_int_type(expr, local_sym_tab, compilation_context):
|
||||
return None
|
||||
|
||||
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)
|
||||
if base is None:
|
||||
return None
|
||||
|
||||
@ -25,10 +25,6 @@ from pythonbpf.assign_pass import (
|
||||
)
|
||||
from pythonbpf.allocation_pass import (
|
||||
handle_assign_allocation,
|
||||
handle_ann_assign_allocation,
|
||||
handle_for_allocation,
|
||||
parse_range,
|
||||
range_counter_name,
|
||||
allocate_temp_pool,
|
||||
create_targets_and_rvals,
|
||||
LocalSymbol,
|
||||
@ -85,11 +81,10 @@ def count_temps_in_call(call_node, local_sym_tab):
|
||||
return count
|
||||
|
||||
|
||||
def handle_block_allocation(
|
||||
def handle_if_allocation(
|
||||
compilation_context, builder, stmt, func, ret_type, local_sym_tab
|
||||
):
|
||||
"""Recursively handle allocations in the body and else-branch of an
|
||||
if, for or while statement."""
|
||||
"""Recursively handle allocations in if/else branches."""
|
||||
if stmt.body:
|
||||
allocate_mem(
|
||||
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):
|
||||
nonlocal max_temps_needed
|
||||
|
||||
if isinstance(stmt, (ast.If, ast.For, ast.While)):
|
||||
# A loop header is evaluated like a statement of its own: range()
|
||||
# bounds once before the loop, a while test on every iteration.
|
||||
header = {ast.For: "iter", ast.While: "test"}.get(type(stmt))
|
||||
if header is not None:
|
||||
count_temps_in_tree(getattr(stmt, header))
|
||||
if isinstance(stmt, ast.If):
|
||||
for s in stmt.body:
|
||||
update_max_temps_for_stmt(s)
|
||||
for s in stmt.orelse:
|
||||
update_max_temps_for_stmt(s)
|
||||
return
|
||||
|
||||
count_temps_in_tree(stmt)
|
||||
|
||||
def count_temps_in_tree(tree):
|
||||
stmt_temps = {}
|
||||
for node in ast.walk(tree):
|
||||
for node in ast.walk(stmt):
|
||||
if isinstance(node, ast.Call):
|
||||
call_temps = count_temps_in_call(node, local_sym_tab)
|
||||
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)
|
||||
|
||||
# Handle allocations
|
||||
if isinstance(stmt, ast.For):
|
||||
handle_for_allocation(compilation_context, builder, stmt, local_sym_tab)
|
||||
if isinstance(stmt, (ast.If, ast.For, ast.While)):
|
||||
handle_block_allocation(
|
||||
if isinstance(stmt, ast.If):
|
||||
handle_if_allocation(
|
||||
compilation_context,
|
||||
builder,
|
||||
stmt,
|
||||
@ -161,10 +146,6 @@ def allocate_mem(compilation_context, builder, body, func, ret_type, local_sym_t
|
||||
)
|
||||
elif isinstance(stmt, ast.Assign):
|
||||
handle_assign_allocation(compilation_context, builder, stmt, local_sym_tab)
|
||||
elif isinstance(stmt, ast.AnnAssign):
|
||||
handle_ann_assign_allocation(
|
||||
compilation_context, builder, stmt, local_sym_tab
|
||||
)
|
||||
|
||||
allocate_temp_pool(builder, max_temps_needed, local_sym_tab)
|
||||
|
||||
@ -214,24 +195,6 @@ def handle_assign(func, compilation_context, builder, stmt, local_sym_tab):
|
||||
logger.error(f"Unsupported assignment target: {ast.dump(target)}")
|
||||
|
||||
|
||||
def handle_ann_assign(func, compilation_context, builder, stmt, local_sym_tab):
|
||||
"""Handle `x: T = v`. The allocation pass already made x's slot with the
|
||||
annotated type, so what is left is an ordinary store of v into it, through
|
||||
the same helper plain assignment uses (which converts v to the slot's type).
|
||||
A bare `x: T` binds nothing and emits nothing."""
|
||||
if stmt.value is None:
|
||||
return
|
||||
if not handle_variable_assignment(
|
||||
func,
|
||||
compilation_context,
|
||||
builder,
|
||||
stmt.target.id,
|
||||
stmt.value,
|
||||
local_sym_tab,
|
||||
):
|
||||
logger.error(f"Failed to handle annotated assignment to {stmt.target.id}")
|
||||
|
||||
|
||||
def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab):
|
||||
"""Handle `x += v` and friends by direct lowering: resolve the target's
|
||||
slot, load it, apply the operator, store back.
|
||||
@ -332,7 +295,7 @@ def handle_cond(func, compilation_context, builder, cond, local_sym_tab):
|
||||
return convert_to_bool(builder, val)
|
||||
|
||||
|
||||
def handle_if(func, compilation_context, builder, stmt, local_sym_tab, ret_type):
|
||||
def handle_if(func, compilation_context, builder, stmt, local_sym_tab):
|
||||
"""Handle if statements in the function body."""
|
||||
logger.info("Handling if statement")
|
||||
# start = builder.block.parent
|
||||
@ -350,175 +313,28 @@ def handle_if(func, compilation_context, builder, stmt, local_sym_tab, ret_type)
|
||||
builder.cbranch(cond, then_block, merge_block)
|
||||
|
||||
builder.position_at_end(then_block)
|
||||
process_block(
|
||||
func, compilation_context, builder, stmt.body, local_sym_tab, ret_type
|
||||
)
|
||||
for s in stmt.body:
|
||||
process_stmt(func, compilation_context, builder, s, local_sym_tab, False)
|
||||
if not builder.block.is_terminated:
|
||||
builder.branch(merge_block)
|
||||
|
||||
if else_block:
|
||||
builder.position_at_end(else_block)
|
||||
process_block(
|
||||
func, compilation_context, builder, stmt.orelse, local_sym_tab, ret_type
|
||||
)
|
||||
for s in stmt.orelse:
|
||||
process_stmt(
|
||||
func,
|
||||
compilation_context,
|
||||
builder,
|
||||
s,
|
||||
local_sym_tab,
|
||||
False,
|
||||
)
|
||||
if not builder.block.is_terminated:
|
||||
builder.branch(merge_block)
|
||||
|
||||
builder.position_at_end(merge_block)
|
||||
|
||||
|
||||
def _lower_loop(
|
||||
func,
|
||||
compilation_context,
|
||||
builder,
|
||||
stmt,
|
||||
local_sym_tab,
|
||||
ret_type,
|
||||
body_block,
|
||||
continue_block,
|
||||
end_block,
|
||||
else_block,
|
||||
):
|
||||
"""What for and while share once their header is emitted: the body, with
|
||||
`continue` and `break` bound to this loop, falling through to
|
||||
continue_block; then the else-branch, which runs only when the loop ends
|
||||
without a break, so it sits between the exit test and end_block."""
|
||||
builder.position_at_end(body_block)
|
||||
compilation_context.loop_stack.append((continue_block, end_block))
|
||||
try:
|
||||
process_block(
|
||||
func, compilation_context, builder, stmt.body, local_sym_tab, ret_type
|
||||
)
|
||||
finally:
|
||||
compilation_context.loop_stack.pop()
|
||||
if not builder.block.is_terminated:
|
||||
builder.branch(continue_block)
|
||||
|
||||
if else_block is not None:
|
||||
# Outside this loop's scope: a break here leaves the enclosing loop.
|
||||
builder.position_at_end(else_block)
|
||||
process_block(
|
||||
func, compilation_context, builder, stmt.orelse, local_sym_tab, ret_type
|
||||
)
|
||||
if not builder.block.is_terminated:
|
||||
builder.branch(end_block)
|
||||
|
||||
builder.position_at_end(end_block)
|
||||
|
||||
|
||||
def handle_while(func, compilation_context, builder, stmt, local_sym_tab, ret_type):
|
||||
"""Handle `while test: body [else: orelse]`. The test is re-evaluated at
|
||||
the top of every iteration, and is where `continue` goes."""
|
||||
cond_block = func.append_basic_block(name="while.cond")
|
||||
body_block = func.append_basic_block(name="while.body")
|
||||
else_block = func.append_basic_block(name="while.else") if stmt.orelse else None
|
||||
end_block = func.append_basic_block(name="while.end")
|
||||
|
||||
builder.branch(cond_block)
|
||||
builder.position_at_end(cond_block)
|
||||
cond = handle_cond(func, compilation_context, builder, stmt.test, local_sym_tab)
|
||||
builder.cbranch(cond, body_block, else_block or end_block)
|
||||
|
||||
_lower_loop(
|
||||
func,
|
||||
compilation_context,
|
||||
builder,
|
||||
stmt,
|
||||
local_sym_tab,
|
||||
ret_type,
|
||||
body_block,
|
||||
cond_block,
|
||||
end_block,
|
||||
else_block,
|
||||
)
|
||||
|
||||
|
||||
def handle_for(func, compilation_context, builder, stmt, local_sym_tab, ret_type):
|
||||
"""Handle `for name in range(...): body [else: orelse]`.
|
||||
|
||||
The allocation pass made a hidden induction counter (typed from the
|
||||
bounds) next to the loop variable. The bounds are evaluated once, before
|
||||
the loop, as Python does; each iteration copies the counter into the loop
|
||||
variable, and `continue` goes to the step, not straight back to the test.
|
||||
"""
|
||||
start, stop, step = parse_range(stmt)
|
||||
counter = local_sym_tab[range_counter_name(stmt)]
|
||||
loop_ty = counter.ir_type
|
||||
|
||||
def bound(expr):
|
||||
val, ty = get_typed_operand(
|
||||
func, compilation_context, expr, builder, local_sym_tab
|
||||
)
|
||||
if val is None or not isinstance(ty, ir.IntType):
|
||||
raise SyntaxError(
|
||||
f"range() bound on line {stmt.lineno} must be an integer: "
|
||||
f"{ast.unparse(expr)}"
|
||||
)
|
||||
return convert(builder, val, ty, loop_ty)
|
||||
|
||||
start_val = ir.Constant(loop_ty, 0) if start is None else bound(start)
|
||||
stop_val = bound(stop)
|
||||
builder.store(start_val, counter.var)
|
||||
|
||||
target = local_sym_tab[stmt.target.id]
|
||||
if target.var is None:
|
||||
raise SyntaxError(
|
||||
f"cannot use '{stmt.target.id}' as a loop variable: it is the "
|
||||
f"context parameter"
|
||||
)
|
||||
|
||||
cond_block = func.append_basic_block(name="for.cond")
|
||||
body_block = func.append_basic_block(name="for.body")
|
||||
inc_block = func.append_basic_block(name="for.inc")
|
||||
else_block = func.append_basic_block(name="for.else") if stmt.orelse else None
|
||||
end_block = func.append_basic_block(name="for.end")
|
||||
|
||||
builder.branch(cond_block)
|
||||
builder.position_at_end(cond_block)
|
||||
idx = builder.load(counter.var)
|
||||
# Counting up runs while below stop, counting down while above it.
|
||||
predicate = "<" if step > 0 else ">"
|
||||
compare = builder.icmp_signed if signedness(loop_ty) else builder.icmp_unsigned
|
||||
builder.cbranch(
|
||||
compare(predicate, idx, stop_val), body_block, else_block or end_block
|
||||
)
|
||||
|
||||
# The loop variable is bound to the counter's value, per iteration.
|
||||
builder.position_at_end(body_block)
|
||||
builder.store(
|
||||
convert(builder, builder.load(counter.var), loop_ty, target.ir_type),
|
||||
target.var,
|
||||
)
|
||||
|
||||
builder.position_at_end(inc_block)
|
||||
next_idx = builder.add(builder.load(counter.var), ir.Constant(loop_ty, 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 handle_loop_jump(compilation_context, builder, stmt):
|
||||
"""Handle `break` and `continue`: branch to the innermost loop's exit or
|
||||
next-iteration block."""
|
||||
keyword = "break" if isinstance(stmt, ast.Break) else "continue"
|
||||
if not compilation_context.loop_stack:
|
||||
raise SyntaxError(f"'{keyword}' outside loop (line {stmt.lineno})")
|
||||
continue_block, break_block = compilation_context.loop_stack[-1]
|
||||
builder.branch(break_block if keyword == "break" else continue_block)
|
||||
|
||||
|
||||
def handle_return(
|
||||
func, builder, stmt, local_sym_tab, ret_type, compilation_context=None
|
||||
):
|
||||
@ -567,20 +383,12 @@ def process_stmt(
|
||||
)
|
||||
elif isinstance(stmt, ast.Assign):
|
||||
handle_assign(func, compilation_context, builder, stmt, local_sym_tab)
|
||||
elif isinstance(stmt, ast.AnnAssign):
|
||||
handle_ann_assign(func, compilation_context, builder, stmt, local_sym_tab)
|
||||
elif isinstance(stmt, ast.AugAssign):
|
||||
handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab)
|
||||
elif isinstance(stmt, ast.Global):
|
||||
logger.debug(f"global declaration of {', '.join(stmt.names)} already bound")
|
||||
elif isinstance(stmt, ast.If):
|
||||
handle_if(func, compilation_context, builder, stmt, local_sym_tab, ret_type)
|
||||
elif isinstance(stmt, ast.While):
|
||||
handle_while(func, compilation_context, builder, stmt, local_sym_tab, ret_type)
|
||||
elif isinstance(stmt, ast.For):
|
||||
handle_for(func, compilation_context, builder, stmt, local_sym_tab, ret_type)
|
||||
elif isinstance(stmt, (ast.Break, ast.Continue)):
|
||||
handle_loop_jump(compilation_context, builder, stmt)
|
||||
handle_if(func, compilation_context, builder, stmt, local_sym_tab)
|
||||
elif isinstance(stmt, ast.Return):
|
||||
did_return = handle_return(
|
||||
func, builder, stmt, local_sym_tab, ret_type, compilation_context
|
||||
@ -595,19 +403,6 @@ def process_stmt(
|
||||
return did_return
|
||||
|
||||
|
||||
def process_block(func, compilation_context, builder, stmts, local_sym_tab, ret_type):
|
||||
"""Process a nested statement list (an if-branch or loop body). Stops at
|
||||
the first statement that ends the block -- break, continue or return --
|
||||
because whatever follows it in the same list can never run, and would
|
||||
otherwise be emitted after a terminator."""
|
||||
for s in stmts:
|
||||
if builder.block.is_terminated:
|
||||
break
|
||||
process_stmt(
|
||||
func, compilation_context, builder, s, local_sym_tab, False, ret_type
|
||||
)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# SECTION 3: Function Body Processing
|
||||
# ============================================================================
|
||||
|
||||
@ -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)
|
||||
|
||||
|
||||
@ -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",
|
||||
|
||||
@ -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(
|
||||
|
||||
@ -341,12 +341,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}")
|
||||
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -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):
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||
|
||||
@ -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
|
||||
|
||||
@ -41,6 +41,39 @@ class IntTy(ir.IntType):
|
||||
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:
|
||||
"""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 +140,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,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -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;
|
||||
}
|
||||
@ -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()
|
||||
@ -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()
|
||||
21
tests/failing_tests/vmlinux/ctx_data_end_offset.py
Normal file
21
tests/failing_tests/vmlinux/ctx_data_end_offset.py
Normal 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()
|
||||
21
tests/failing_tests/vmlinux/ctx_data_offset_too_big.py
Normal file
21
tests/failing_tests/vmlinux/ctx_data_offset_too_big.py
Normal 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()
|
||||
@ -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()
|
||||
@ -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()
|
||||
@ -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()
|
||||
@ -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()
|
||||
@ -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()
|
||||
@ -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()
|
||||
49
tests/passing_tests/signedness/c_bool.py
Normal file
49
tests/passing_tests/signedness/c_bool.py
Normal 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()
|
||||
25
tests/passing_tests/vmlinux/ctx_bounds_check.py
Normal file
25
tests/passing_tests/vmlinux/ctx_bounds_check.py
Normal 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()
|
||||
21
tests/passing_tests/vmlinux/ctx_bounds_check_direct.py
Normal file
21
tests/passing_tests/vmlinux/ctx_bounds_check_direct.py
Normal 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()
|
||||
26
tests/passing_tests/vmlinux/ctx_data_arith.py
Normal file
26
tests/passing_tests/vmlinux/ctx_data_arith.py
Normal 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()
|
||||
21
tests/passing_tests/vmlinux/ctx_data_length.py
Normal file
21
tests/passing_tests/vmlinux/ctx_data_length.py
Normal 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()
|
||||
20
tests/passing_tests/vmlinux/ctx_data_meta_offset.py
Normal file
20
tests/passing_tests/vmlinux/ctx_data_meta_offset.py
Normal 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()
|
||||
25
tests/passing_tests/vmlinux/ctx_data_narrow_store.py
Normal file
25
tests/passing_tests/vmlinux/ctx_data_narrow_store.py
Normal 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()
|
||||
21
tests/passing_tests/vmlinux/ctx_data_plus_one.py
Normal file
21
tests/passing_tests/vmlinux/ctx_data_plus_one.py
Normal 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()
|
||||
24
tests/passing_tests/vmlinux/ctx_data_runtime_offset.py
Normal file
24
tests/passing_tests/vmlinux/ctx_data_runtime_offset.py
Normal 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()
|
||||
22
tests/passing_tests/vmlinux/ctx_data_via_local.py
Normal file
22
tests/passing_tests/vmlinux/ctx_data_via_local.py
Normal 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()
|
||||
47
tests/passing_tests/vmlinux/ctx_field_into_slots.py
Normal file
47
tests/passing_tests/vmlinux/ctx_field_into_slots.py
Normal 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()
|
||||
@ -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()
|
||||
@ -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()
|
||||
@ -38,11 +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/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/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_variable_step.py" = {reason = "range() step must be an integer literal: its sign decides the loop test", 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"}
|
||||
|
||||
|
||||
@ -68,12 +68,63 @@ CASES = {
|
||||
[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
|
||||
# is truncated to 16 bits (C: __u16 queue = ctx->rx_queue_index).
|
||||
"vmlinux/ctx_field_narrow_store.py": (
|
||||
[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,18 +144,6 @@ 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\*"],
|
||||
[],
|
||||
),
|
||||
# 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+, %"],
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user