Compare commits

..

2 Commits

Author SHA1 Message Date
d7a763639a Core: Guard vmlinux struct lookup against non-class metadata
_allocate_for_attribute reached for `metadata.__name__` whenever the
base symbol was not a known user struct, but `metadata` is only a struct
class for struct-typed symbols. For a symbol carrying None (any plainly
typed local) or a ctypes class (a `c_void_p` context parameter), that
raised AttributeError instead of reporting the unsupported access.

Resolve the name via getattr and fall through to the existing
"struct type not found" diagnostic when there is none.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 04:39:01 +05:30
b47063c49c Core: Resolve plain-ctypes context parameter in helper args
process_func_body only entered the context parameter into local_sym_tab
when its annotation was a vmlinux struct, so a program declared as
`def prog(ctx: c_void_p)` had no `ctx` symbol at all. Passing `ctx` to a
helper that takes a raw pointer -- probe_read(dst, size, ctx) -- failed
with "Variable 'ctx' not found in local symbol table".

Register the parameter for plain ctypes annotations too, keeping `var`
as None: that is the established sentinel meaning "this symbol is the
context parameter, read it from func.args[0]" (see
VmlinuxHandler.handle_vmlinux_struct_field). Metadata holds the
annotated Python type, mirroring the vmlinux branch.

Teach the consumer side accordingly: get_or_create_ptr_from_arg now
recognises the sentinel and hands back the function's first argument
instead of an alloca. The special case lives at the call site rather
than inside get_var_ptr_from_name so that helper stays a pure symbol
table lookup -- the call site already has `func` and `builder` in scope,
and get_var_ptr_from_name has no other callers to update.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 04:38:49 +05:30
9 changed files with 48 additions and 128 deletions

View File

@ -15,8 +15,8 @@ sys.path.insert(0, os.path.abspath(".."))
project = "PythonBPF" project = "PythonBPF"
copyright = "2026, Pragyansh Chaturvedi, Varun Mallya" copyright = "2026, Pragyansh Chaturvedi, Varun Mallya"
author = "Pragyansh Chaturvedi, Varun Mallya" author = "Pragyansh Chaturvedi, Varun Mallya"
release = "0.1.9" release = "0.1.8"
version = "0.1.9" version = "0.1.8"
# -- General configuration --------------------------------------------------- # -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration

View File

@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "pythonbpf" name = "pythonbpf"
version = "0.1.9" version = "0.1.8"
description = "Reduced Python frontend for eBPF" description = "Reduced Python frontend for eBPF"
authors = [ authors = [
{ name = "r41k0u", email="pragyanshchaturvedi18@gmail.com" }, { name = "r41k0u", email="pragyanshchaturvedi18@gmail.com" },

View File

@ -340,9 +340,15 @@ def _allocate_for_attribute(
struct_type: type = local_sym_tab[struct_var].metadata struct_type: type = local_sym_tab[struct_var].metadata
if not struct_type or struct_type not in structs_sym_tab: if not struct_type or struct_type not in structs_sym_tab:
if VmlinuxHandlerRegistry.is_vmlinux_struct(struct_type.__name__): # `metadata` only names a struct for struct-typed symbols. For anything
# else (None, an IR type, or a plain ctypes class such as a `c_void_p`
# context parameter) there is no vmlinux struct name to look up, so guard
# the attribute access instead of blowing up with an AttributeError.
vmlinux_struct_name = getattr(struct_type, "__name__", None)
if vmlinux_struct_name and VmlinuxHandlerRegistry.is_vmlinux_struct(
vmlinux_struct_name
):
# Handle vmlinux struct field access # Handle vmlinux struct field access
vmlinux_struct_name = struct_type.__name__
if not VmlinuxHandlerRegistry.has_field(vmlinux_struct_name, field_name): if not VmlinuxHandlerRegistry.has_field(vmlinux_struct_name, field_name):
logger.error( logger.error(
f"Field '{field_name}' not found in vmlinux struct '{vmlinux_struct_name}'" f"Field '{field_name}' not found in vmlinux struct '{vmlinux_struct_name}'"

View File

@ -26,7 +26,7 @@ import re
logger: Logger = logging.getLogger(__name__) logger: Logger = logging.getLogger(__name__)
VERSION = "v0.1.9" VERSION = "v0.1.8"
def finalize_module(original_str): def finalize_module(original_str):

View File

@ -11,7 +11,7 @@ def deref_to_depth(func, builder, val, target_depth):
cur_type = val.type cur_type = val.type
for depth in range(target_depth): for depth in range(target_depth):
if not isinstance(cur_type, ir.PointerType): if not isinstance(val.type, ir.PointerType):
logger.error("Cannot dereference further, non-pointer type") logger.error("Cannot dereference further, non-pointer type")
return None return None

View File

@ -1,11 +1,12 @@
from llvmlite import ir from llvmlite import ir
import ast import ast
import ctypes
import logging import logging
from pythonbpf.helper import ( from pythonbpf.helper import (
HelperHandlerRegistry, HelperHandlerRegistry,
) )
from pythonbpf.type_deducer import ctypes_to_ir from pythonbpf.type_deducer import ctypes_to_ir, is_ctypes
from pythonbpf.expr import ( from pythonbpf.expr import (
eval_expr, eval_expr,
handle_expr, handle_expr,
@ -325,6 +326,9 @@ def process_func_body(
f"Unsupported annotation type: {ast.dump(context_arg.annotation)}" f"Unsupported annotation type: {ast.dump(context_arg.annotation)}"
) )
# NOTE: `var` is None for the context parameter. It is the sentinel
# that tells consumers the symbol is an incoming function argument
# (`func.args[0]`) rather than a stack slot they can load from.
if VmlinuxHandlerRegistry.is_vmlinux_struct(context_type_name): if VmlinuxHandlerRegistry.is_vmlinux_struct(context_type_name):
resolved_type = VmlinuxHandlerRegistry.get_struct_type( resolved_type = VmlinuxHandlerRegistry.get_struct_type(
context_type_name context_type_name
@ -332,6 +336,18 @@ def process_func_body(
context_type = LocalSymbol(None, None, resolved_type) context_type = LocalSymbol(None, None, resolved_type)
local_sym_tab[context_name] = context_type local_sym_tab[context_name] = context_type
logger.info(f"Added argument '{context_name}' to local symbol table") logger.info(f"Added argument '{context_name}' to local symbol table")
elif is_ctypes(context_type_name):
# Plain ctypes annotation, e.g. `ctx: c_void_p`. Register it so
# helpers that take the raw context (probe_read, ...) can resolve
# the name. Metadata is the annotated Python type, mirroring the
# vmlinux branch above.
context_type = LocalSymbol(
None,
ir.PointerType(),
getattr(ctypes, context_type_name, None),
)
local_sym_tab[context_name] = context_type
logger.info(f"Added argument '{context_name}' to local symbol table")
# pre-allocate dynamic variables # pre-allocate dynamic variables
local_sym_tab = allocate_mem( local_sym_tab = allocate_mem(

View File

@ -113,12 +113,7 @@ def bpf_map_lookup_elem_emitter(
f"Map lookup expects exactly one argument (key), got {len(call.args)}" f"Map lookup expects exactly one argument (key), got {len(call.args)}"
) )
key_ptr = get_or_create_ptr_from_arg( key_ptr = get_or_create_ptr_from_arg(
func, func, compilation_context, call.args[0], builder, local_sym_tab
compilation_context,
call.args[0],
builder,
local_sym_tab,
expected_type=ir.IntType(64),
) )
map_void_ptr = builder.bitcast(map_ptr, ir.PointerType()) map_void_ptr = builder.bitcast(map_ptr, ir.PointerType())
@ -220,20 +215,10 @@ def bpf_map_update_elem_emitter(
flags_arg = call.args[2] if len(call.args) > 2 else None flags_arg = call.args[2] if len(call.args) > 2 else None
key_ptr = get_or_create_ptr_from_arg( key_ptr = get_or_create_ptr_from_arg(
func, func, compilation_context, key_arg, builder, local_sym_tab
compilation_context,
key_arg,
builder,
local_sym_tab,
expected_type=ir.IntType(64),
) )
value_ptr = get_or_create_ptr_from_arg( value_ptr = get_or_create_ptr_from_arg(
func, func, compilation_context, value_arg, builder, local_sym_tab
compilation_context,
value_arg,
builder,
local_sym_tab,
expected_type=ir.IntType(64),
) )
flags_val = get_flags_val(flags_arg, builder, local_sym_tab) flags_val = get_flags_val(flags_arg, builder, local_sym_tab)
@ -282,12 +267,7 @@ def bpf_map_delete_elem_emitter(
f"Map delete expects exactly one argument (key), got {len(call.args)}" f"Map delete expects exactly one argument (key), got {len(call.args)}"
) )
key_ptr = get_or_create_ptr_from_arg( key_ptr = get_or_create_ptr_from_arg(
func, func, compilation_context, call.args[0], builder, local_sym_tab
compilation_context,
call.args[0],
builder,
local_sym_tab,
expected_type=ir.IntType(64),
) )
map_void_ptr = builder.bitcast(map_ptr, ir.PointerType()) map_void_ptr = builder.bitcast(map_ptr, ir.PointerType())

View File

@ -6,8 +6,6 @@ from pythonbpf.expr import (
eval_expr, eval_expr,
access_struct_field, access_struct_field,
) )
from pythonbpf.expr.ir_ops import deref_to_depth
from pythonbpf.expr.type_normalization import get_base_type_and_depth
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -52,8 +50,20 @@ def get_or_create_ptr_from_arg(
logger.info(f"Getting pointer from arg: {ast.dump(arg)}") logger.info(f"Getting pointer from arg: {ast.dump(arg)}")
sz = None sz = None
if isinstance(arg, ast.Name): if isinstance(arg, ast.Name):
# Stack space is already allocated symbol = local_sym_tab.get(arg.id) if local_sym_tab else None
ptr = get_var_ptr_from_name(arg.id, local_sym_tab) if symbol is not None and symbol.var is None:
# A None `var` marks the context parameter (see process_func_body):
# it arrives as the function's first argument, not as a stack slot,
# so there is no alloca to hand back. Use the argument itself.
if not func.args:
raise ValueError(
f"'{arg.id}' is the context parameter but "
f"'{func.name}' takes no arguments"
)
ptr = builder.bitcast(func.args[0], ir.PointerType())
else:
# Stack space is already allocated
ptr = get_var_ptr_from_name(arg.id, local_sym_tab)
elif isinstance(arg, ast.Constant) and isinstance(arg.value, int): elif isinstance(arg, ast.Constant) and isinstance(arg.value, int):
int_width = 64 # Default to i64 int_width = 64 # Default to i64
if expected_type and isinstance(expected_type, ir.IntType): if expected_type and isinstance(expected_type, ir.IntType):
@ -106,18 +116,6 @@ def get_or_create_ptr_from_arg(
if val is None: if val is None:
raise ValueError("Failed to evaluate expression for helper arg.") raise ValueError("Failed to evaluate expression for helper arg.")
if expected_type and isinstance(val.type, ir.PointerType):
_, val_depth = get_base_type_and_depth(val.type)
_, expected_depth = get_base_type_and_depth(expected_type)
if val_depth > expected_depth:
val = deref_to_depth(func, builder, val, val_depth - expected_depth)
if val is None:
raise ValueError("Failed to dereference pointer to expected depth")
else:
logger.debug(
"Expected Type not known / Not a pointer, skipping dereference"
)
ptr, temp_name = compilation_context.scratch_pool.get_next_temp( ptr, temp_name = compilation_context.scratch_pool.get_next_temp(
local_sym_tab, expected_type local_sym_tab, expected_type
) )

View File

@ -1,80 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
log() { echo -e "${GREEN}[release]${NC} $1"; }
warn() { echo -e "${YELLOW}[release]${NC} $1"; }
err() { echo -e "${RED}[release]${NC} $1"; exit 1; }
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$REPO_ROOT"
git diff --quiet || err "Working tree is dirty — commit or stash changes first."
LATEST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "none")
log "Latest tag: $LATEST_TAG"
CURRENT_VERSION=$(grep -E '^version\s*=' pyproject.toml | head -1 | sed 's/version\s*=\s*"\([^"]*\)"/\1/')
log "Current version in pyproject.toml: $CURRENT_VERSION"
echo ""
read -r -p "Enter new version (e.g. 0.1.9): " NEW_VERSION
if [[ ! "$NEW_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
err "Invalid version format — use X.Y.Z (e.g. 0.1.9)"
fi
TAG="v${NEW_VERSION}"
if git rev-parse "$TAG" >/dev/null 2>&1; then
err "Tag $TAG already exists."
fi
# --- Apply version bumps across all files ---
sed -i "s/^version = \"$CURRENT_VERSION\"/version = \"$NEW_VERSION\"/" pyproject.toml
sed -i "s/VERSION = \"v$CURRENT_VERSION\"/VERSION = \"v$NEW_VERSION\"/" pythonbpf/codegen.py
sed -i "s/release = \"$CURRENT_VERSION\"/release = \"$NEW_VERSION\"/" docs/conf.py
sed -i "s/version = \"$CURRENT_VERSION\"/version = \"$NEW_VERSION\"/" docs/conf.py
log "Bumped version $CURRENT_VERSION → $NEW_VERSION in:"
log " pyproject.toml"
log " pythonbpf/codegen.py"
log " docs/conf.py"
# --- Show diff and confirm ---
echo ""
log "Changes to be committed:"
git diff --stat
echo ""
git diff
echo ""
read -r -p "Commit these changes and create tag $TAG? [y/N]: " CONFIRM
if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then
git checkout -- pyproject.toml pythonbpf/codegen.py docs/conf.py
warn "Reverted changes. Aborted."
exit 0
fi
git add pyproject.toml pythonbpf/codegen.py docs/conf.py
git commit -m "Bump version to $NEW_VERSION"
log "Committed version bump."
git tag "$TAG"
log "Created tag $TAG."
echo ""
read -r -p "Push commit and tag to origin? [y/N]: " PUSH
if [[ "$PUSH" =~ ^[Yy]$ ]]; then
git push origin HEAD
git push origin "$TAG"
log "Pushed commit and tag $TAG. CI will build and publish to PyPI."
else
warn "Push skipped. Run: git push origin HEAD && git push origin $TAG"
fi