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/deref-
...
fix/augass
| Author | SHA1 | Date | |
|---|---|---|---|
| 13538a4042 |
@ -60,6 +60,10 @@ def trace_open(ctx: c_void_p) -> c_int64:
|
||||
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 or insert a key-value pair.
|
||||
|
||||
@ -3,7 +3,7 @@ import logging
|
||||
from inspect import isclass
|
||||
|
||||
from llvmlite import ir
|
||||
from pythonbpf.expr import eval_expr, convert, deref_to_value
|
||||
from pythonbpf.expr import eval_expr, convert
|
||||
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
|
||||
@ -40,11 +40,6 @@ def handle_struct_field_assignment(
|
||||
return
|
||||
|
||||
val, val_type = val_result
|
||||
if isinstance(field_type, ir.IntType):
|
||||
# An integer field takes the value a pointer points at (r.val = p).
|
||||
val, val_type = deref_to_value(
|
||||
func, builder, rval, val, val_type, local_sym_tab
|
||||
)
|
||||
|
||||
# Special case: i8* string to [N x i8] char array
|
||||
if _is_char_array(field_type) and _is_i8_ptr(val_type):
|
||||
@ -92,6 +87,24 @@ def _copy_string_to_char_array(
|
||||
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):
|
||||
"""Check if type is [N x i8]."""
|
||||
return (
|
||||
@ -152,12 +165,6 @@ def handle_variable_assignment(
|
||||
return False
|
||||
|
||||
val, val_type = val_result
|
||||
if isinstance(var_type, ir.IntType):
|
||||
# An integer slot takes the value a pointer points at (x = p); a
|
||||
# pointer slot keeps the pointer, below.
|
||||
val, val_type = deref_to_value(
|
||||
func, builder, rval, val, val_type, local_sym_tab
|
||||
)
|
||||
logger.info(
|
||||
f"Evaluated value for {var_name}: {val} of type {val_type}, expected {var_type}"
|
||||
)
|
||||
@ -234,12 +241,9 @@ def handle_variable_assignment(
|
||||
return False
|
||||
elif isinstance(val_type, ir.IntType) and isinstance(var_type, ir.PointerType):
|
||||
# NOTE: This is assignment to a PTR_TO_MAP_VALUE_OR_NULL
|
||||
logger.info(
|
||||
f"Creating temporary variable for pointer assignment to {var_name}"
|
||||
)
|
||||
var_ptr_tmp = local_sym_tab[f"{var_name}_tmp"].var
|
||||
builder.store(val, var_ptr_tmp)
|
||||
val = var_ptr_tmp
|
||||
rebind_map_value_local(builder, local_sym_tab, var_name, val)
|
||||
logger.info(f"Rebound map-lookup local {var_name} to a computed value")
|
||||
return True
|
||||
else:
|
||||
logger.error(
|
||||
f"Type mismatch for variable {var_name}: {val_type} vs {var_type}"
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
from .expr_pass import eval_expr, handle_expr, get_typed_operand, deref_to_value
|
||||
from .expr_pass import eval_expr, handle_expr, get_typed_operand
|
||||
from .type_normalization import (
|
||||
convert_to_bool,
|
||||
get_base_type_and_depth,
|
||||
@ -20,7 +20,6 @@ __all__ = [
|
||||
"canonicalise",
|
||||
"to_promoted",
|
||||
"get_typed_operand",
|
||||
"deref_to_value",
|
||||
"usual_arithmetic_conversions",
|
||||
"get_base_type_and_depth",
|
||||
"deref_to_depth",
|
||||
|
||||
@ -222,28 +222,6 @@ def _descriptor(val, ty):
|
||||
return None
|
||||
|
||||
|
||||
def deref_to_value(func, builder, expr, val, val_ty, local_sym_tab):
|
||||
"""Load through a pointer to an integer (a map-lookup result), with the
|
||||
null check every dereference gets, so a consumer that wants a number gets
|
||||
one. Anything else is returned unchanged. The descriptor comes from the
|
||||
map's declared value ctype when expr names a lookup local (a c_uint64 value
|
||||
is unsigned), else from the pointee."""
|
||||
if val is None or not isinstance(val.type, ir.PointerType):
|
||||
return val, val_ty
|
||||
if not hasattr(val.type, "pointee"):
|
||||
return val, val_ty # an opaque pointer says nothing about a pointee
|
||||
base_type, depth = get_base_type_and_depth(val.type)
|
||||
if not isinstance(base_type, ir.IntType):
|
||||
return val, val_ty # a struct or char pointer is not a number
|
||||
val = deref_to_depth(func, builder, val, depth)
|
||||
declared = None
|
||||
if isinstance(expr, ast.Name) and expr.id in local_sym_tab:
|
||||
meta = local_sym_tab[expr.id].metadata
|
||||
if isinstance(meta, str) and is_ctypes(meta):
|
||||
declared = ctypes_to_ir(meta)
|
||||
return val, _descriptor(val, declared if declared is not None else base_type)
|
||||
|
||||
|
||||
def get_typed_operand(func, compilation_context, operand, builder, local_sym_tab):
|
||||
"""Evaluate an operand to (value, IntTy). Pointers (map-lookup results) are
|
||||
dereferenced to the scalar they point at."""
|
||||
@ -292,8 +270,9 @@ def get_typed_operand(func, compilation_context, operand, builder, local_sym_tab
|
||||
raise ValueError(f"Failed to evaluate call expression: {operand}")
|
||||
val, ty = res
|
||||
logger.info(f"Evaluated expr to {val} of type {val.type}")
|
||||
if isinstance(val.type, ir.PointerType):
|
||||
return deref_to_value(func, builder, operand, val, ty, local_sym_tab)
|
||||
base_type, depth = get_base_type_and_depth(val.type)
|
||||
if depth > 0:
|
||||
val = deref_to_depth(func, builder, val, depth)
|
||||
return val, _descriptor(val, ty)
|
||||
raise TypeError(f"Unsupported operand type: {type(operand)}")
|
||||
|
||||
@ -374,12 +353,6 @@ def _handle_ctypes_call(
|
||||
# Extract the actual IR value and type
|
||||
# val could be (value, ir_type) or (value, Field)
|
||||
value, val_type = val
|
||||
if isinstance(expected_type, ir.IntType) and call_type != "c_void_p":
|
||||
# c_int64(p) on a map lookup is the value, as p + 0 already is;
|
||||
# c_void_p(p) keeps the pointer.
|
||||
value, val_type = deref_to_value(
|
||||
func, builder, arg, value, val_type, local_sym_tab
|
||||
)
|
||||
|
||||
# If val_type is a Field object (from vmlinux struct), get the actual IR type of the value
|
||||
if isinstance(val_type, Field):
|
||||
|
||||
@ -22,6 +22,8 @@ from pythonbpf.expr import (
|
||||
from pythonbpf.assign_pass import (
|
||||
handle_variable_assignment,
|
||||
handle_struct_field_assignment,
|
||||
is_map_value_local,
|
||||
rebind_map_value_local,
|
||||
)
|
||||
from pythonbpf.allocation_pass import (
|
||||
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
|
||||
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):
|
||||
name = stmt.target.id
|
||||
# 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(
|
||||
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:
|
||||
# `x += v` binds x as a local and reads it unbound: UnboundLocalError.
|
||||
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)}"
|
||||
)
|
||||
|
||||
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(
|
||||
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
|
||||
)
|
||||
@ -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)),
|
||||
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):
|
||||
|
||||
32
tests/passing_tests/assign/augassign_map_value.py
Normal file
32
tests/passing_tests/assign/augassign_map_value.py
Normal 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()
|
||||
@ -1,36 +0,0 @@
|
||||
# Control: a pointer local assigned a pointer keeps the pointer (aliasing).
|
||||
from pythonbpf import bpf, map, struct, section, bpfglobal, compile
|
||||
from pythonbpf.maps import HashMap
|
||||
from ctypes import c_void_p, c_int64, c_uint32, c_uint64
|
||||
|
||||
|
||||
@bpf
|
||||
@map
|
||||
def m() -> HashMap:
|
||||
return HashMap(key=c_uint32, value=c_uint64, max_entries=4)
|
||||
|
||||
|
||||
@bpf
|
||||
@struct
|
||||
class rec:
|
||||
val: c_uint64
|
||||
|
||||
|
||||
@bpf
|
||||
@section("tracepoint/raw_syscalls/sys_enter")
|
||||
def prog(ctx: c_void_p) -> c_int64:
|
||||
k = c_uint32(1)
|
||||
p = m.lookup(k)
|
||||
q = m.lookup(k)
|
||||
if p:
|
||||
q = p # noqa: F841
|
||||
return c_int64(0)
|
||||
|
||||
|
||||
@bpf
|
||||
@bpfglobal
|
||||
def LICENSE() -> str:
|
||||
return "GPL"
|
||||
|
||||
|
||||
compile()
|
||||
@ -1,36 +0,0 @@
|
||||
# A ctypes cast of a map-lookup pointer is a cast of its value, as p + 0 is.
|
||||
from pythonbpf import bpf, map, struct, section, bpfglobal, compile
|
||||
from pythonbpf.maps import HashMap
|
||||
from ctypes import c_void_p, c_int64, c_uint32, c_uint64
|
||||
|
||||
|
||||
@bpf
|
||||
@map
|
||||
def m() -> HashMap:
|
||||
return HashMap(key=c_uint32, value=c_uint64, max_entries=4)
|
||||
|
||||
|
||||
@bpf
|
||||
@struct
|
||||
class rec:
|
||||
val: c_uint64
|
||||
|
||||
|
||||
@bpf
|
||||
@section("tracepoint/raw_syscalls/sys_enter")
|
||||
def prog(ctx: c_void_p) -> c_int64:
|
||||
k = c_uint32(1)
|
||||
p = m.lookup(k)
|
||||
q = m.lookup(k) # noqa: F841
|
||||
if p:
|
||||
y = c_int64(p) # noqa: F841
|
||||
return c_int64(0)
|
||||
|
||||
|
||||
@bpf
|
||||
@bpfglobal
|
||||
def LICENSE() -> str:
|
||||
return "GPL"
|
||||
|
||||
|
||||
compile()
|
||||
@ -1,37 +0,0 @@
|
||||
# An integer local takes the value a map-lookup pointer points at.
|
||||
from pythonbpf import bpf, map, struct, section, bpfglobal, compile
|
||||
from pythonbpf.maps import HashMap
|
||||
from ctypes import c_void_p, c_int64, c_uint32, c_uint64
|
||||
|
||||
|
||||
@bpf
|
||||
@map
|
||||
def m() -> HashMap:
|
||||
return HashMap(key=c_uint32, value=c_uint64, max_entries=4)
|
||||
|
||||
|
||||
@bpf
|
||||
@struct
|
||||
class rec:
|
||||
val: c_uint64
|
||||
|
||||
|
||||
@bpf
|
||||
@section("tracepoint/raw_syscalls/sys_enter")
|
||||
def prog(ctx: c_void_p) -> c_int64:
|
||||
k = c_uint32(1)
|
||||
p = m.lookup(k)
|
||||
q = m.lookup(k) # noqa: F841
|
||||
if p:
|
||||
x = c_uint64(0)
|
||||
x = p # noqa: F841
|
||||
return c_int64(0)
|
||||
|
||||
|
||||
@bpf
|
||||
@bpfglobal
|
||||
def LICENSE() -> str:
|
||||
return "GPL"
|
||||
|
||||
|
||||
compile()
|
||||
@ -1,36 +0,0 @@
|
||||
# The same cast on a return, the natural spelling.
|
||||
from pythonbpf import bpf, map, struct, section, bpfglobal, compile
|
||||
from pythonbpf.maps import HashMap
|
||||
from ctypes import c_void_p, c_int64, c_uint32, c_uint64
|
||||
|
||||
|
||||
@bpf
|
||||
@map
|
||||
def m() -> HashMap:
|
||||
return HashMap(key=c_uint32, value=c_uint64, max_entries=4)
|
||||
|
||||
|
||||
@bpf
|
||||
@struct
|
||||
class rec:
|
||||
val: c_uint64
|
||||
|
||||
|
||||
@bpf
|
||||
@section("tracepoint/raw_syscalls/sys_enter")
|
||||
def prog(ctx: c_void_p) -> c_int64:
|
||||
k = c_uint32(1)
|
||||
p = m.lookup(k)
|
||||
q = m.lookup(k) # noqa: F841
|
||||
if p:
|
||||
return c_int64(p)
|
||||
return c_int64(0)
|
||||
|
||||
|
||||
@bpf
|
||||
@bpfglobal
|
||||
def LICENSE() -> str:
|
||||
return "GPL"
|
||||
|
||||
|
||||
compile()
|
||||
@ -1,37 +0,0 @@
|
||||
# An integer struct field takes the value a map-lookup pointer points at.
|
||||
from pythonbpf import bpf, map, struct, section, bpfglobal, compile
|
||||
from pythonbpf.maps import HashMap
|
||||
from ctypes import c_void_p, c_int64, c_uint32, c_uint64
|
||||
|
||||
|
||||
@bpf
|
||||
@map
|
||||
def m() -> HashMap:
|
||||
return HashMap(key=c_uint32, value=c_uint64, max_entries=4)
|
||||
|
||||
|
||||
@bpf
|
||||
@struct
|
||||
class rec:
|
||||
val: c_uint64
|
||||
|
||||
|
||||
@bpf
|
||||
@section("tracepoint/raw_syscalls/sys_enter")
|
||||
def prog(ctx: c_void_p) -> c_int64:
|
||||
k = c_uint32(1)
|
||||
p = m.lookup(k)
|
||||
q = m.lookup(k) # noqa: F841
|
||||
if p:
|
||||
r = rec()
|
||||
r.val = p
|
||||
return c_int64(0)
|
||||
|
||||
|
||||
@bpf
|
||||
@bpfglobal
|
||||
def LICENSE() -> str:
|
||||
return "GPL"
|
||||
|
||||
|
||||
compile()
|
||||
@ -68,17 +68,6 @@ CASES = {
|
||||
[r"\bsub i64", r"trunc i64 .* to i32", r"zext i32 .* to i64"],
|
||||
[],
|
||||
),
|
||||
# A pointer consumed as a number is dereferenced (null-checked) first; no
|
||||
# pointer is ever stored into an integer slot.
|
||||
"deref/struct_field.py": ([r"deref_\d_not_null"], [r"store i64\* [^,]*, i64\* "]),
|
||||
"deref/int_local.py": (
|
||||
[r"deref_\d_not_null"],
|
||||
[r'store i64\* [^,]*, i64\*\* %"x"'],
|
||||
),
|
||||
"deref/cast.py": ([r"deref_\d_not_null"], [r'store i64\* [^,]*, i64\*\* %"y"']),
|
||||
"deref/return_cast.py": ([r"deref_\d_not_null"], [r"ret i64\*"]),
|
||||
# Control: pointer into a pointer slot stays a pointer, no dereference.
|
||||
"deref/alias.py": ([r'store i64\* [^,]*, i64\*\* %"q"'], [r"deref_\d_not_null"]),
|
||||
# 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": (
|
||||
@ -92,6 +81,12 @@ CASES = {
|
||||
[r"trunc i64 .* to i32", r"zext i32 .* to i64"],
|
||||
[r"sext i32 .* to i64"],
|
||||
),
|
||||
# `v += 1; v >>= 1` on a c_uint64 map value: read through the pointer,
|
||||
# operate unsigned, rebind v to the lookup local's spare slot.
|
||||
"assign/augassign_map_value.py": (
|
||||
[r"deref_1_not_null", r"\blshr i64", r"store i64\* %\"v_tmp\", i64\*\* %\"v\""],
|
||||
[r"\bashr i64"],
|
||||
),
|
||||
# `return p` on a map lookup dereferences through a null check and returns
|
||||
# the i64, never the pointer.
|
||||
"return/map_value.py": (
|
||||
|
||||
Reference in New Issue
Block a user