mirror of
https://github.com/varun-r-mallya/Python-BPF.git
synced 2026-12-06 01:48:35 +00:00
- `pass` is accepted as a statement, the natural body of a loop run for its side effects. - Falling off the end of a function returns 0 in the function's own return type. After `while True` that block is unreachable, but a c_int32 function still emitted `ret i64 0`, which llc rejected. - A range() step other than 1 could wrap the counter past INT64_MAX or UINT64_MAX back inside the range and loop forever. The step block now ends the loop when the distance left to stop, exact as an unsigned number, is no longer than the step. That is a normal exit, so the else-branch runs. Steps of 1 cannot overshoot and keep the plain loop, so the helper-bounded loop the verifier walks is unchanged. - A step of 2**64 or more no longer truncates to 0: it is a compile error, since it does not fit the counter. Steps from 2**63 up are emitted by their bits. - The counter's signedness folds each bound into a signed 64-bit type rather than joining the bounds alone, so only a c_uint64 bound makes it unsigned: range(-1, n) over a c_uint32 n runs 4 times, as in C with an __s64 counter.
877 lines
32 KiB
Python
877 lines
32 KiB
Python
from llvmlite import ir
|
|
import ast
|
|
import ctypes
|
|
import logging
|
|
|
|
from pythonbpf.helper import (
|
|
HelperHandlerRegistry,
|
|
)
|
|
from pythonbpf.type_deducer import ctypes_to_ir, is_ctypes, signedness
|
|
from pythonbpf.expr import (
|
|
eval_expr,
|
|
handle_expr,
|
|
convert_to_bool,
|
|
get_typed_operand,
|
|
apply_binop,
|
|
convert,
|
|
to_promoted,
|
|
canonicalise,
|
|
usual_arithmetic_conversions,
|
|
VmlinuxHandlerRegistry,
|
|
)
|
|
from pythonbpf.assign_pass import (
|
|
handle_variable_assignment,
|
|
handle_struct_field_assignment,
|
|
)
|
|
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,
|
|
)
|
|
from .function_debug_info import generate_function_debug_info
|
|
from .return_utils import handle_none_return
|
|
from .function_metadata import get_probe_string, is_global_function, infer_return_type
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
# ============================================================================
|
|
# SECTION 1: Memory Allocation
|
|
# ============================================================================
|
|
|
|
|
|
def count_temps_in_call(call_node, local_sym_tab):
|
|
"""Count the number of temporary variables needed for a function call."""
|
|
|
|
count = {}
|
|
is_helper = False
|
|
|
|
# NOTE: We exclude print calls for now
|
|
if isinstance(call_node.func, ast.Name):
|
|
if (
|
|
HelperHandlerRegistry.has_handler(call_node.func.id)
|
|
and call_node.func.id != "print"
|
|
):
|
|
is_helper = True
|
|
func_name = call_node.func.id
|
|
elif isinstance(call_node.func, ast.Attribute):
|
|
if HelperHandlerRegistry.has_handler(call_node.func.attr):
|
|
is_helper = True
|
|
func_name = call_node.func.attr
|
|
|
|
if not is_helper:
|
|
return {} # No temps needed
|
|
|
|
for arg_idx in range(len(call_node.args)):
|
|
# NOTE: Count all non-name arguments
|
|
# For struct fields, if it is being passed as an argument,
|
|
# The struct object should already exist in the local_sym_tab
|
|
arg = call_node.args[arg_idx]
|
|
if isinstance(arg, ast.Name) or (
|
|
isinstance(arg, ast.Attribute) and arg.value.id in local_sym_tab
|
|
):
|
|
continue
|
|
param_type = HelperHandlerRegistry.get_param_type(func_name, arg_idx)
|
|
if isinstance(param_type, ir.PointerType):
|
|
pointee_type = param_type.pointee
|
|
count[pointee_type] = count.get(pointee_type, 0) + 1
|
|
|
|
return count
|
|
|
|
|
|
def handle_block_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."""
|
|
if stmt.body:
|
|
allocate_mem(
|
|
compilation_context,
|
|
builder,
|
|
stmt.body,
|
|
func,
|
|
ret_type,
|
|
local_sym_tab,
|
|
)
|
|
if stmt.orelse:
|
|
allocate_mem(
|
|
compilation_context,
|
|
builder,
|
|
stmt.orelse,
|
|
func,
|
|
ret_type,
|
|
local_sym_tab,
|
|
)
|
|
|
|
|
|
def allocate_mem(compilation_context, builder, body, func, ret_type, local_sym_tab):
|
|
max_temps_needed = {}
|
|
|
|
def merge_type_counts(count_dict):
|
|
nonlocal max_temps_needed
|
|
for typ, cnt in count_dict.items():
|
|
max_temps_needed[typ] = max(max_temps_needed.get(typ, 0), cnt)
|
|
|
|
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))
|
|
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):
|
|
if isinstance(node, ast.Call):
|
|
call_temps = count_temps_in_call(node, local_sym_tab)
|
|
for typ, cnt in call_temps.items():
|
|
stmt_temps[typ] = stmt_temps.get(typ, 0) + cnt
|
|
merge_type_counts(stmt_temps)
|
|
|
|
for stmt in body:
|
|
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(
|
|
compilation_context,
|
|
builder,
|
|
stmt,
|
|
func,
|
|
ret_type,
|
|
local_sym_tab,
|
|
)
|
|
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)
|
|
|
|
return local_sym_tab
|
|
|
|
|
|
# ============================================================================
|
|
# SECTION 2: Statement Handlers
|
|
# ============================================================================
|
|
|
|
|
|
def handle_assign(func, compilation_context, builder, stmt, local_sym_tab):
|
|
"""Handle assignment statements in the function body."""
|
|
|
|
# NOTE: Support multi-target assignments (e.g.: a, b = 1, 2)
|
|
targets, rvals = create_targets_and_rvals(stmt)
|
|
|
|
for target, rval in zip(targets, rvals):
|
|
if isinstance(target, ast.Name):
|
|
# NOTE: Simple variable assignment case: x = 5
|
|
var_name = target.id
|
|
result = handle_variable_assignment(
|
|
func,
|
|
compilation_context,
|
|
builder,
|
|
var_name,
|
|
rval,
|
|
local_sym_tab,
|
|
)
|
|
if not result:
|
|
logger.error(f"Failed to handle assignment to {var_name}")
|
|
continue
|
|
|
|
if isinstance(target, ast.Attribute):
|
|
# NOTE: Struct field assignment case: pkt.field = value
|
|
handle_struct_field_assignment(
|
|
func,
|
|
compilation_context,
|
|
builder,
|
|
target,
|
|
rval,
|
|
local_sym_tab,
|
|
)
|
|
continue
|
|
|
|
# Unsupported target type
|
|
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.
|
|
|
|
No desugaring into synthetic Assign/BinOp nodes: every pass in this
|
|
compiler walks the tree the user wrote, and nodes invented mid-codegen are
|
|
invisible to the passes that already ran and carry no source locations.
|
|
Semantic agreement with `x = x op v` comes from sharing the value-level
|
|
helpers instead — the RHS goes through get_typed_operand like any other
|
|
read, and the operator table is apply_binop, the same one binary-op
|
|
evaluation uses.
|
|
"""
|
|
if isinstance(stmt.target, ast.Name):
|
|
name = stmt.target.id
|
|
# One table: a declared global is a local_sym_tab entry whose slot is
|
|
# the GlobalVariable, so it needs no separate branch.
|
|
if name in local_sym_tab:
|
|
# `x += v` reads x first, so it needs x to be bound already.
|
|
local_sym_tab[name].check_bound_at(name, stmt.lineno)
|
|
slot = local_sym_tab[name].var
|
|
slot_type = local_sym_tab[name].ir_type
|
|
if slot is None:
|
|
raise SyntaxError(
|
|
f"cannot assign to '{name}': it is the context parameter"
|
|
)
|
|
elif name in compilation_context.bpf_globals:
|
|
# `x += v` binds x as a local and reads it unbound: UnboundLocalError.
|
|
raise SyntaxError(
|
|
f"local variable '{name}' referenced before assignment; "
|
|
f"add 'global {name}' to update the @bpfglobal"
|
|
)
|
|
else:
|
|
raise SyntaxError(f"augmented assignment to undefined variable '{name}'")
|
|
elif isinstance(stmt.target, ast.Attribute) and isinstance(
|
|
stmt.target.value, ast.Name
|
|
):
|
|
# NOTE: one level of struct dereference only (`obj.field += v`). A
|
|
# nested target (`obj.inner.field += v`) has an Attribute, not a Name,
|
|
# as its value and is rejected below; supporting it means walking the
|
|
# chain of gep()s, which plain assignment does not do either.
|
|
var_name, field_name = stmt.target.value.id, stmt.target.attr
|
|
if var_name not in local_sym_tab:
|
|
raise SyntaxError(
|
|
f"augmented assignment to field of undefined variable '{var_name}'"
|
|
)
|
|
metadata = local_sym_tab[var_name].metadata
|
|
structs_sym_tab = compilation_context.structs_sym_tab
|
|
if metadata not in structs_sym_tab:
|
|
raise SyntaxError(
|
|
f"augmented assignment to '{var_name}.{field_name}' is only "
|
|
f"supported for struct fields"
|
|
)
|
|
struct_info = structs_sym_tab[metadata]
|
|
if field_name not in struct_info.fields:
|
|
raise SyntaxError(f"Field '{field_name}' not found in struct '{metadata}'")
|
|
slot = struct_info.gep(builder, local_sym_tab[var_name].var, field_name)
|
|
slot_type = struct_info.field_type(field_name)
|
|
elif isinstance(stmt.target, ast.Attribute):
|
|
raise SyntaxError(
|
|
f"augmented assignment to a nested struct field "
|
|
f"('...{stmt.target.attr}') is not supported yet; only one level "
|
|
f"of dereference (obj.field) works so far"
|
|
)
|
|
else:
|
|
raise SyntaxError(
|
|
f"Unsupported augmented-assignment target: {ast.dump(stmt.target)}"
|
|
)
|
|
|
|
if not isinstance(slot_type, ir.IntType):
|
|
raise SyntaxError(
|
|
f"augmented assignment needs an integer target, got {slot_type}"
|
|
)
|
|
|
|
# Python evaluates the target's current value before the right-hand side.
|
|
current = builder.load(slot)
|
|
rhs, rhs_ty = get_typed_operand(
|
|
func, compilation_context, stmt.value, builder, local_sym_tab
|
|
)
|
|
if rhs is None:
|
|
raise SyntaxError(
|
|
f"Failed to evaluate augmented-assignment value: {ast.dump(stmt.value)}"
|
|
)
|
|
# x op= v is typed exactly like x = x op v: operate in the promoted type,
|
|
# then convert the result to the target's type on the way back in.
|
|
result_ty = usual_arithmetic_conversions(slot_type, rhs_ty)
|
|
current = to_promoted(builder, current, slot_type, result_ty)
|
|
rhs = to_promoted(builder, rhs, rhs_ty, result_ty)
|
|
result = canonicalise(
|
|
builder,
|
|
apply_binop(builder, stmt.op, current, rhs, signedness(result_ty)),
|
|
result_ty,
|
|
)
|
|
builder.store(convert(builder, result, result_ty, slot_type), slot)
|
|
|
|
|
|
def handle_cond(func, compilation_context, builder, cond, local_sym_tab):
|
|
val = eval_expr(func, compilation_context, builder, cond, local_sym_tab)[0]
|
|
return convert_to_bool(builder, val)
|
|
|
|
|
|
def handle_if(func, compilation_context, builder, stmt, local_sym_tab, ret_type):
|
|
"""Handle if statements in the function body."""
|
|
logger.info("Handling if statement")
|
|
# start = builder.block.parent
|
|
then_block = func.append_basic_block(name="if.then")
|
|
merge_block = func.append_basic_block(name="if.end")
|
|
if stmt.orelse:
|
|
else_block = func.append_basic_block(name="if.else")
|
|
else:
|
|
else_block = None
|
|
|
|
cond = handle_cond(func, compilation_context, builder, stmt.test, local_sym_tab)
|
|
if else_block:
|
|
builder.cbranch(cond, then_block, else_block)
|
|
else:
|
|
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
|
|
)
|
|
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
|
|
)
|
|
if not builder.block.is_terminated:
|
|
builder.branch(merge_block)
|
|
|
|
builder.position_at_end(merge_block)
|
|
|
|
|
|
def _lower_loop(
|
|
func,
|
|
compilation_context,
|
|
builder,
|
|
stmt,
|
|
local_sym_tab,
|
|
ret_type,
|
|
body_block,
|
|
continue_block,
|
|
end_block,
|
|
else_block,
|
|
):
|
|
"""What for and while share once their header is emitted: the body, with
|
|
`continue` and `break` bound to this loop, falling through to
|
|
continue_block; then the else-branch, which runs only when the loop ends
|
|
without a break, so it sits between the exit test and end_block."""
|
|
builder.position_at_end(body_block)
|
|
compilation_context.loop_stack.append((continue_block, end_block))
|
|
try:
|
|
process_block(
|
|
func, compilation_context, builder, stmt.body, local_sym_tab, ret_type
|
|
)
|
|
finally:
|
|
compilation_context.loop_stack.pop()
|
|
if not builder.block.is_terminated:
|
|
builder.branch(continue_block)
|
|
|
|
if else_block is not None:
|
|
# Outside this loop's scope: a break here leaves the enclosing loop.
|
|
builder.position_at_end(else_block)
|
|
process_block(
|
|
func, compilation_context, builder, stmt.orelse, local_sym_tab, ret_type
|
|
)
|
|
if not builder.block.is_terminated:
|
|
builder.branch(end_block)
|
|
|
|
builder.position_at_end(end_block)
|
|
|
|
|
|
def handle_while(func, compilation_context, builder, stmt, local_sym_tab, ret_type):
|
|
"""Handle `while test: body [else: orelse]`. The test is re-evaluated at
|
|
the top of every iteration, and is where `continue` goes."""
|
|
cond_block = func.append_basic_block(name="while.cond")
|
|
body_block = func.append_basic_block(name="while.body")
|
|
else_block = func.append_basic_block(name="while.else") if stmt.orelse else None
|
|
end_block = func.append_basic_block(name="while.end")
|
|
|
|
builder.branch(cond_block)
|
|
builder.position_at_end(cond_block)
|
|
cond = handle_cond(func, compilation_context, builder, stmt.test, local_sym_tab)
|
|
builder.cbranch(cond, body_block, else_block or end_block)
|
|
|
|
_lower_loop(
|
|
func,
|
|
compilation_context,
|
|
builder,
|
|
stmt,
|
|
local_sym_tab,
|
|
ret_type,
|
|
body_block,
|
|
cond_block,
|
|
end_block,
|
|
else_block,
|
|
)
|
|
|
|
|
|
def handle_for(func, compilation_context, builder, stmt, local_sym_tab, ret_type):
|
|
"""Handle `for name in range(...): body [else: orelse]`.
|
|
|
|
The allocation pass made a hidden induction counter (typed from the
|
|
bounds) next to the loop variable. The bounds are evaluated once, before
|
|
the loop, as Python does; each iteration copies the counter into the loop
|
|
variable, and `continue` goes to the step, not straight back to the test.
|
|
"""
|
|
start, stop, step = parse_range(stmt)
|
|
counter = local_sym_tab[range_counter_name(stmt)]
|
|
loop_ty = counter.ir_type
|
|
|
|
def bound(expr):
|
|
val, ty = get_typed_operand(
|
|
func, compilation_context, expr, builder, local_sym_tab
|
|
)
|
|
if val is None or not isinstance(ty, ir.IntType):
|
|
raise SyntaxError(
|
|
f"range() bound on line {stmt.lineno} must be an integer: "
|
|
f"{ast.unparse(expr)}"
|
|
)
|
|
return convert(builder, val, ty, loop_ty)
|
|
|
|
start_val = ir.Constant(loop_ty, 0) if start is None else bound(start)
|
|
stop_val = bound(stop)
|
|
builder.store(start_val, counter.var)
|
|
|
|
target = local_sym_tab[stmt.target.id]
|
|
if target.var is None:
|
|
raise SyntaxError(
|
|
f"cannot use '{stmt.target.id}' as a loop variable: it is the "
|
|
f"context parameter"
|
|
)
|
|
|
|
cond_block = func.append_basic_block(name="for.cond")
|
|
body_block = func.append_basic_block(name="for.body")
|
|
inc_block = func.append_basic_block(name="for.inc")
|
|
else_block = func.append_basic_block(name="for.else") if stmt.orelse else None
|
|
end_block = func.append_basic_block(name="for.end")
|
|
|
|
builder.branch(cond_block)
|
|
builder.position_at_end(cond_block)
|
|
idx = builder.load(counter.var)
|
|
# Counting up runs while below stop, counting down while above it.
|
|
predicate = "<" if step > 0 else ">"
|
|
compare = builder.icmp_signed if signedness(loop_ty) else builder.icmp_unsigned
|
|
builder.cbranch(
|
|
compare(predicate, idx, stop_val), body_block, else_block or end_block
|
|
)
|
|
|
|
# The loop variable is bound to the counter's value, per iteration.
|
|
builder.position_at_end(body_block)
|
|
builder.store(
|
|
convert(builder, builder.load(counter.var), loop_ty, target.ir_type),
|
|
target.var,
|
|
)
|
|
|
|
builder.position_at_end(inc_block)
|
|
idx = builder.load(counter.var)
|
|
if abs(step) > 1:
|
|
# The body only runs with the counter strictly inside the range, so
|
|
# the distance left to stop is exact as an unsigned number. A step no
|
|
# shorter than that distance ends the loop here, before the add can
|
|
# wrap the counter back inside the range (a step of 1 cannot
|
|
# overshoot stop, so it keeps the plain loop).
|
|
left = builder.sub(stop_val, idx) if step > 0 else builder.sub(idx, stop_val)
|
|
step_in_range = func.append_basic_block(name="for.step")
|
|
builder.cbranch(
|
|
builder.icmp_unsigned(">", left, ir.Constant(loop_ty, _wrap64(abs(step)))),
|
|
step_in_range,
|
|
else_block or end_block,
|
|
)
|
|
builder.position_at_end(step_in_range)
|
|
next_idx = builder.add(idx, ir.Constant(loop_ty, _wrap64(step)))
|
|
builder.store(next_idx, counter.var)
|
|
builder.branch(cond_block)
|
|
|
|
_lower_loop(
|
|
func,
|
|
compilation_context,
|
|
builder,
|
|
stmt,
|
|
local_sym_tab,
|
|
ret_type,
|
|
body_block,
|
|
inc_block,
|
|
end_block,
|
|
else_block,
|
|
)
|
|
|
|
|
|
def _wrap64(value):
|
|
"""`value` modulo 2**64, as the signed Python int LLVM parses for an i64:
|
|
a step of 2**63 or more (or its negation) is written by its bits."""
|
|
value %= 1 << 64
|
|
return value - (1 << 64) if value >= 1 << 63 else value
|
|
|
|
|
|
def handle_loop_jump(compilation_context, builder, stmt):
|
|
"""Handle `break` and `continue`: branch to the innermost loop's exit or
|
|
next-iteration block."""
|
|
keyword = "break" if isinstance(stmt, ast.Break) else "continue"
|
|
if not compilation_context.loop_stack:
|
|
raise SyntaxError(f"'{keyword}' outside loop (line {stmt.lineno})")
|
|
continue_block, break_block = compilation_context.loop_stack[-1]
|
|
builder.branch(break_block if keyword == "break" else continue_block)
|
|
|
|
|
|
def handle_return(
|
|
func, builder, stmt, local_sym_tab, ret_type, compilation_context=None
|
|
):
|
|
logger.info(f"Handling return statement: {ast.dump(stmt)}")
|
|
if stmt.value is None:
|
|
return handle_none_return(builder)
|
|
else:
|
|
# Fallback for now if ctx not passed, but caller should pass it
|
|
if compilation_context is None:
|
|
raise RuntimeError(
|
|
"CompilationContext required for return statement evaluation"
|
|
)
|
|
|
|
# A pointer to a value is dereferenced to it (null-checked), the way
|
|
# every other consumer of a value does; get_typed_operand is that path.
|
|
val = get_typed_operand(
|
|
func, compilation_context, stmt.value, builder, local_sym_tab
|
|
)
|
|
logger.info(f"Evaluated return expression to {val}")
|
|
# The declared return type is the LHS of an implicit assignment:
|
|
# widen per the value's sign, truncate if narrower.
|
|
builder.ret(convert(builder, val[0], val[1], ret_type))
|
|
return True
|
|
|
|
|
|
def process_stmt(
|
|
func,
|
|
compilation_context,
|
|
builder,
|
|
stmt,
|
|
local_sym_tab,
|
|
did_return,
|
|
ret_type=ir.IntType(64),
|
|
):
|
|
logger.info(f"Processing statement: {ast.dump(stmt)}")
|
|
# Use context scratch pool
|
|
compilation_context.scratch_pool.reset()
|
|
|
|
if isinstance(stmt, ast.Expr):
|
|
handle_expr(
|
|
func,
|
|
compilation_context,
|
|
builder,
|
|
stmt,
|
|
local_sym_tab,
|
|
)
|
|
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)
|
|
elif isinstance(stmt, ast.Pass):
|
|
pass
|
|
elif isinstance(stmt, ast.Return):
|
|
did_return = handle_return(
|
|
func, builder, stmt, local_sym_tab, ret_type, compilation_context
|
|
)
|
|
else:
|
|
# Dropping a statement makes the program mean something other than what
|
|
# it says (a loop compiles to nothing), so refuse rather than warn.
|
|
raise NotImplementedError(
|
|
f"Unsupported statement on line {getattr(stmt, 'lineno', '?')}: "
|
|
f"{type(stmt).__name__}"
|
|
)
|
|
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
|
|
# ============================================================================
|
|
|
|
|
|
def process_func_body(
|
|
compilation_context,
|
|
builder,
|
|
func_node,
|
|
func,
|
|
ret_type,
|
|
):
|
|
"""Process the body of a bpf function"""
|
|
# TODO: A lot. We just have print -> bpf_trace_printk for now
|
|
did_return = False
|
|
|
|
local_sym_tab = {}
|
|
|
|
# Add the context parameter (first function argument) to the local symbol table
|
|
if func_node.args.args and len(func_node.args.args) > 0:
|
|
context_arg = func_node.args.args[0]
|
|
context_name = context_arg.arg
|
|
|
|
if hasattr(context_arg, "annotation") and context_arg.annotation:
|
|
if isinstance(context_arg.annotation, ast.Name):
|
|
context_type_name = context_arg.annotation.id
|
|
elif isinstance(context_arg.annotation, ast.Attribute):
|
|
context_type_name = context_arg.annotation.attr
|
|
else:
|
|
raise TypeError(
|
|
f"Unsupported annotation type: {ast.dump(context_arg.annotation)}"
|
|
)
|
|
|
|
# NOTE: `var` is None for the context parameter. It is the sentinel
|
|
# that tells consumers the symbol is an incoming function argument
|
|
# (`func.args[0]`) rather than a stack slot they can load from.
|
|
if VmlinuxHandlerRegistry.is_vmlinux_struct(context_type_name):
|
|
resolved_type = VmlinuxHandlerRegistry.get_struct_type(
|
|
context_type_name
|
|
)
|
|
context_type = LocalSymbol(None, None, resolved_type)
|
|
local_sym_tab[context_name] = context_type
|
|
logger.info(f"Added argument '{context_name}' to local symbol table")
|
|
elif is_ctypes(context_type_name):
|
|
# Plain ctypes annotation, e.g. `ctx: c_void_p`. Register it so
|
|
# helpers that take the raw context (probe_read, ...) can resolve
|
|
# the name. Metadata is the annotated Python type, mirroring the
|
|
# vmlinux branch above.
|
|
context_type = LocalSymbol(
|
|
None,
|
|
ir.PointerType(),
|
|
getattr(ctypes, context_type_name, None),
|
|
)
|
|
local_sym_tab[context_name] = context_type
|
|
logger.info(f"Added argument '{context_name}' to local symbol table")
|
|
|
|
# A `global x` statement binds x in this function's scope to the
|
|
# @bpfglobal's storage. It goes into local_sym_tab like any other name,
|
|
# flagged, so every read and write resolves it through the one table with
|
|
# no separate lookup order to get wrong. Python's rules apply: a parameter
|
|
# cannot be declared global, and the name must be a @bpfglobal.
|
|
first_use = {}
|
|
for node in ast.walk(func_node):
|
|
if isinstance(node, ast.Name):
|
|
first_use[node.id] = min(first_use.get(node.id, node.lineno), node.lineno)
|
|
|
|
for node in ast.walk(func_node):
|
|
if isinstance(node, ast.Global):
|
|
for gname in node.names:
|
|
if gname in local_sym_tab:
|
|
raise SyntaxError(f"name '{gname}' is parameter and global")
|
|
# Python reads the declaration as covering the whole body, and
|
|
# rejects a body that used the name before saying so, because
|
|
# the two readings of the earlier line disagree.
|
|
if first_use.get(gname, node.lineno) < node.lineno:
|
|
raise SyntaxError(
|
|
f"name '{gname}' is used prior to global declaration"
|
|
)
|
|
if gname not in compilation_context.bpf_globals:
|
|
raise SyntaxError(
|
|
f"'global {gname}' in '{func_node.name}': no @bpfglobal "
|
|
f"named '{gname}' is declared"
|
|
)
|
|
sym = compilation_context.bpf_globals[gname]
|
|
local_sym_tab[gname] = LocalSymbol(
|
|
sym.var, sym.ir_type, None, declared_global=True
|
|
)
|
|
|
|
# pre-allocate dynamic variables
|
|
local_sym_tab = allocate_mem(
|
|
compilation_context,
|
|
builder,
|
|
func_node.body,
|
|
func,
|
|
ret_type,
|
|
local_sym_tab,
|
|
)
|
|
|
|
logger.info(f"Local symbol table: {local_sym_tab.keys()}")
|
|
|
|
for stmt in func_node.body:
|
|
did_return = process_stmt(
|
|
func,
|
|
compilation_context,
|
|
builder,
|
|
stmt,
|
|
local_sym_tab,
|
|
did_return,
|
|
ret_type,
|
|
)
|
|
|
|
if not did_return:
|
|
# Falling off the end returns 0, in the function's own return type:
|
|
# after `while True` this block is unreachable, but it still has to
|
|
# type-check.
|
|
default_ty = ret_type if isinstance(ret_type, ir.IntType) else ir.IntType(64)
|
|
builder.ret(ir.Constant(default_ty, 0))
|
|
|
|
|
|
def process_bpf_chunk(func_node, compilation_context, return_type):
|
|
"""Process a single BPF chunk (function) and emit corresponding LLVM IR."""
|
|
|
|
# Set current function in context (optional but good for future)
|
|
compilation_context.current_func = func_node
|
|
|
|
func_name = func_node.name
|
|
|
|
ret_type = return_type
|
|
|
|
# TODO: parse parameters
|
|
param_types = []
|
|
if func_node.args.args:
|
|
# Assume first arg to be ctx
|
|
param_types.append(ir.PointerType())
|
|
|
|
func_ty = ir.FunctionType(ret_type, param_types)
|
|
func = ir.Function(compilation_context.module, func_ty, func_name)
|
|
|
|
func.linkage = "dso_local"
|
|
func.attributes.add("nounwind")
|
|
func.attributes.add("noinline")
|
|
# func.attributes.add("optnone")
|
|
|
|
if func_node.args.args:
|
|
# Only look at the first argument for now
|
|
param = func.args[0]
|
|
param.add_attribute("captures(none)")
|
|
|
|
probe_string = get_probe_string(func_node)
|
|
if probe_string is not None:
|
|
func.section = probe_string
|
|
|
|
block = func.append_basic_block(name="entry")
|
|
builder = ir.IRBuilder(block)
|
|
|
|
process_func_body(
|
|
compilation_context,
|
|
builder,
|
|
func_node,
|
|
func,
|
|
ret_type,
|
|
)
|
|
return func
|
|
|
|
|
|
# ============================================================================
|
|
# SECTION 4: Top-Level Function Processor
|
|
# ============================================================================
|
|
|
|
|
|
def func_proc(tree, compilation_context, chunks):
|
|
"""Process all functions decorated with @bpf and @bpfglobal"""
|
|
for func_node in chunks:
|
|
# Ignore structs and maps
|
|
# Check against the lists
|
|
if (
|
|
func_node.name in compilation_context.structs_sym_tab
|
|
or func_node.name in compilation_context.map_sym_tab
|
|
):
|
|
continue
|
|
|
|
# Also check decorators to be sure
|
|
decorators = [d.id for d in func_node.decorator_list if isinstance(d, ast.Name)]
|
|
if "struct" in decorators or "map" in decorators:
|
|
continue
|
|
|
|
if is_global_function(func_node):
|
|
continue
|
|
func_type = get_probe_string(func_node)
|
|
logger.info(f"Found probe_string of {func_node.name}: {func_type}")
|
|
|
|
return_type = ctypes_to_ir(infer_return_type(func_node))
|
|
func = process_bpf_chunk(func_node, compilation_context, return_type)
|
|
|
|
logger.info(f"Generating Debug Info for Function {func_node.name}")
|
|
generate_function_debug_info(func_node, compilation_context.module, func)
|
|
|
|
|
|
# TODO: WIP, for string assignment to fixed-size arrays
|
|
def assign_string_to_array(builder, target_array_ptr, source_string_ptr, array_length):
|
|
"""
|
|
Copy a string (i8*) to a fixed-size array ([N x i8]*)
|
|
"""
|
|
# Create a loop to copy characters one by one
|
|
# entry_block = builder.block
|
|
copy_block = builder.append_basic_block("copy_char")
|
|
end_block = builder.append_basic_block("copy_end")
|
|
|
|
# Create loop counter
|
|
i = builder.alloca(ir.IntType(32))
|
|
builder.store(ir.Constant(ir.IntType(32), 0), i)
|
|
|
|
# Start the loop
|
|
builder.branch(copy_block)
|
|
|
|
# Copy loop
|
|
builder.position_at_end(copy_block)
|
|
idx = builder.load(i)
|
|
in_bounds = builder.icmp_unsigned(
|
|
"<", idx, ir.Constant(ir.IntType(32), array_length)
|
|
)
|
|
builder.cbranch(in_bounds, copy_block, end_block)
|
|
|
|
with builder.if_then(in_bounds):
|
|
# Load character from source
|
|
src_ptr = builder.gep(source_string_ptr, [idx])
|
|
char = builder.load(src_ptr)
|
|
|
|
# Store character in target
|
|
dst_ptr = builder.gep(target_array_ptr, [ir.Constant(ir.IntType(32), 0), idx])
|
|
builder.store(char, dst_ptr)
|
|
|
|
# Increment counter
|
|
next_idx = builder.add(idx, ir.Constant(ir.IntType(32), 1))
|
|
builder.store(next_idx, i)
|
|
|
|
builder.position_at_end(end_block)
|
|
|
|
# Ensure null termination
|
|
last_idx = ir.Constant(ir.IntType(32), array_length - 1)
|
|
null_ptr = builder.gep(target_array_ptr, [ir.Constant(ir.IntType(32), 0), last_idx])
|
|
builder.store(ir.Constant(ir.IntType(8), 0), null_ptr)
|