Compare commits

..

1 Commits

Author SHA1 Message Date
aa13482191 Core: Write struct fields through a map-lookup pointer, null-checked
`s = m.lookup(k); s.count = 5` (and `s.count += 1`) compiled without an
error to IR llc rejects: "invalid getelementptr indices" on
`getelementptr inbounds i64*, i64** %s, i32 0, i32 0`. Both the
assignment and augmented-assignment paths indexed into the local's own
slot, which for a lookup or cast local holds a pointer to the struct, not
the struct. Reads already got this right in access_struct_field.

with_struct_field_ptr now resolves a field for a write the same way:
directly for a struct local; for a pointer local, by loading the pointer,
casting it to the struct type, and emitting the store only on the
non-null path (emit_if_not_null, the write-side counterpart of
_null_checked_operation). The write lands in the map entry itself, so
`s.count += 1` is an in-place update with no update() call, and the
maps/structs guide examples that did update(k, s) after a field
assignment now just assign.
2026-09-25 11:22:21 +05:30
9 changed files with 150 additions and 113 deletions

View File

@ -60,10 +60,6 @@ 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.
@ -357,8 +353,8 @@ def track_stats(ctx: c_void_p) -> c_int64:
stats = process_stats.lookup(process_id) stats = process_stats.lookup(process_id)
if stats: if stats:
stats.count = stats.count + 1 # A field assignment writes into the map entry itself
process_stats.update(process_id, stats) stats.count += 1
else: else:
new_stats = Stats() new_stats = Stats()
new_stats.count = 1 new_stats.count = 1

View File

@ -161,9 +161,8 @@ def track_syscalls(ctx: c_void_p) -> c_int64:
s = stats.lookup(process_id) s = stats.lookup(process_id)
if s: if s:
# Update existing stats # A field assignment writes into the map entry itself
s.syscall_count = s.syscall_count + 1 s.syscall_count += 1
stats.update(process_id, s)
else: else:
# Create new stats # Create new stats
new_stats = ProcessStats() new_stats = ProcessStats()

View File

@ -3,7 +3,7 @@ import logging
from inspect import isclass from inspect import isclass
from llvmlite import ir from llvmlite import ir
from pythonbpf.expr import eval_expr, convert from pythonbpf.expr import eval_expr, convert, with_struct_field_ptr
from pythonbpf.helper import emit_probe_read_kernel_str_call from pythonbpf.helper import emit_probe_read_kernel_str_call
from pythonbpf.type_deducer import ctypes_to_ir from pythonbpf.type_deducer import ctypes_to_ir
from pythonbpf.vmlinux_parser.dependency_node import Field from pythonbpf.vmlinux_parser.dependency_node import Field
@ -30,8 +30,7 @@ def handle_struct_field_assignment(
logger.error(f"Field '{field_name}' not found in struct '{struct_type}'") logger.error(f"Field '{field_name}' not found in struct '{struct_type}'")
return return
# Get field pointer and evaluate value # Python evaluates the value before the target.
field_ptr = struct_info.gep(builder, local_sym_tab[var_name].var, field_name)
field_type = struct_info.field_type(field_name) field_type = struct_info.field_type(field_name)
val_result = eval_expr(func, compilation_context, builder, rval, local_sym_tab) val_result = eval_expr(func, compilation_context, builder, rval, local_sym_tab)
@ -43,24 +42,29 @@ def handle_struct_field_assignment(
# Special case: i8* string to [N x i8] char array # Special case: i8* string to [N x i8] char array
if _is_char_array(field_type) and _is_i8_ptr(val_type): if _is_char_array(field_type) and _is_i8_ptr(val_type):
_copy_string_to_char_array(
func,
builder,
val,
field_ptr,
field_type,
local_sym_tab,
)
logger.info(f"Copied string to char array {var_name}.{field_name}")
return
# Same implicit widening/truncation as assignment to a local: expressions def store(builder, field_ptr):
# evaluate in i64, but a field may be narrower. _copy_string_to_char_array(
if isinstance(val_type, ir.IntType) and isinstance(field_type, ir.IntType): func,
val = convert(builder, val, val_type, field_type) builder,
val,
field_ptr,
field_type,
local_sym_tab,
)
# Regular assignment else:
builder.store(val, field_ptr) # Same implicit widening/truncation as assignment to a local:
# expressions evaluate in i64, but a field may be narrower.
if isinstance(val_type, ir.IntType) and isinstance(field_type, ir.IntType):
val = convert(builder, val, val_type, field_type)
def store(builder, field_ptr):
builder.store(val, field_ptr)
with_struct_field_ptr(
func, builder, local_sym_tab[var_name], struct_info, field_name, store
)
logger.info(f"Assigned to struct field {var_name}.{field_name}") logger.info(f"Assigned to struct field {var_name}.{field_name}")
@ -87,24 +91,6 @@ 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 (
@ -241,9 +227,12 @@ 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
rebind_map_value_local(builder, local_sym_tab, var_name, val) logger.info(
logger.info(f"Rebound map-lookup local {var_name} to a computed value") f"Creating temporary variable for pointer assignment to {var_name}"
return True )
var_ptr_tmp = local_sym_tab[f"{var_name}_tmp"].var
builder.store(val, var_ptr_tmp)
val = var_ptr_tmp
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}"

View File

@ -7,7 +7,7 @@ from .type_normalization import (
to_promoted, to_promoted,
) )
from .operators import usual_arithmetic_conversions from .operators import usual_arithmetic_conversions
from .ir_ops import deref_to_depth, access_struct_field from .ir_ops import deref_to_depth, access_struct_field, with_struct_field_ptr
from .operators import apply_binop from .operators import apply_binop
from .call_registry import CallHandlerRegistry from .call_registry import CallHandlerRegistry
from .vmlinux_registry import VmlinuxHandlerRegistry from .vmlinux_registry import VmlinuxHandlerRegistry
@ -25,6 +25,7 @@ __all__ = [
"deref_to_depth", "deref_to_depth",
"apply_binop", "apply_binop",
"access_struct_field", "access_struct_field",
"with_struct_field_ptr",
"CallHandlerRegistry", "CallHandlerRegistry",
"VmlinuxHandlerRegistry", "VmlinuxHandlerRegistry",
] ]

View File

@ -62,6 +62,42 @@ def _null_checked_operation(func, builder, ptr, operation, result_type, name_pre
return phi return phi
def emit_if_not_null(func, builder, ptr, emit, name_prefix):
"""Emit `emit(builder)` only on the path where `ptr` is non-null. The
write-side counterpart of _null_checked_operation: a store has no value to
merge, so the null path simply skips it."""
not_null_block = func.append_basic_block(name=f"{name_prefix}_not_null")
merge_block = func.append_basic_block(name=f"{name_prefix}_merge")
is_not_null = builder.icmp_signed("!=", ptr, ir.Constant(ptr.type, None))
builder.cbranch(is_not_null, not_null_block, merge_block)
builder.position_at_end(not_null_block)
emit(builder)
builder.branch(merge_block)
builder.position_at_end(merge_block)
def with_struct_field_ptr(func, builder, symbol, struct_info, field_name, emit):
"""Call `emit(builder, field_ptr)` with a pointer to `field_name` of the
struct `symbol` holds. A struct local holds the struct itself; a
map-lookup or cast local holds a pointer to it, which may be null, and
`emit` then runs only when it is not, as the read of the field yields 0
there instead (see access_struct_field)."""
if not isinstance(symbol.ir_type, ir.PointerType):
emit(builder, struct_info.gep(builder, symbol.var, field_name))
return
struct_ptr = builder.load(symbol.var)
def emit_through_ptr(builder):
typed_ptr = builder.bitcast(struct_ptr, struct_info.ir_type.as_pointer())
emit(builder, struct_info.gep(builder, typed_ptr, field_name))
emit_if_not_null(func, builder, struct_ptr, emit_through_ptr, f"field_{field_name}")
def access_struct_field( def access_struct_field(
builder, var_ptr, var_type, var_metadata, field_name, structs_sym_tab, func=None builder, var_ptr, var_type, var_metadata, field_name, structs_sym_tab, func=None
): ):

View File

@ -17,13 +17,13 @@ from pythonbpf.expr import (
to_promoted, to_promoted,
canonicalise, canonicalise,
usual_arithmetic_conversions, usual_arithmetic_conversions,
access_struct_field,
with_struct_field_ptr,
VmlinuxHandlerRegistry, VmlinuxHandlerRegistry,
) )
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,
@ -209,9 +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 # Set for a field reached through a pointer (a map-lookup or cast local):
# written through, exactly as `v = v + 1` does it. # it is read and written through null checks rather than as a plain slot.
map_value_local = None field_via_pointer = 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
@ -225,13 +225,6 @@ 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(
@ -262,8 +255,12 @@ def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab):
struct_info = structs_sym_tab[metadata] struct_info = structs_sym_tab[metadata]
if field_name not in struct_info.fields: if field_name not in struct_info.fields:
raise SyntaxError(f"Field '{field_name}' not found in struct '{metadata}'") raise SyntaxError(f"Field '{field_name}' not found in struct '{metadata}'")
slot = struct_info.gep(builder, local_sym_tab[var_name].var, field_name) symbol = local_sym_tab[var_name]
slot_type = struct_info.field_type(field_name) slot_type = struct_info.field_type(field_name)
if isinstance(symbol.ir_type, ir.PointerType):
field_via_pointer = (symbol, struct_info, field_name)
else:
slot = struct_info.gep(builder, symbol.var, field_name)
elif isinstance(stmt.target, ast.Attribute): elif isinstance(stmt.target, ast.Attribute):
raise SyntaxError( raise SyntaxError(
f"augmented assignment to a nested struct field " f"augmented assignment to a nested struct field "
@ -275,20 +272,25 @@ 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)}"
) )
# Python evaluates the target's current value before the right-hand side. if not isinstance(slot_type, ir.IntType):
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.
if field_via_pointer is not None:
symbol, struct_info, field_name = field_via_pointer
current, _ = access_struct_field(
builder,
symbol.var,
symbol.ir_type,
symbol.metadata,
field_name,
compilation_context.structs_sym_tab,
func,
)
else:
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
) )
@ -307,8 +309,13 @@ def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab):
result_ty, result_ty,
) )
result = convert(builder, result, result_ty, slot_type) result = convert(builder, result, result_ty, slot_type)
if map_value_local is not None: if field_via_pointer is not None:
rebind_map_value_local(builder, local_sym_tab, map_value_local, result) with_struct_field_ptr(
func,
builder,
*field_via_pointer,
lambda builder, field_ptr: builder.store(result, field_ptr),
)
else: else:
builder.store(result, slot) builder.store(result, slot)

View File

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

@ -0,0 +1,41 @@
# Assignment to a field of a struct map value writes through the lookup
# pointer into the map, null-checked: `stats.count += 1` updates the entry in
# place, with no update() call. Also a sub-64-bit field and a plain store.
from pythonbpf import bpf, map, section, bpfglobal, compile, struct
from pythonbpf.maps import HashMap
from ctypes import c_void_p, c_int64, c_uint64, c_uint32
@bpf
@struct
class stats_t:
count: c_uint64
flags: c_uint32
@bpf
@map
def stats() -> HashMap:
return HashMap(key=c_uint32, value=stats_t, max_entries=16)
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def prog(ctx: c_void_p) -> c_int64:
k = c_uint32(0)
s = stats.lookup(k)
if s:
s.count += 1
s.flags = 3
s.flags <<= 1
return s.count
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -81,11 +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"],
), ),
# `v += 1; v >>= 1` on a c_uint64 map value: read through the pointer, # A field of a struct map value is written through the lookup pointer,
# operate unsigned, rebind v to the lookup local's spare slot. # behind a null check, never by indexing into the local's own slot.
"assign/augassign_map_value.py": ( "assign/struct_map_value_field.py": (
[r"deref_1_not_null", r"\blshr i64", r"store i64\* %\"v_tmp\", i64\*\* %\"v\""], [r"field_count_not_null", r"field_flags_not_null", r"store i32 .*, i32\* %"],
[r"\bashr i64"], [r"getelementptr inbounds i64\*, i64\*\*"],
), ),
# `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.