From d4f1b5a9b4ec7035e2e7226038843f05824fcd4a Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Sun, 31 May 2026 12:46:11 +0530 Subject: [PATCH 01/21] Handle nested map lookup helper args Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- pythonbpf/helper/bpf_helper_handler.py | 21 ++++++++++++++++++--- pythonbpf/helper/helper_utils.py | 8 ++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/pythonbpf/helper/bpf_helper_handler.py b/pythonbpf/helper/bpf_helper_handler.py index f44f05f..245c34d 100644 --- a/pythonbpf/helper/bpf_helper_handler.py +++ b/pythonbpf/helper/bpf_helper_handler.py @@ -113,7 +113,12 @@ def bpf_map_lookup_elem_emitter( f"Map lookup expects exactly one argument (key), got {len(call.args)}" ) key_ptr = get_or_create_ptr_from_arg( - func, compilation_context, call.args[0], builder, local_sym_tab + func, + compilation_context, + call.args[0], + builder, + local_sym_tab, + expected_type=ir.IntType(64), ) map_void_ptr = builder.bitcast(map_ptr, ir.PointerType()) @@ -215,10 +220,20 @@ def bpf_map_update_elem_emitter( flags_arg = call.args[2] if len(call.args) > 2 else None key_ptr = get_or_create_ptr_from_arg( - func, compilation_context, key_arg, builder, local_sym_tab + func, + compilation_context, + key_arg, + builder, + local_sym_tab, + expected_type=ir.IntType(64), ) value_ptr = get_or_create_ptr_from_arg( - func, compilation_context, value_arg, builder, local_sym_tab + func, + compilation_context, + value_arg, + builder, + local_sym_tab, + expected_type=ir.IntType(64), ) flags_val = get_flags_val(flags_arg, builder, local_sym_tab) diff --git a/pythonbpf/helper/helper_utils.py b/pythonbpf/helper/helper_utils.py index 211a925..655608d 100644 --- a/pythonbpf/helper/helper_utils.py +++ b/pythonbpf/helper/helper_utils.py @@ -6,6 +6,8 @@ from pythonbpf.expr import ( eval_expr, 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__) @@ -104,6 +106,12 @@ def get_or_create_ptr_from_arg( if val is None: 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) + ptr, temp_name = compilation_context.scratch_pool.get_next_temp( local_sym_tab, expected_type ) From 0482aa2be9d7f30c83728aeb0b014f9e4bc90b90 Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Sun, 31 May 2026 15:31:43 +0530 Subject: [PATCH 02/21] Fix deref_to_depth loop type check to use cur_type Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- pythonbpf/expr/ir_ops.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pythonbpf/expr/ir_ops.py b/pythonbpf/expr/ir_ops.py index df6f503..3f10d19 100644 --- a/pythonbpf/expr/ir_ops.py +++ b/pythonbpf/expr/ir_ops.py @@ -11,7 +11,7 @@ def deref_to_depth(func, builder, val, target_depth): cur_type = val.type for depth in range(target_depth): - if not isinstance(val.type, ir.PointerType): + if not isinstance(cur_type, ir.PointerType): logger.error("Cannot dereference further, non-pointer type") return None From 7cdb9cb2f567097d4fd6e7cd778cc7dab11eb7f0 Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Sun, 31 May 2026 15:31:53 +0530 Subject: [PATCH 03/21] Add null-safety check after deref_to_depth in helper_utils Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- pythonbpf/helper/helper_utils.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pythonbpf/helper/helper_utils.py b/pythonbpf/helper/helper_utils.py index 655608d..2036d60 100644 --- a/pythonbpf/helper/helper_utils.py +++ b/pythonbpf/helper/helper_utils.py @@ -111,6 +111,8 @@ def get_or_create_ptr_from_arg( _, 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") ptr, temp_name = compilation_context.scratch_pool.get_next_temp( local_sym_tab, expected_type From 0dea1836dfb6905e68a07c1999d8f1747a32be99 Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Sun, 31 May 2026 15:32:03 +0530 Subject: [PATCH 04/21] Pass expected_type to bpf_map_delete_elem key arg Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- pythonbpf/helper/bpf_helper_handler.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/pythonbpf/helper/bpf_helper_handler.py b/pythonbpf/helper/bpf_helper_handler.py index 245c34d..9fde71f 100644 --- a/pythonbpf/helper/bpf_helper_handler.py +++ b/pythonbpf/helper/bpf_helper_handler.py @@ -282,7 +282,12 @@ def bpf_map_delete_elem_emitter( f"Map delete expects exactly one argument (key), got {len(call.args)}" ) key_ptr = get_or_create_ptr_from_arg( - func, compilation_context, call.args[0], builder, local_sym_tab + func, + compilation_context, + call.args[0], + builder, + local_sym_tab, + expected_type=ir.IntType(64), ) map_void_ptr = builder.bitcast(map_ptr, ir.PointerType()) From d0f7a9dcec48a28bd27722f2336ef100d3c265b2 Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Mon, 1 Jun 2026 11:57:48 +0530 Subject: [PATCH 05/21] Add DEBUG log in case of no expected type or target is not a pointer --- pythonbpf/helper/helper_utils.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pythonbpf/helper/helper_utils.py b/pythonbpf/helper/helper_utils.py index 2036d60..95ab34f 100644 --- a/pythonbpf/helper/helper_utils.py +++ b/pythonbpf/helper/helper_utils.py @@ -113,6 +113,8 @@ def get_or_create_ptr_from_arg( 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( local_sym_tab, expected_type From 5a9c77f0160bc32cd60351d511856df72413772f Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Mon, 1 Jun 2026 12:09:06 +0530 Subject: [PATCH 06/21] janitorial --- pythonbpf/helper/helper_utils.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pythonbpf/helper/helper_utils.py b/pythonbpf/helper/helper_utils.py index 95ab34f..dd00228 100644 --- a/pythonbpf/helper/helper_utils.py +++ b/pythonbpf/helper/helper_utils.py @@ -114,7 +114,9 @@ def get_or_create_ptr_from_arg( 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") + logger.debug( + "Expected Type not known / Not a pointer, skipping dereference" + ) ptr, temp_name = compilation_context.scratch_pool.get_next_temp( local_sym_tab, expected_type From 5311a16c21e8360abe22b302a66c69ffed83bc4e Mon Sep 17 00:00:00 2001 From: Varun R Mallya Date: Fri, 5 Jun 2026 22:19:18 +0530 Subject: [PATCH 07/21] Bump version to 0.1.9 --- docs/conf.py | 4 ++-- pyproject.toml | 2 +- pythonbpf/codegen.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index 8bddd93..c4089f8 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -15,8 +15,8 @@ sys.path.insert(0, os.path.abspath("..")) project = "PythonBPF" copyright = "2026, Pragyansh Chaturvedi, Varun Mallya" author = "Pragyansh Chaturvedi, Varun Mallya" -release = "0.1.8" -version = "0.1.8" +release = "0.1.9" +version = "0.1.9" # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration diff --git a/pyproject.toml b/pyproject.toml index 7d6cb52..7a20083 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "pythonbpf" -version = "0.1.8" +version = "0.1.9" description = "Reduced Python frontend for eBPF" authors = [ { name = "r41k0u", email="pragyanshchaturvedi18@gmail.com" }, diff --git a/pythonbpf/codegen.py b/pythonbpf/codegen.py index 7c95b14..2cc0b30 100644 --- a/pythonbpf/codegen.py +++ b/pythonbpf/codegen.py @@ -26,7 +26,7 @@ import re logger: Logger = logging.getLogger(__name__) -VERSION = "v0.1.8" +VERSION = "v0.1.9" def finalize_module(original_str): From 40eead72a189fb3c16f8965611027cb06d6e9a1f Mon Sep 17 00:00:00 2001 From: Varun R Mallya Date: Fri, 5 Jun 2026 22:20:18 +0530 Subject: [PATCH 08/21] add release script Signed-off-by: Varun R Mallya --- tools/release.sh | 80 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100755 tools/release.sh diff --git a/tools/release.sh b/tools/release.sh new file mode 100755 index 0000000..0ac00d6 --- /dev/null +++ b/tools/release.sh @@ -0,0 +1,80 @@ +#!/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 From b47063c49c475f61d7678b5807efacb96f2800aa Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Fri, 7 Aug 2026 04:38:49 +0530 Subject: [PATCH 09/21] 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) --- pythonbpf/functions/functions_pass.py | 18 +++++++++++++++++- pythonbpf/helper/helper_utils.py | 16 ++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/pythonbpf/functions/functions_pass.py b/pythonbpf/functions/functions_pass.py index 23a81de..89e87af 100644 --- a/pythonbpf/functions/functions_pass.py +++ b/pythonbpf/functions/functions_pass.py @@ -1,11 +1,12 @@ from llvmlite import ir import ast +import ctypes import logging from pythonbpf.helper import ( HelperHandlerRegistry, ) -from pythonbpf.type_deducer import ctypes_to_ir +from pythonbpf.type_deducer import ctypes_to_ir, is_ctypes from pythonbpf.expr import ( eval_expr, handle_expr, @@ -325,6 +326,9 @@ def process_func_body( 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): resolved_type = VmlinuxHandlerRegistry.get_struct_type( context_type_name @@ -332,6 +336,18 @@ def process_func_body( context_type = LocalSymbol(None, None, resolved_type) local_sym_tab[context_name] = context_type 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 local_sym_tab = allocate_mem( diff --git a/pythonbpf/helper/helper_utils.py b/pythonbpf/helper/helper_utils.py index 211a925..958db55 100644 --- a/pythonbpf/helper/helper_utils.py +++ b/pythonbpf/helper/helper_utils.py @@ -50,8 +50,20 @@ def get_or_create_ptr_from_arg( logger.info(f"Getting pointer from arg: {ast.dump(arg)}") sz = None if isinstance(arg, ast.Name): - # Stack space is already allocated - ptr = get_var_ptr_from_name(arg.id, local_sym_tab) + symbol = local_sym_tab.get(arg.id) if local_sym_tab else None + 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): int_width = 64 # Default to i64 if expected_type and isinstance(expected_type, ir.IntType): From d7a763639a2f3eda4da2bdb7ade58c2c1327ab0f Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Fri, 7 Aug 2026 04:39:01 +0530 Subject: [PATCH 10/21] 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) --- pythonbpf/allocation_pass.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/pythonbpf/allocation_pass.py b/pythonbpf/allocation_pass.py index 9aaaf19..293839d 100644 --- a/pythonbpf/allocation_pass.py +++ b/pythonbpf/allocation_pass.py @@ -340,9 +340,15 @@ def _allocate_for_attribute( struct_type: type = local_sym_tab[struct_var].metadata 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 - vmlinux_struct_name = struct_type.__name__ if not VmlinuxHandlerRegistry.has_field(vmlinux_struct_name, field_name): logger.error( f"Field '{field_name}' not found in vmlinux struct '{vmlinux_struct_name}'" From f796338245bc867ed249ff699492a25145b6df04 Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Fri, 7 Aug 2026 05:37:05 +0530 Subject: [PATCH 11/21] Tests: Silence deprecation warnings in test-cov and test-verifier c2de7da added -W ignore::DeprecationWarning to the 'test' target only, so 'make test-cov' and 'make test-verifier' still drown in warnings from the generated vmlinux.py. Also correct the test-verifier note: the suite does not run pytest under sudo, tests/framework/verifier.py shells out to 'sudo bpftool' itself. Co-Authored-By: Claude Opus 5 (1M context) --- Makefile | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 7874b44..5e3be67 100644 --- a/Makefile +++ b/Makefile @@ -10,12 +10,13 @@ test: pytest tests/ -W ignore::DeprecationWarning -v --tb=short -m "not verifier" test-cov: - pytest tests/ -v --tb=short -m "not verifier" \ + pytest tests/ -W ignore::DeprecationWarning -v --tb=short -m "not verifier" \ --cov=pythonbpf --cov-report=term-missing --cov-report=html test-verifier: - @echo "NOTE: verifier tests require sudo and bpftool. Uses sudo .venv/bin/python3." - pytest tests/test_verifier.py -v --tb=short -m verifier + @echo "NOTE: verifier tests shell out to 'sudo bpftool'; run 'sudo -v' first so" + @echo " the timestamp does not lapse mid-run. bpftool must be installed." + pytest tests/test_verifier.py -W ignore::DeprecationWarning -v --tb=short -m verifier all: clean install From edefe626d097f48c1e6af6c3aac349cc3d6c48da Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Fri, 7 Aug 2026 05:37:05 +0530 Subject: [PATCH 12/21] Tests: Use a real program section in return, var_rval and if These three declared @section("sometag1"), which is not a section name libbpf can map to a program type: libbpf: failed to guess program type from ELF section 'sometag1' so they were rejected before the kernel verifier ever saw them. They generate IR and compile fine; only the section was wrong. Switch to tracepoint/syscalls/sys_enter_execve, matching the other tracepoint tests. Co-Authored-By: Claude Opus 5 (1M context) --- tests/failing_tests/if.py | 2 +- tests/passing_tests/return.py | 2 +- tests/passing_tests/var_rval.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/failing_tests/if.py b/tests/failing_tests/if.py index 638c2ce..8949d25 100644 --- a/tests/failing_tests/if.py +++ b/tests/failing_tests/if.py @@ -3,7 +3,7 @@ from ctypes import c_void_p, c_int64 @bpf -@section("sometag1") +@section("tracepoint/syscalls/sys_enter_execve") def sometag(ctx: c_void_p) -> c_int64: if 3 + 2 == 5: return c_int64(5) diff --git a/tests/passing_tests/return.py b/tests/passing_tests/return.py index 9bd048b..67a0bb0 100644 --- a/tests/passing_tests/return.py +++ b/tests/passing_tests/return.py @@ -3,7 +3,7 @@ from ctypes import c_void_p, c_int64 @bpf -@section("sometag1") +@section("tracepoint/syscalls/sys_enter_execve") def sometag(ctx: c_void_p) -> c_int64: return c_int64(1 - 1) diff --git a/tests/passing_tests/var_rval.py b/tests/passing_tests/var_rval.py index ee1735e..0742c04 100644 --- a/tests/passing_tests/var_rval.py +++ b/tests/passing_tests/var_rval.py @@ -5,7 +5,7 @@ from ctypes import c_void_p, c_int64 @bpf -@section("sometag1") +@section("tracepoint/syscalls/sys_enter_execve") def sometag(ctx: c_void_p) -> c_int64: a = 1 - 1 return c_int64(a) From a7e2bc39efc9656e7989cd7061ae3f0cf0842e80 Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Fri, 7 Aug 2026 05:39:49 +0530 Subject: [PATCH 13/21] Tests: Add a verifier level to the expected-failure tiers test_config.toml could only declare a failure at the "ir" or "llc" level, and test_verifier.py dropped every declared-xfail case from the level-3 run outright. A program that generates IR and compiles cleanly but that the kernel verifier rejects therefore had no way to be declared: it was silently treated as must-pass at all three levels. Levels now form an ordered pipeline (ir < llc < verifier) and a declared level marks that level and every later one xfail, which is what the old ir-implies-llc special case was expressing. Level 3 runs every test file and reports declared failures as expected ones rather than skipping them. Co-Authored-By: Claude Opus 5 (1M context) --- tests/README.md | 12 ++++++++++-- tests/conftest.py | 20 +++++++++++++------- tests/framework/bpf_test_case.py | 16 +++++++++++++++- tests/test_verifier.py | 17 +++++++++++------ 4 files changed, 49 insertions(+), 16 deletions(-) diff --git a/tests/README.md b/tests/README.md index 2861f4f..6b63fd4 100644 --- a/tests/README.md +++ b/tests/README.md @@ -69,8 +69,16 @@ Known-broken tests are declared in `tests/test_config.toml`: "failing_tests/my_test.py" = {reason = "...", level = "ir"} ``` -- `level = "ir"` — fails during IR generation; both IR and LLC tests are marked xfail. -- `level = "llc"` — IR generates fine but `llc` rejects it; only the LLC test is marked xfail. +- `level = "ir"` — fails during IR generation. +- `level = "llc"` — IR generates fine but `llc` rejects it. +- `level = "verifier"` — IR and `llc` both succeed, but the kernel verifier rejects the object. + +A failure at one level implies failure at every later one, so the declared level marks +that level **and all later ones** xfail. An `"ir"` entry is xfail at all three levels; a +`"verifier"` entry is xfail at level 3 only and must still pass levels 1 and 2. + +Every test file runs at every level, including the ones declared here — level 3 does not +skip declared failures, it reports them as expected ones. All xfails use `strict = True`: if a test starts **passing** it shows up as **XPASS** and is treated as a test failure. This is intentional — it means the bug was fixed and the test should be promoted to `passing_tests/`. diff --git a/tests/conftest.py b/tests/conftest.py index ce92d1d..42ab30e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -19,6 +19,7 @@ import logging import pytest +from tests.framework.bpf_test_case import level_index from tests.framework.collector import collect_all_test_files # ── vmlinux availability ──────────────────────────────────────────────────── @@ -70,14 +71,19 @@ def pytest_collection_modifyitems(items): # xfail (strict: XPASS counts as a test failure, alerting us to fixed bugs) if case.is_expected_fail: - # Level "ir" → fails at IR generation: xfail both IR and LLC tests - # Level "llc" → IR succeeds but LLC fails: only xfail the LLC test - is_llc_test = item.nodeid.startswith("tests/test_llc_compilation.py") + # A failure at one level implies failure at every later one, so mark + # this item xfail whenever the declared level is at or before it: + # "ir" → IR, LLC and verifier + # "llc" → LLC and verifier (IR is expected to succeed) + # "verifier" → verifier only + if item.nodeid.startswith("tests/test_verifier.py"): + item_level = "verifier" + elif item.nodeid.startswith("tests/test_llc_compilation.py"): + item_level = "llc" + else: + item_level = "ir" - apply_xfail = (case.xfail_level == "ir") or ( - case.xfail_level == "llc" and is_llc_test - ) - if apply_xfail: + if level_index(case.xfail_level) <= level_index(item_level): item.add_marker( pytest.mark.xfail( reason=case.xfail_reason, diff --git a/tests/framework/bpf_test_case.py b/tests/framework/bpf_test_case.py index d80a713..a993166 100644 --- a/tests/framework/bpf_test_case.py +++ b/tests/framework/bpf_test_case.py @@ -1,6 +1,20 @@ from dataclasses import dataclass from pathlib import Path +# The three test levels, in pipeline order. A test declared as failing at one +# level is also expected to fail at every later level: a program that cannot +# generate IR cannot reach llc, and one that llc rejects never reaches the +# kernel. Used by conftest to decide which items to mark xfail. +LEVELS = ("ir", "llc", "verifier") + + +def level_index(level: str) -> int: + """Position of a level in the pipeline. Unknown levels sort first ("ir").""" + try: + return LEVELS.index(level) + except ValueError: + return 0 + @dataclass class BpfTestCase: @@ -8,7 +22,7 @@ class BpfTestCase: rel_path: str is_expected_fail: bool = False xfail_reason: str = "" - xfail_level: str = "ir" # "ir" or "llc" + xfail_level: str = "ir" # one of LEVELS needs_vmlinux: bool = False skip_reason: str = "" diff --git a/tests/test_verifier.py b/tests/test_verifier.py index 413ef45..3966e3f 100644 --- a/tests/test_verifier.py +++ b/tests/test_verifier.py @@ -24,12 +24,12 @@ from tests.framework.compiler import run_ir_generation, run_llc from tests.framework.verifier import verify_object -def _passing_test_files(): - return [c.path for c in collect_all_test_files() if not c.is_expected_fail] +def _verifier_test_files(): + return [c.path for c in collect_all_test_files()] -def _passing_test_ids(): - return [c.rel_path for c in collect_all_test_files() if not c.is_expected_fail] +def _verifier_test_ids(): + return [c.rel_path for c in collect_all_test_files()] def _get_rejection_reason(verifier_test_file: Path, output) -> str: @@ -43,11 +43,16 @@ def _get_rejection_reason(verifier_test_file: Path, output) -> str: return errstr +# Every test file runs at this level, including the ones declared in +# test_config.toml. conftest marks those xfail, so an "ir"- or "llc"-level +# failure is still reported as an expected failure rather than being silently +# dropped from the level-3 run — and a "verifier"-level entry becomes possible +# at all. @pytest.mark.verifier @pytest.mark.parametrize( "verifier_test_file", - _passing_test_files(), - ids=_passing_test_ids(), + _verifier_test_files(), + ids=_verifier_test_ids(), ) def test_kernel_verifier(verifier_test_file: Path, tmp_path, caplog): """Compile the BPF test and verify it passes the kernel verifier.""" From ecb277469439db526a86d9b08e2a96a304312fe6 Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Fri, 7 Aug 2026 16:55:39 +0530 Subject: [PATCH 14/21] Tests: Declare the ringbuf map with its real type and a legal size The map was declared as RingBuf, which is not an exported name -- the class is RingBuffer. maps_pass has no processor registered under RingBuf, so it fell through to the 'unknown map type, defaulting to HashMap' path and was emitted as BPF_MAP_TYPE_HASH with no key or value size. The kernel rejected it: libbpf: map 'mymap': found type = 1. libbpf: map 'mymap': failed to create: -EINVAL Nothing caught this earlier because the test framework compiles the file's AST and never imports it, so the bogus 'from pythonbpf.maps import RingBuf' never raised ImportError. Using the real name also subjects the map to process_ringbuf_map's validation, which max_entries=1024 does not survive: a ringbuf needs a power of two at least as large as the page size. Raised to 4096. libbpf now reports type = 27 with max_entries = 4096. Co-Authored-By: Claude Opus 5 (1M context) --- tests/passing_tests/ringbuf.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/passing_tests/ringbuf.py b/tests/passing_tests/ringbuf.py index 0566d85..05652cf 100644 --- a/tests/passing_tests/ringbuf.py +++ b/tests/passing_tests/ringbuf.py @@ -1,13 +1,13 @@ from pythonbpf import bpf, BPF, map, bpfglobal, section, compile, compile_to_ir -from pythonbpf.maps import RingBuf, HashMap +from pythonbpf.maps import RingBuffer, HashMap from ctypes import c_int32, c_void_p # Define a map @bpf @map -def mymap() -> RingBuf: - return RingBuf(max_entries=(1024)) +def mymap() -> RingBuffer: + return RingBuffer(max_entries=4096) @bpf From 79c8a1e1948d654d8bdad8082d591535b94927eb Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Fri, 7 Aug 2026 16:57:51 +0530 Subject: [PATCH 15/21] Core: Reject an unknown map type instead of silently emitting a hash map process_bpf_map logged a warning and fell back to process_hash_map for any map type it did not recognise. That turns a typo into an object file that compiles cleanly, carries the wrong BPF_MAP_TYPE, skips the intended map type's parameter validation entirely, and is only rejected once it reaches the kernel -- as tests/passing_tests/ringbuf.py was, with 'failed to create: -EINVAL'. A warning was not enough to surface it either: the test framework only fails a test on logging.ERROR records. Raise instead, naming the registered map types so the fix is obvious: ValueError: Unknown map type 'RingBuf' returned by 'm'. Known map types: HashMap, PerfEventArray, RingBuffer Co-Authored-By: Claude Opus 5 (1M context) --- pythonbpf/maps/maps_pass.py | 16 +++++++++++----- pythonbpf/maps/maps_utils.py | 5 +++++ 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/pythonbpf/maps/maps_pass.py b/pythonbpf/maps/maps_pass.py index 083b24a..7e3b1ed 100644 --- a/pythonbpf/maps/maps_pass.py +++ b/pythonbpf/maps/maps_pass.py @@ -175,10 +175,16 @@ def process_bpf_map(func_node, compilation_context): if isinstance(rval, ast.Call) and isinstance(rval.func, ast.Name): handler = MapProcessorRegistry.get_processor(rval.func.id) - if handler: - return handler(map_name, rval, compilation_context) - else: - logger.warning(f"Unknown map type {rval.func.id}, defaulting to HashMap") - return process_hash_map(map_name, rval, compilation_context) + if handler is None: + # Falling back to a hash map here used to produce an object that + # compiled cleanly and was then rejected by the kernel, because the + # map carried the wrong type and none of the real map type's + # validation ran. A misspelled map type is a program error. + known = ", ".join(sorted(MapProcessorRegistry.known_types())) + raise ValueError( + f"Unknown map type '{rval.func.id}' returned by '{map_name}'. " + f"Known map types: {known}" + ) + return handler(map_name, rval, compilation_context) else: raise ValueError("Function under @map must return a map") diff --git a/pythonbpf/maps/maps_utils.py b/pythonbpf/maps/maps_utils.py index 194b408..decf04b 100644 --- a/pythonbpf/maps/maps_utils.py +++ b/pythonbpf/maps/maps_utils.py @@ -33,3 +33,8 @@ class MapProcessorRegistry: def get_processor(cls, map_type_name): """Get the processor function for a map type""" return cls._processors.get(map_type_name) + + @classmethod + def known_types(cls): + """Names of every registered map type, for error messages""" + return list(cls._processors) From d66b468f39f43613cd8cd1547314dca03a4f41c8 Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Fri, 7 Aug 2026 16:57:54 +0530 Subject: [PATCH 16/21] Tests: Promote if.py to passing_tests It generates IR, compiles, and now passes the kernel verifier, so it is no longer a failing test. It sat in failing_tests/ with no test_config.toml entry, which meant the framework already required it to pass at every level -- the directory was merely misleading. Co-Authored-By: Claude Opus 5 (1M context) --- tests/{failing_tests => passing_tests}/if.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tests/{failing_tests => passing_tests}/if.py (100%) diff --git a/tests/failing_tests/if.py b/tests/passing_tests/if.py similarity index 100% rename from tests/failing_tests/if.py rename to tests/passing_tests/if.py From fd2412e733f11fd9b7137d9c6f662b8c59d9d8ba Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Fri, 7 Aug 2026 17:00:23 +0530 Subject: [PATCH 17/21] Tests: Declare xdp_test_1 as a verifier-level expected failure It generates IR and compiles, and the CO-RE relocations against struct xdp_md resolve correctly, so it must keep passing levels 1 and 2. The kernel rejects it: the 'data + 34 < data_end' guard is emitted as a signed compare over values round-tripped through the stack, so the verifier never narrows the packet range and the later iph.saddr read fails with invalid access to packet, off=26 size=4, R1(id=0,off=26,r=0) R1 offset is outside of the packet Direct packet access needs bounds checks in a form the verifier can follow. strict = True, so this flags up if that ever lands. Co-Authored-By: Claude Opus 5 (1M context) --- tests/test_config.toml | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/tests/test_config.toml b/tests/test_config.toml index edcd90c..8a6255a 100644 --- a/tests/test_config.toml +++ b/tests/test_config.toml @@ -2,15 +2,27 @@ # # [xfail] — tests expected to fail. # key = path relative to tests/ -# value = {reason = "...", level = "ir" | "llc"} -# level "ir" = fails during pythonbpf IR generation (exception or ERROR log) -# level "llc" = IR generates but llc rejects it +# value = {reason = "...", level = "ir" | "llc" | "verifier"} +# level "ir" = fails during pythonbpf IR generation (exception or ERROR log) +# level "llc" = IR generates but llc rejects it +# level "verifier" = IR and llc both succeed, but the kernel verifier rejects it +# +# A failure at one level implies failure at every later one, so the declared +# level marks that level and all later ones xfail. # [xfail] "failing_tests/conditionals/struct_ptr.py" = {reason = "Struct pointer used directly as boolean condition not supported", level = "ir"} +# Compiles cleanly; rejected by the kernel. The `data + 34 < data_end` guard is +# emitted as a signed compare over values round-tripped through the stack, so the +# verifier never narrows the packet range (it stays r=0) and the later +# `iph.saddr` read fails with "invalid access to packet, off=26 size=4" / +# "R1 offset is outside of the packet". Direct packet access needs bounds checks +# in a form the verifier can follow. +"failing_tests/xdp/xdp_test_1.py" = {reason = "XDP direct packet access: the data/data_end guard does not establish a packet range the verifier can use", level = "verifier"} + "failing_tests/license.py" = {reason = "Missing LICENSE global produces IR that llc rejects — should be caught earlier with a clear error message", level = "llc"} "failing_tests/undeclared_values.py" = {reason = "Undeclared variable used in f-string — should raise SyntaxError (correct behaviour, test documents it)", level = "ir"} From e1b40d2c778712af171315e0605fe75256011459 Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi <76248539+r41k0u@users.noreply.github.com> Date: Fri, 14 Aug 2026 03:04:28 +0530 Subject: [PATCH 18/21] Fix comment in maps_pass.py --- pythonbpf/maps/maps_pass.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/pythonbpf/maps/maps_pass.py b/pythonbpf/maps/maps_pass.py index 7e3b1ed..ca07845 100644 --- a/pythonbpf/maps/maps_pass.py +++ b/pythonbpf/maps/maps_pass.py @@ -176,10 +176,9 @@ def process_bpf_map(func_node, compilation_context): if isinstance(rval, ast.Call) and isinstance(rval.func, ast.Name): handler = MapProcessorRegistry.get_processor(rval.func.id) if handler is None: - # Falling back to a hash map here used to produce an object that - # compiled cleanly and was then rejected by the kernel, because the - # map carried the wrong type and none of the real map type's - # validation ran. A misspelled map type is a program error. + # Raise an exception and fail the build because the + # map carried the wrong type. A misspelled map type + # is a program error. known = ", ".join(sorted(MapProcessorRegistry.known_types())) raise ValueError( f"Unknown map type '{rval.func.id}' returned by '{map_name}'. " From 180c35f83ed6d7c5d0044b6c75398c86336e0db9 Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi <76248539+r41k0u@users.noreply.github.com> Date: Fri, 14 Aug 2026 03:06:06 +0530 Subject: [PATCH 19/21] just return the keys instead of all the processors in maps_utils,py --- pythonbpf/maps/maps_utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pythonbpf/maps/maps_utils.py b/pythonbpf/maps/maps_utils.py index decf04b..a271697 100644 --- a/pythonbpf/maps/maps_utils.py +++ b/pythonbpf/maps/maps_utils.py @@ -37,4 +37,4 @@ class MapProcessorRegistry: @classmethod def known_types(cls): """Names of every registered map type, for error messages""" - return list(cls._processors) + return list(cls._processors.keys()) From 91146d3f43bf44ab2eac3cd8259e62586c495f3a Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi <76248539+r41k0u@users.noreply.github.com> Date: Fri, 21 Aug 2026 17:39:55 +0530 Subject: [PATCH 20/21] Update README.md --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4220703..6504f7d 100644 --- a/README.md +++ b/README.md @@ -222,10 +222,12 @@ This architecture eliminates the need for embedding C code in Python, allowing f --- -## Resources +## Resources and Talks +* [Linux Plumbers Conference 2025](https://www.youtube.com/watch?v=eFVhLnWFxtE) * [Video demonstration](https://youtu.be/eMyLW8iWbks) -* [Slide deck](https://docs.google.com/presentation/d/1DsWDIVrpJhM4RgOETO9VWqUtEHo3-c7XIWmNpi6sTSo/edit?usp=sharing) +* [More Demos](https://www.youtube.com/watch?v=GN17VBZYdCY) +* [FOSDEM 2026](https://mirrors.dotsrc.org/fosdem/2026/h1308/T9D8ZR-pythonbpf.mp4) --- From 9a8e1ba90958e860ff7fc477ce443f946071e245 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 24 Aug 2026 10:54:08 +0000 Subject: [PATCH 21/21] build(deps): bump the actions group across 1 directory with 2 updates Bumps the actions group with 2 updates in the / directory: [actions/checkout](https://github.com/actions/checkout) and [actions/setup-python](https://github.com/actions/setup-python). Updates `actions/checkout` from 6 to 7 - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v6...v7) Updates `actions/setup-python` from 6 to 7 - [Release notes](https://github.com/actions/setup-python/releases) - [Commits](https://github.com/actions/setup-python/compare/v6...v7) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: '7' dependency-type: direct:production update-type: version-update:semver-major dependency-group: actions - dependency-name: actions/setup-python dependency-version: '7' dependency-type: direct:production update-type: version-update:semver-major dependency-group: actions ... Signed-off-by: dependabot[bot] --- .github/workflows/format.yml | 4 ++-- .github/workflows/python-publish.yml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml index b391a5b..b5dfff8 100644 --- a/.github/workflows/format.yml +++ b/.github/workflows/format.yml @@ -12,8 +12,8 @@ jobs: name: Format runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 - - uses: actions/setup-python@v6 + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 with: python-version: "3.x" - uses: pre-commit/action@v3.0.1 diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml index 483c77c..b1782e5 100644 --- a/.github/workflows/python-publish.yml +++ b/.github/workflows/python-publish.yml @@ -20,9 +20,9 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - - uses: actions/setup-python@v6 + - uses: actions/setup-python@v7 with: python-version: "3.x"