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/narrow
| Author | SHA1 | Date | |
|---|---|---|---|
| c11a25c0ab |
@ -228,8 +228,14 @@ def _allocate_for_map_method(
|
||||
_allocate_for_map_method_fallback(builder, var_name, local_sym_tab)
|
||||
return
|
||||
|
||||
# Main variable (pointer to pointer)
|
||||
ir_type = ir.PointerType(ir.IntType(64))
|
||||
# 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))
|
||||
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, 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):
|
||||
@ -152,12 +147,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}"
|
||||
)
|
||||
@ -237,15 +226,24 @@ def handle_variable_assignment(
|
||||
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
|
||||
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:
|
||||
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, deref_to_value
|
||||
from .expr_pass import eval_expr, handle_expr, get_typed_operand, holds_map_int_value
|
||||
from .type_normalization import (
|
||||
convert_to_bool,
|
||||
get_base_type_and_depth,
|
||||
@ -20,7 +20,7 @@ __all__ = [
|
||||
"canonicalise",
|
||||
"to_promoted",
|
||||
"get_typed_operand",
|
||||
"deref_to_value",
|
||||
"holds_map_int_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):
|
||||
@ -409,25 +382,41 @@ 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 = eval_expr(
|
||||
func,
|
||||
compilation_context,
|
||||
builder,
|
||||
cond.left,
|
||||
local_sym_tab,
|
||||
)
|
||||
rhs = eval_expr(
|
||||
func,
|
||||
compilation_context,
|
||||
builder,
|
||||
cond.comparators[0],
|
||||
local_sym_tab,
|
||||
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
|
||||
)
|
||||
|
||||
if lhs is None or rhs is None:
|
||||
|
||||
@ -2,7 +2,15 @@ import ast
|
||||
import logging
|
||||
|
||||
from llvmlite import ir
|
||||
from pythonbpf.expr import eval_expr, get_base_type_and_depth, deref_to_depth, convert
|
||||
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.vmlinux_registry import VmlinuxHandlerRegistry
|
||||
from pythonbpf.helper.helper_utils import get_char_array_ptr_and_size
|
||||
|
||||
@ -107,7 +115,13 @@ def _process_name_in_fval(
|
||||
):
|
||||
"""Process name nodes in formatted values."""
|
||||
if local_sym_tab and name_node.id in local_sym_tab:
|
||||
_, var_type, tmp = local_sym_tab[name_node.id]
|
||||
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
|
||||
_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
|
||||
@ -159,7 +173,8 @@ def _populate_fval(ftype, node, fmt_parts, exprs):
|
||||
if ftype.width == 64:
|
||||
fmt_parts.append("%lld")
|
||||
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")
|
||||
exprs.append(node)
|
||||
else:
|
||||
@ -229,6 +244,18 @@ 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)
|
||||
|
||||
|
||||
@ -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()
|
||||
56
tests/passing_tests/signedness/map_value_narrow.py
Normal file
56
tests/passing_tests/signedness/map_value_narrow.py
Normal file
@ -0,0 +1,56 @@
|
||||
# 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()
|
||||
@ -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,19 @@ 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[^\"]*\"\)$"],
|
||||
),
|
||||
# `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