mirror of
https://github.com/varun-r-mallya/Python-BPF.git
synced 2026-12-06 09:58:34 +00:00
Compare commits
1 Commits
fix/narrow
...
fix/struct
| Author | SHA1 | Date | |
|---|---|---|---|
| aa13482191 |
@ -353,8 +353,8 @@ def track_stats(ctx: c_void_p) -> c_int64:
|
||||
stats = process_stats.lookup(process_id)
|
||||
|
||||
if stats:
|
||||
stats.count = stats.count + 1
|
||||
process_stats.update(process_id, stats)
|
||||
# A field assignment writes into the map entry itself
|
||||
stats.count += 1
|
||||
else:
|
||||
new_stats = Stats()
|
||||
new_stats.count = 1
|
||||
|
||||
@ -161,9 +161,8 @@ def track_syscalls(ctx: c_void_p) -> c_int64:
|
||||
s = stats.lookup(process_id)
|
||||
|
||||
if s:
|
||||
# Update existing stats
|
||||
s.syscall_count = s.syscall_count + 1
|
||||
stats.update(process_id, s)
|
||||
# A field assignment writes into the map entry itself
|
||||
s.syscall_count += 1
|
||||
else:
|
||||
# Create new stats
|
||||
new_stats = ProcessStats()
|
||||
|
||||
@ -228,14 +228,8 @@ def _allocate_for_map_method(
|
||||
_allocate_for_map_method_fallback(builder, var_name, local_sym_tab)
|
||||
return
|
||||
|
||||
# Main variable (pointer to pointer). An integer value is pointed at with
|
||||
# its own width, so that reads and writes through it are value-sized: the
|
||||
# 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))
|
||||
# Main variable (pointer to pointer)
|
||||
ir_type = ir.PointerType(ir.IntType(64))
|
||||
var = builder.alloca(ir_type, name=var_name)
|
||||
local_sym_tab[var_name] = LocalSymbol(var, ir_type, value_type)
|
||||
# Temporary variable for computed values
|
||||
|
||||
@ -3,7 +3,7 @@ import logging
|
||||
from inspect import isclass
|
||||
|
||||
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.type_deducer import ctypes_to_ir
|
||||
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}'")
|
||||
return
|
||||
|
||||
# Get field pointer and evaluate value
|
||||
field_ptr = struct_info.gep(builder, local_sym_tab[var_name].var, field_name)
|
||||
# Python evaluates the value before the target.
|
||||
field_type = struct_info.field_type(field_name)
|
||||
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
|
||||
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
|
||||
# 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):
|
||||
_copy_string_to_char_array(
|
||||
func,
|
||||
builder,
|
||||
val,
|
||||
field_ptr,
|
||||
field_type,
|
||||
local_sym_tab,
|
||||
)
|
||||
|
||||
# Regular assignment
|
||||
builder.store(val, field_ptr)
|
||||
else:
|
||||
# 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}")
|
||||
|
||||
|
||||
@ -226,24 +230,15 @@ def handle_variable_assignment(
|
||||
logger.info(
|
||||
f"Creating temporary variable for pointer assignment to {var_name}"
|
||||
)
|
||||
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
|
||||
var_ptr_tmp = local_sym_tab[f"{var_name}_tmp"].var
|
||||
builder.store(val, var_ptr_tmp)
|
||||
val = var_ptr_tmp
|
||||
else:
|
||||
logger.error(
|
||||
f"Type mismatch for variable {var_name}: {val_type} vs {var_type}"
|
||||
)
|
||||
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)
|
||||
logger.info(f"Assigned value to variable {var_name}")
|
||||
return True
|
||||
|
||||
@ -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 (
|
||||
convert_to_bool,
|
||||
get_base_type_and_depth,
|
||||
@ -7,7 +7,7 @@ from .type_normalization import (
|
||||
to_promoted,
|
||||
)
|
||||
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 .call_registry import CallHandlerRegistry
|
||||
from .vmlinux_registry import VmlinuxHandlerRegistry
|
||||
@ -20,12 +20,12 @@ __all__ = [
|
||||
"canonicalise",
|
||||
"to_promoted",
|
||||
"get_typed_operand",
|
||||
"holds_map_int_value",
|
||||
"usual_arithmetic_conversions",
|
||||
"get_base_type_and_depth",
|
||||
"deref_to_depth",
|
||||
"apply_binop",
|
||||
"access_struct_field",
|
||||
"with_struct_field_ptr",
|
||||
"CallHandlerRegistry",
|
||||
"VmlinuxHandlerRegistry",
|
||||
]
|
||||
|
||||
@ -382,41 +382,25 @@ def _handle_ctypes_call(
|
||||
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):
|
||||
"""Handle ast.Compare expressions."""
|
||||
|
||||
if len(cond.ops) != 1 or len(cond.comparators) != 1:
|
||||
logger.error("Only single comparisons are supported")
|
||||
return None
|
||||
lhs = _compare_operand(func, compilation_context, builder, cond.left, local_sym_tab)
|
||||
rhs = _compare_operand(
|
||||
func, compilation_context, builder, cond.comparators[0], local_sym_tab
|
||||
lhs = eval_expr(
|
||||
func,
|
||||
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:
|
||||
|
||||
@ -62,6 +62,42 @@ def _null_checked_operation(func, builder, ptr, operation, result_type, name_pre
|
||||
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(
|
||||
builder, var_ptr, var_type, var_metadata, field_name, structs_sym_tab, func=None
|
||||
):
|
||||
|
||||
@ -17,6 +17,8 @@ from pythonbpf.expr import (
|
||||
to_promoted,
|
||||
canonicalise,
|
||||
usual_arithmetic_conversions,
|
||||
access_struct_field,
|
||||
with_struct_field_ptr,
|
||||
VmlinuxHandlerRegistry,
|
||||
)
|
||||
from pythonbpf.assign_pass import (
|
||||
@ -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
|
||||
evaluation uses.
|
||||
"""
|
||||
# Set for a field reached through a pointer (a map-lookup or cast local):
|
||||
# it is read and written through null checks rather than as a plain slot.
|
||||
field_via_pointer = None
|
||||
if isinstance(stmt.target, ast.Name):
|
||||
name = stmt.target.id
|
||||
# One table: a declared global is a local_sym_tab entry whose slot is
|
||||
@ -250,8 +255,12 @@ def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab):
|
||||
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)
|
||||
symbol = local_sym_tab[var_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):
|
||||
raise SyntaxError(
|
||||
f"augmented assignment to a nested struct field "
|
||||
@ -269,7 +278,19 @@ def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab):
|
||||
)
|
||||
|
||||
# Python evaluates the target's current value before the right-hand side.
|
||||
current = builder.load(slot)
|
||||
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(
|
||||
func, compilation_context, stmt.value, builder, local_sym_tab
|
||||
)
|
||||
@ -287,7 +308,16 @@ def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab):
|
||||
apply_binop(builder, stmt.op, current, rhs, signedness(result_ty)),
|
||||
result_ty,
|
||||
)
|
||||
builder.store(convert(builder, result, result_ty, slot_type), slot)
|
||||
result = convert(builder, result, result_ty, slot_type)
|
||||
if field_via_pointer is not None:
|
||||
with_struct_field_ptr(
|
||||
func,
|
||||
builder,
|
||||
*field_via_pointer,
|
||||
lambda builder, field_ptr: builder.store(result, field_ptr),
|
||||
)
|
||||
else:
|
||||
builder.store(result, slot)
|
||||
|
||||
|
||||
def handle_cond(func, compilation_context, builder, cond, local_sym_tab):
|
||||
|
||||
@ -2,15 +2,7 @@ import ast
|
||||
import logging
|
||||
|
||||
from llvmlite import ir
|
||||
from pythonbpf.expr import (
|
||||
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 import eval_expr, get_base_type_and_depth, deref_to_depth, convert
|
||||
from pythonbpf.expr.vmlinux_registry import VmlinuxHandlerRegistry
|
||||
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."""
|
||||
if local_sym_tab and name_node.id in local_sym_tab:
|
||||
sym = 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
|
||||
_, var_type, tmp = local_sym_tab[name_node.id]
|
||||
_populate_fval(var_type, name_node, fmt_parts, exprs)
|
||||
elif name_node.id in compilation_context.bpf_globals:
|
||||
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:
|
||||
fmt_parts.append("%lld")
|
||||
exprs.append(node)
|
||||
elif ftype.width <= 32:
|
||||
# Narrower integers are promoted to int, as C varargs do.
|
||||
elif ftype.width == 32:
|
||||
fmt_parts.append("%d")
|
||||
exprs.append(node)
|
||||
else:
|
||||
@ -244,18 +229,6 @@ def _prepare_expr_args(expr, func, compilation_context, builder, local_sym_tab):
|
||||
if 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
|
||||
val, _ = eval_expr(func, compilation_context, builder, expr, local_sym_tab)
|
||||
|
||||
|
||||
41
tests/passing_tests/assign/struct_map_value_field.py
Normal file
41
tests/passing_tests/assign/struct_map_value_field.py
Normal 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()
|
||||
@ -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()
|
||||
@ -81,18 +81,11 @@ CASES = {
|
||||
[r"trunc i64 .* to i32", r"zext i32 .* to i64"],
|
||||
[r"sext i32 .* to i64"],
|
||||
),
|
||||
# A narrow map value is loaded at its width, widened per its sign, and
|
||||
# never read with an 8-byte load; a c_uint8 value is printed by value.
|
||||
"signedness/map_value_narrow.py": (
|
||||
[
|
||||
r"load i32, i32\* %\"deref",
|
||||
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[^\"]*\"\)$"],
|
||||
# A field of a struct map value is written through the lookup pointer,
|
||||
# behind a null check, never by indexing into the local's own slot.
|
||||
"assign/struct_map_value_field.py": (
|
||||
[r"field_count_not_null", r"field_flags_not_null", r"store i32 .*, i32\* %"],
|
||||
[r"getelementptr inbounds i64\*, i64\*\*"],
|
||||
),
|
||||
# `return p` on a map lookup dereferences through a null check and returns
|
||||
# the i64, never the pointer.
|
||||
|
||||
Reference in New Issue
Block a user