Compare commits

..

1 Commits

Author SHA1 Message Date
13538a4042 Core: Augmented assignment to a map-lookup local rebinds it, as v = v + 1 does
`v = m.lookup(k); v += 1` was rejected with "augmented assignment needs
an integer target, got i64*": the Name branch took the local's slot type,
the pointer, as the target type. `v = v + 1` already compiles, and to a
rebinding: the value is read through the pointer, null-checked, and the
local is pointed at its spare `v_tmp` slot holding the result; the map is
not written. `v += 1` now does the same. The read is get_typed_operand's,
so the operation takes the map's declared value type and sign (u64 >>= is
an lshr); the write is a rebind_map_value_local helper, now shared with
plain assignment so the two cannot drift apart. A struct-valued lookup
local is refused with a pointer to its fields.
2026-09-25 11:22:19 +05:30
10 changed files with 109 additions and 157 deletions

View File

@ -60,6 +60,10 @@ def trace_open(ctx: c_void_p) -> c_int64:
return 0 return 0
``` ```
An integer value behaves like a Python `int`: `value += 1`, like
`value = value + 1`, rebinds the local to the new number and leaves the map
unchanged. To store it, call `update`.
##### update(key, value, flags=None) ##### update(key, value, flags=None)
Update or insert a key-value pair. Update or insert a key-value pair.

View File

@ -228,14 +228,8 @@ def _allocate_for_map_method(
_allocate_for_map_method_fallback(builder, var_name, local_sym_tab) _allocate_for_map_method_fallback(builder, var_name, local_sym_tab)
return return
# Main variable (pointer to pointer). An integer value is pointed at with # Main variable (pointer to pointer)
# its own width, so that reads and writes through it are value-sized: the ir_type = ir.PointerType(ir.IntType(64))
# verifier rejects an 8-byte access to a 4-byte map value. A struct value
# keeps the generic i64*; field access casts it to the struct type.
if isinstance(value_ir_type, ir.IntType):
ir_type = ir.PointerType(ir.IntType(value_ir_type.width))
else:
ir_type = ir.PointerType(ir.IntType(64))
var = builder.alloca(ir_type, name=var_name) var = builder.alloca(ir_type, name=var_name)
local_sym_tab[var_name] = LocalSymbol(var, ir_type, value_type) local_sym_tab[var_name] = LocalSymbol(var, ir_type, value_type)
# Temporary variable for computed values # Temporary variable for computed values

View File

@ -87,6 +87,24 @@ def _copy_string_to_char_array(
emit_probe_read_kernel_str_call(builder, dst_i8_ptr, array_size, src_ptr) emit_probe_read_kernel_str_call(builder, dst_i8_ptr, array_size, src_ptr)
def is_map_value_local(local_sym_tab, var_name):
"""Whether `var_name` holds a map-lookup result: a pointer to the value,
allocated with a spare `<name>_tmp` slot for values computed from it."""
return (
isinstance(local_sym_tab[var_name].ir_type, ir.PointerType)
and f"{var_name}_tmp" in local_sym_tab
)
def rebind_map_value_local(builder, local_sym_tab, var_name, val):
"""Bind a map-lookup local to a computed value, the way Python rebinds a
name: the value goes into the local's `<name>_tmp` slot and the local is
pointed at it. The map itself is not written."""
tmp = local_sym_tab[f"{var_name}_tmp"].var
builder.store(val, tmp)
builder.store(tmp, local_sym_tab[var_name].var)
def _is_char_array(ir_type): def _is_char_array(ir_type):
"""Check if type is [N x i8].""" """Check if type is [N x i8]."""
return ( return (
@ -223,27 +241,15 @@ def handle_variable_assignment(
return False return False
elif isinstance(val_type, ir.IntType) and isinstance(var_type, ir.PointerType): elif isinstance(val_type, ir.IntType) and isinstance(var_type, ir.PointerType):
# NOTE: This is assignment to a PTR_TO_MAP_VALUE_OR_NULL # NOTE: This is assignment to a PTR_TO_MAP_VALUE_OR_NULL
logger.info( rebind_map_value_local(builder, local_sym_tab, var_name, val)
f"Creating temporary variable for pointer assignment to {var_name}" logger.info(f"Rebound map-lookup local {var_name} to a computed value")
) return True
tmp = local_sym_tab[f"{var_name}_tmp"]
# The spare slot has the map value's width; expressions are i64.
builder.store(convert(builder, val, val_type, tmp.ir_type), tmp.var)
val = tmp.var
else: else:
logger.error( logger.error(
f"Type mismatch for variable {var_name}: {val_type} vs {var_type}" f"Type mismatch for variable {var_name}: {val_type} vs {var_type}"
) )
return False return False
if (
isinstance(val.type, ir.PointerType)
and isinstance(var_type, ir.PointerType)
and val.type != var_type
):
# A map lookup returns a generic pointer; the local is typed by the
# map's value, so the pointer is cast to it (no instruction in BPF).
val = builder.bitcast(val, var_type)
builder.store(val, var_ptr) builder.store(val, var_ptr)
logger.info(f"Assigned value to variable {var_name}") logger.info(f"Assigned value to variable {var_name}")
return True return True

View File

@ -1,4 +1,4 @@
from .expr_pass import eval_expr, handle_expr, get_typed_operand, holds_map_int_value from .expr_pass import eval_expr, handle_expr, get_typed_operand
from .type_normalization import ( from .type_normalization import (
convert_to_bool, convert_to_bool,
get_base_type_and_depth, get_base_type_and_depth,
@ -20,7 +20,6 @@ __all__ = [
"canonicalise", "canonicalise",
"to_promoted", "to_promoted",
"get_typed_operand", "get_typed_operand",
"holds_map_int_value",
"usual_arithmetic_conversions", "usual_arithmetic_conversions",
"get_base_type_and_depth", "get_base_type_and_depth",
"deref_to_depth", "deref_to_depth",

View File

@ -382,41 +382,25 @@ def _handle_ctypes_call(
return value, expected_type return value, expected_type
def holds_map_int_value(sym):
"""Whether a local is a lookup result on a map with an integer value: a
pointer to the value, with the value's ctype as its metadata. Such a local
is used by value, read through the pointer (see get_typed_operand)."""
return (
isinstance(sym.ir_type, ir.PointerType)
and isinstance(sym.metadata, str)
and is_ctypes(sym.metadata)
)
def _compare_operand(func, compilation_context, builder, operand, local_sym_tab):
"""Evaluate one side of a comparison. A map-lookup local compares by its
value, read at the map value's width and typed by its declared ctype,
exactly as it is read as an arithmetic operand."""
if (
isinstance(operand, ast.Name)
and operand.id in local_sym_tab
and holds_map_int_value(local_sym_tab[operand.id])
):
return get_typed_operand(
func, compilation_context, operand, builder, local_sym_tab
)
return eval_expr(func, compilation_context, builder, operand, local_sym_tab)
def _handle_compare(func, compilation_context, builder, cond, local_sym_tab): def _handle_compare(func, compilation_context, builder, cond, local_sym_tab):
"""Handle ast.Compare expressions.""" """Handle ast.Compare expressions."""
if len(cond.ops) != 1 or len(cond.comparators) != 1: if len(cond.ops) != 1 or len(cond.comparators) != 1:
logger.error("Only single comparisons are supported") logger.error("Only single comparisons are supported")
return None return None
lhs = _compare_operand(func, compilation_context, builder, cond.left, local_sym_tab) lhs = eval_expr(
rhs = _compare_operand( func,
func, compilation_context, builder, cond.comparators[0], local_sym_tab compilation_context,
builder,
cond.left,
local_sym_tab,
)
rhs = eval_expr(
func,
compilation_context,
builder,
cond.comparators[0],
local_sym_tab,
) )
if lhs is None or rhs is None: if lhs is None or rhs is None:

View File

@ -22,6 +22,8 @@ from pythonbpf.expr import (
from pythonbpf.assign_pass import ( from pythonbpf.assign_pass import (
handle_variable_assignment, handle_variable_assignment,
handle_struct_field_assignment, handle_struct_field_assignment,
is_map_value_local,
rebind_map_value_local,
) )
from pythonbpf.allocation_pass import ( from pythonbpf.allocation_pass import (
handle_assign_allocation, handle_assign_allocation,
@ -207,6 +209,9 @@ def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab):
read, and the operator table is apply_binop, the same one binary-op read, and the operator table is apply_binop, the same one binary-op
evaluation uses. evaluation uses.
""" """
# A map-lookup local reads through its pointer and is rebound, not
# written through, exactly as `v = v + 1` does it.
map_value_local = None
if isinstance(stmt.target, ast.Name): if isinstance(stmt.target, ast.Name):
name = stmt.target.id name = stmt.target.id
# One table: a declared global is a local_sym_tab entry whose slot is # One table: a declared global is a local_sym_tab entry whose slot is
@ -220,6 +225,13 @@ def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab):
raise SyntaxError( raise SyntaxError(
f"cannot assign to '{name}': it is the context parameter" f"cannot assign to '{name}': it is the context parameter"
) )
if is_map_value_local(local_sym_tab, name):
if local_sym_tab[name].metadata in compilation_context.structs_sym_tab:
raise SyntaxError(
f"augmented assignment to '{name}', a struct map value; "
f"update one of its fields instead ({name}.field += ...)"
)
map_value_local = name
elif name in compilation_context.bpf_globals: elif name in compilation_context.bpf_globals:
# `x += v` binds x as a local and reads it unbound: UnboundLocalError. # `x += v` binds x as a local and reads it unbound: UnboundLocalError.
raise SyntaxError( raise SyntaxError(
@ -263,13 +275,20 @@ def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab):
f"Unsupported augmented-assignment target: {ast.dump(stmt.target)}" f"Unsupported augmented-assignment target: {ast.dump(stmt.target)}"
) )
if not isinstance(slot_type, ir.IntType): # Python evaluates the target's current value before the right-hand side.
if map_value_local is not None:
# The null-checked read every other use of the local gets; its
# descriptor is the map's declared value type, which is also the
# type the result is stored back as.
current, slot_type = get_typed_operand(
func, compilation_context, stmt.target, builder, local_sym_tab
)
elif isinstance(slot_type, ir.IntType):
current = builder.load(slot)
else:
raise SyntaxError( raise SyntaxError(
f"augmented assignment needs an integer target, got {slot_type}" 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( rhs, rhs_ty = get_typed_operand(
func, compilation_context, stmt.value, builder, local_sym_tab func, compilation_context, stmt.value, builder, local_sym_tab
) )
@ -287,7 +306,11 @@ def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab):
apply_binop(builder, stmt.op, current, rhs, signedness(result_ty)), apply_binop(builder, stmt.op, current, rhs, signedness(result_ty)),
result_ty, result_ty,
) )
builder.store(convert(builder, result, result_ty, slot_type), slot) result = convert(builder, result, result_ty, slot_type)
if map_value_local is not None:
rebind_map_value_local(builder, local_sym_tab, map_value_local, result)
else:
builder.store(result, slot)
def handle_cond(func, compilation_context, builder, cond, local_sym_tab): def handle_cond(func, compilation_context, builder, cond, local_sym_tab):

View File

@ -2,15 +2,7 @@ import ast
import logging import logging
from llvmlite import ir from llvmlite import ir
from pythonbpf.expr import ( from pythonbpf.expr import eval_expr, get_base_type_and_depth, deref_to_depth, convert
eval_expr,
get_base_type_and_depth,
deref_to_depth,
convert,
get_typed_operand,
holds_map_int_value,
)
from pythonbpf.type_deducer import ctypes_to_ir
from pythonbpf.expr.vmlinux_registry import VmlinuxHandlerRegistry from pythonbpf.expr.vmlinux_registry import VmlinuxHandlerRegistry
from pythonbpf.helper.helper_utils import get_char_array_ptr_and_size from pythonbpf.helper.helper_utils import get_char_array_ptr_and_size
@ -115,13 +107,7 @@ def _process_name_in_fval(
): ):
"""Process name nodes in formatted values.""" """Process name nodes in formatted values."""
if local_sym_tab and name_node.id in local_sym_tab: if local_sym_tab and name_node.id in local_sym_tab:
sym = local_sym_tab[name_node.id] _, var_type, tmp = local_sym_tab[name_node.id]
# A map-lookup local prints as its value, of the map's value type;
# its pointer type alone would make a c_uint8 value look like a string.
if holds_map_int_value(sym):
var_type = ctypes_to_ir(sym.metadata)
else:
var_type = sym.ir_type
_populate_fval(var_type, name_node, fmt_parts, exprs) _populate_fval(var_type, name_node, fmt_parts, exprs)
elif name_node.id in compilation_context.bpf_globals: elif name_node.id in compilation_context.bpf_globals:
var_type = compilation_context.bpf_globals[name_node.id].ir_type var_type = compilation_context.bpf_globals[name_node.id].ir_type
@ -173,8 +159,7 @@ def _populate_fval(ftype, node, fmt_parts, exprs):
if ftype.width == 64: if ftype.width == 64:
fmt_parts.append("%lld") fmt_parts.append("%lld")
exprs.append(node) exprs.append(node)
elif ftype.width <= 32: elif ftype.width == 32:
# Narrower integers are promoted to int, as C varargs do.
fmt_parts.append("%d") fmt_parts.append("%d")
exprs.append(node) exprs.append(node)
else: else:
@ -244,18 +229,6 @@ def _prepare_expr_args(expr, func, compilation_context, builder, local_sym_tab):
if char_array_ptr: if char_array_ptr:
return char_array_ptr return char_array_ptr
# A map-lookup local: its value, widened per the map's value type
if (
isinstance(expr, ast.Name)
and local_sym_tab
and expr.id in local_sym_tab
and holds_map_int_value(local_sym_tab[expr.id])
):
val, ty = get_typed_operand(
func, compilation_context, expr, builder, local_sym_tab
)
return _handle_int_arg(val, builder, ty)
# Regular expression evaluation # Regular expression evaluation
val, _ = eval_expr(func, compilation_context, builder, expr, local_sym_tab) val, _ = eval_expr(func, compilation_context, builder, expr, local_sym_tab)

View File

@ -0,0 +1,32 @@
# Augmented assignment to a map-lookup local: `v += 1` is `v = v + 1`. It reads
# the value through the pointer (null-checked) and rebinds v to the result; the
# map itself is not written.
from pythonbpf import bpf, map, section, bpfglobal, compile
from pythonbpf.maps import HashMap
from ctypes import c_void_p, c_int64, c_uint64
@bpf
@map
def m() -> HashMap:
return HashMap(key=c_int64, value=c_uint64, max_entries=4)
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def prog(ctx: c_void_p) -> c_int64:
v = m.lookup(0)
if v:
v += 1
v >>= 1 # c_uint64 value: a logical shift
return v
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -1,56 +0,0 @@
# Map values narrower than 64 bits are read and written at their own width:
# the verifier rejects an 8-byte access to a 4-byte value. Each value is then
# widened per its declared sign -- zext for c_uint32 and c_uint8, sext for
# c_int32 -- in arithmetic, comparisons and printing alike, and a c_uint8
# value prints as a number, not as a string.
from pythonbpf import bpf, map, section, bpfglobal, compile
from pythonbpf.maps import HashMap
from ctypes import c_void_p, c_int64, c_uint32, c_int32, c_uint8
@bpf
@map
def u32s() -> HashMap:
return HashMap(key=c_uint32, value=c_uint32, max_entries=4)
@bpf
@map
def i32s() -> HashMap:
return HashMap(key=c_uint32, value=c_int32, max_entries=4)
@bpf
@map
def u8s() -> HashMap:
return HashMap(key=c_uint32, value=c_uint8, max_entries=4)
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def prog(ctx: c_void_p) -> c_int64:
k = c_uint32(0)
u = u32s.lookup(k)
i = i32s.lookup(k)
b = u8s.lookup(k)
if u:
if u == 3:
print(f"u {u}")
u32s.update(k, u + 1)
if i:
n = i - 1
print(f"i {i} n {n}")
if b:
print(f"b {b}")
b = b + 2
return b
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -81,18 +81,11 @@ CASES = {
[r"trunc i64 .* to i32", r"zext i32 .* to i64"], [r"trunc i64 .* to i32", r"zext i32 .* to i64"],
[r"sext i32 .* to i64"], [r"sext i32 .* to i64"],
), ),
# A narrow map value is loaded at its width, widened per its sign, and # `v += 1; v >>= 1` on a c_uint64 map value: read through the pointer,
# never read with an 8-byte load; a c_uint8 value is printed by value. # operate unsigned, rebind v to the lookup local's spare slot.
"signedness/map_value_narrow.py": ( "assign/augassign_map_value.py": (
[ [r"deref_1_not_null", r"\blshr i64", r"store i64\* %\"v_tmp\", i64\*\* %\"v\""],
r"load i32, i32\* %\"deref", [r"\bashr i64"],
r"load i8, i8\* %\"deref",
r"zext i32 %\"deref",
r"sext i32 %\"deref",
r"zext i8 %\"deref",
r"store i8 .*, i8\* %\"b_tmp\"",
],
[r"load i64, i64\* %\"deref", r"i8\* %\"deref[^\"]*\"\)$"],
), ),
# `return p` on a map lookup dereferences through a null check and returns # `return p` on a map lookup dereferences through a null check and returns
# the i64, never the pointer. # the i64, never the pointer.