Compare commits

..

28 Commits

Author SHA1 Message Date
d197a11deb Core: Shorten the unbound-local messages and drop a comment
Review on the previous round: the UnboundLocalError-shaped messages said
in five lines what one says, and the ast.Global branch of process_stmt
explained itself at length for a no-op. Both messages now name the
problem and the fix and stop; the branch keeps its debug log only.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-17 20:46:04 +05:30
dc212c37bd Tests: Pin which storage each global-variable access resolves to
Levels 1 and 2 only prove the globals cases compile; what they are about
is whether a name resolves to the @bpfglobal symbol or to a stack slot
that shadows it. test_globals_ir.py reads the IR of each BPF function
and counts loads and stores per operand, exactly: `global counter` is
load/add/store on @counter with no slot, a read needs no declaration and
hits the symbol, and a write without `global` binds a slot for the whole
body of that function while a second function still reads the symbol.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-17 20:33:24 +05:30
3c3ad8d00b Tests: Shadowing is a passing case now, unbound reads are the error
globals_shadowing.py asserted the old rule, so it moves to
passing_tests/globals/shadowing.py and asserts the new one: the write
without `global` binds a local, and a second program still reads the
global's initializer. copy_to_local.py covers `x = a_global`, the read
shape that used to fail in the allocation pass.

globals_read_before_shadow.py takes over as the failing case, since a
read above the binding is what Python rejects, and the augassign test
keeps its xfail with the reason reworded to the UnboundLocalError it is.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 15:13:58 +05:30
3a3b4b2cc1 Core: Say what is unsupported instead of dropping it silently
Three review notes from the globals PR, all about being explicit:

- Augmented assignment on a struct field handles one level of
  dereference. Say so where the target is unpacked, and give
  `obj.inner.field += v` its own message instead of an ast.dump.
- The ast.Global branch of process_stmt is a no-op for a reason
  (declarations are collected before anything is lowered, because the
  binding is function-wide). Spell that out, and log the names at debug
  level rather than leaving a bare pass.
- process_stmt had no else, so any statement the compiler does not
  handle was dropped without a word, which makes a program mean
  something other than what it says. Warn, with the line number.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 15:13:56 +05:30
f0a9a4001a Core: Allocate a local copied from a global with the global's type
`x = a_global` logged three errors and emitted nothing: the Name source
path in the allocation pass only looked in the local symbol table, so a
read that needs no declaration failed anyway. Resolve local first, then
the BPF globals, and give the copy the source's type as the local-source
case already does.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 15:13:25 +05:30
46062f3434 Core: Reject a name used before its global declaration, as Python does
`global x` covers the whole function body, so a body that reads x above
the declaration has two incompatible readings of that line. Python
rejects it with "name 'x' is used prior to global declaration"; say the
same thing rather than silently picking the global.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 15:13:23 +05:30
5948971469 Core: Shadow a @bpfglobal with a local when a write has no global statement
Assigning a global's name without declaring it `global` was a compile
error. Python makes it a local instead: the name is local for the whole
function body, the global keeps its value, and only a `global` statement
writes through to it. Do that, so the same program means the same thing
in Python and in BPF.

Python's scoping is function-wide and static, which the compiler gets
for free: allocation runs as a pre-pass over the whole body, so a name
bound anywhere is in local_sym_tab before the first statement is
lowered, and reads resolve local-first. What does not come for free is
the read above the binding, which Python answers with UnboundLocalError
rather than the global's value. There is no runtime here in which to
raise that, so the local records where its binding ends and a read above
it is rejected, with the message Python would have given. Silence there
would load an uninitialised stack slot through a name the author
expected to be the global.

`counter += 1` without `global counter` stays an error for the same
reason: it binds a local and reads it in the same statement. Only its
message changes, from a shadowing refusal to the UnboundLocalError it
actually is.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 15:12:56 +05:30
526f113a5a Core: Give every symbol kind a common Symbol base class
LocalSymbol, BpfGlobalSymbol and MapSymbol each named the storage behind a
name differently (var, var, sym) and shared no type. They now all derive from
symbols.Symbol, which carries what every symbol has -- the storage pointer
(alloca, GlobalVariable, or None for the context parameter) and its IR type
-- and each subclass adds only what its kind needs: LocalSymbol its metadata
and declared_global flag, BpfGlobalSymbol its ctypes name, MapSymbol its map
type and params. MapSymbol.sym becomes var to match.

local_symbol.py is folded into the new symbols.py. LocalSymbol keeps its
three-field __iter__ for the call sites that tuple-unpack a symbol.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BSDVsZH5NtoASyxB8FCtGU
2026-09-03 11:30:21 +05:30
2b77c406de Core: Bind declared globals in local_sym_tab instead of a per-function set
A 'global x' statement is a fact about one function's scope, but it was
tracked as current_func_globals on the compilation-wide context -- per-function
state living at the wrong level, which had to be set before each body and
reset after, and which every read and write site then had to consult in a
specific order relative to local_sym_tab (the source of the parameter
collision fixed in f4ec12d).

The declaration now does what it means: it binds the name in local_sym_tab to
the @bpfglobal's storage, as a LocalSymbol whose var is the GlobalVariable and
whose declared_global flag records why. A GlobalVariable is a pointer to
storage exactly as an alloca is, so every existing path that loads from or
stores through a symbol's var works unchanged. That deletes the dedicated
global-store branch in handle_variable_assignment, the global branch in
handle_aug_assign, the allocation-pass skip, and the reset -- one table, one
lookup, no order to get wrong. Reads of an undeclared global (legal in Python)
still fall back to bpf_globals after local_sym_tab.

Python's rules fall out naturally: a parameter is already in the table when
the declarations are processed, so 'global ctx' on a parameter is detected by
the same membership check. LocalSymbol.__iter__ deliberately still yields
three fields, since several sites tuple-unpack a symbol.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BSDVsZH5NtoASyxB8FCtGU
2026-09-03 11:14:14 +05:30
f4ec12df60 Core: Resolve assignment targets local-first, and reject global on a parameter
Reads resolve a name local-first (_handle_name_expr, get_operand_value, the
printk formatter), but both write paths checked the declared-global set
before local_sym_tab. Normally harmless because the two tables are disjoint
by construction -- except for a parameter whose name matches a @bpfglobal.
With 'global ctx' in a function taking ctx, the write path stored to the
global while a read of the same name picked the parameter and crashed on its
None slot: the same name resolving to different storage depending on which
side of an assignment it sat.

Python forbids the construct outright, and now so does the compiler, with
Python's own wording: SyntaxError: name 'ctx' is parameter and global. Both
write paths now resolve local-first like the reads, so all name lookups read
the same way; and an augmented assignment to the context parameter itself
gets a clear error instead of a store to None.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BSDVsZH5NtoASyxB8FCtGU
2026-09-03 10:32:10 +05:30
f5c4dece3e Core: Unify the Python-operator tables in expr/operators.py
Operator knowledge was spread across three files: the binary-op table (an
op_map dict rebuilt inline on every _handle_binary_op_impl call, then
extracted to ir_ops.apply_binop for augmented assignment), COMPARISON_OPS in
type_normalization.py, and the unary/boolean operators as isinstance chains
in expr_pass.py. Anyone asking "which operators does PythonBPF support" had
to read all three.

They now live in one module. BINOP_METHODS and COMPARISON_OPS are the tables
themselves; UNARY_OPS and BOOL_OPS list the operators whose lowering is
structural (convert_to_bool, short-circuit control flow) so the registry is
complete even where the emission stays in expr_pass. apply_binop moves here
from ir_ops, which goes back to being purely about IR operations. No
behaviour change: 133 passed, 19 xfailed before and after.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BSDVsZH5NtoASyxB8FCtGU
2026-09-03 07:39:04 +05:30
e8ab1188d8 Tests: Record the lower-do-not-desugar house style in the skill
Captures the trade-off behind reworking augmented assignment: desugaring into
synthetic AST is a legitimate compiler technique with real benefits, and it is
still the wrong shape for this compiler, whose passes communicate through the
source tree. Records both sides so the next person tempted by it declines for
the right reasons, and states the idiom to reach for instead -- shared
value-level helpers, not shared AST.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L1PX8EuP9C3o3veWGA84RF
2026-09-03 07:23:27 +05:30
1b9adc7134 Tests: Pin augmented assignment on struct fields and the shadowing error
A struct-field test with a non-add operator and a sub-64-bit field (the
narrow-on-store path), and a strict expected failure for counter += 1 without
a global statement, which now fails as loudly as plain assignment does. Ruff
flags that line as F823 (referenced before assignment) -- the same
UnboundLocalError Python itself would raise, which is exactly the semantics
the global statement requirement mirrors.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L1PX8EuP9C3o3veWGA84RF
2026-09-03 07:22:48 +05:30
dc9aecf381 Core: Coerce integer width when assigning to a struct field
handle_struct_field_assignment stored the evaluated value as-is, and since
expressions evaluate in i64 that meant any assignment to a sub-64-bit field
(dat.hits = 1 with hits: c_uint32) died in llvmlite with "cannot store i64 to
i32*". Apply the same implicit widening/truncation the local-assignment path
already has. Surfaced by the augmented-assignment struct-field test.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L1PX8EuP9C3o3veWGA84RF
2026-09-03 07:22:03 +05:30
aa321dbd47 Core: Lower augmented assignment directly instead of desugaring
The first version synthesised an Assign(BinOp(...)) node and fed it back
through handle_assign. That is a standard compiler move, but it is not how
this compiler works: every pass walks the tree the user wrote, and a node
invented mid-codegen is invisible to the allocation pass that already ran,
carries no source location for diagnostics, and shows up in logs as a
statement nobody typed.

handle_aug_assign now resolves the target slot (declared global, local, or
struct field), loads it, evaluates the right-hand side, applies the operator,
and stores back. Semantic agreement with "x = x op v" no longer rests on
shared AST but on shared value-level helpers: the RHS goes through
get_operand_value like any other read, and the operator table is extracted
from binary-op evaluation into apply_binop so it exists exactly once.

Two behavioural refinements fall out: augmented assignment to a global name
without a global statement is now the same loud SyntaxError plain assignment
gives (previously it slipped past the allocation pass, which only walks
Assign), and struct-field targets compute their GEP once rather than twice.
Target read precedes RHS evaluation, matching Python.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L1PX8EuP9C3o3veWGA84RF
2026-09-03 07:19:07 +05:30
274bac9313 Tests: Pin name-resolution order under vmlinux collisions
Two tests locking the shadowing semantics: a local named XDP_PASS returned
from a program (the exact case the return fast path used to hijack), and a
vmlinux-importing program where a local shadows one enum constant while a
@bpfglobal shadows another, read in expressions and f-strings.

The vmlinux test needs noqa on its import and both collision sites: ruff
rightly flags unused imports and redefinitions in normal Python, and this file
is deliberately made of them.

These pin compilation; the value-level proof (ret of 55, not 2) was verified
against the emitted IR and the clang reference for the same collision shapes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L1PX8EuP9C3o3veWGA84RF
2026-09-03 06:41:46 +05:30
7f5773e5d8 Core: Make XDP return names respect local and global shadowing
handle_return consulted the hardcoded XDP action table before any symbol
table, so with a local XDP_PASS = 55 in scope, "return XDP_PASS" silently
returned 2. clang treats the equivalent C (a local shadowing an enum constant)
as the local winning, and every other resolution site in the compiler already
resolves local, then global, then vmlinux -- the return fast path was the one
place with the order inverted. It now applies only when the name is bound in
neither table.

Also warn when a @bpfglobal shadows a vmlinux enum constant. C rejects that
outright as a redefinition; PythonBPF follows the rebinding semantics the
Python file itself has (the global wins, consistently), but the collision is
worth a compile-time warning rather than silence.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L1PX8EuP9C3o3veWGA84RF
2026-09-03 06:40:11 +05:30
20b9bb9449 Fix skill to ask Python path 2026-09-03 06:25:10 +05:30
c0fda58d27 Tests: Cover global variable reads, writes, and the error cases
Five passing tests: read in condition and print; the get_cgroup_id_kern.c
read-one-write-one shape; the counter += 1 idiom; two programs sharing global
state (the test_autoattach.c shape); and mixed .bss/.data placement with mixed
widths and signedness.

Three strict expected failures documenting deliberate errors: assignment
without the global statement (shadowing), a global statement naming a
non-global, and a non-integer global type.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L1PX8EuP9C3o3veWGA84RF
2026-09-01 17:10:34 +05:30
26ee4d44c7 Core: Emit debug info for globals so llc produces BTF VAR and DATASEC
Each integer global gets a DIGlobalVariableExpression with a C-named basic
type (matching signedness and width), attached via !dbg -- the same mechanism
map_debug_info.py already uses. llc's BPF backend manufactures the BTF VAR and
DATASEC '.bss'/'.data' entries from it:

    [2] VAR 'expected_pid' type_id=1, linkage=global
    [3] VAR 'cg_id' type_id=1, linkage=global
    [4] DATASEC '.bss' size=0 vlen=2

Verified against clang's output for the same shapes: the in-object DATASEC
var offsets read 0 in both (libbpf patches them from the ELF symbol table at
load), and the ELF symbols carry the real layout, identical to the reference
(expected_pid at .bss+0, cg_id at .bss+8).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L1PX8EuP9C3o3veWGA84RF
2026-09-01 17:07:22 +05:30
4ee96e7461 Core: Support augmented assignment by desugaring to x = x op v
AugAssign previously raised 'not supported' outright. Desugaring to an
ordinary assignment with a BinOp reproduces its Python semantics for Name and
Attribute targets and reuses the whole existing assignment path -- locals,
struct fields, and the new globals all work, so 'counter += 1' (the canonical
global idiom in the kernel selftest corpus) compiles to load/add/store on
@counter.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L1PX8EuP9C3o3veWGA84RF
2026-09-01 16:43:00 +05:30
930594d932 Core: Support writes to @bpfglobal variables via the global statement
Python's own scoping marks the write: 'global cg_id' declares that assignments
to cg_id in this function mean the BPF global, and the assignment then emits
the plain 'store i64 %v, ptr @cg_id' of the C reference, with the same implicit
widening/truncation rules as local assignments.

Without the declaration, an assignment to a global's name is refused:

    SyntaxError: assignment to 'cg_id' shadows the BPF global of the same
    name -- add 'global cg_id' to write to it

That is deliberate. In real Python such an assignment creates a shadowing
local; silently compiling it as either a local or a global store would be wrong
in one direction or the other, so it is a loud error instead. 'global' naming
something that is not a @bpfglobal is also a compile error.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L1PX8EuP9C3o3veWGA84RF
2026-09-01 16:40:49 +05:30
e95ee717fd Core: Resolve @bpfglobal reads in expressions and f-strings
Name resolution tried local_sym_tab, then vmlinux enums, then failed. Globals
now resolve between the two, in _handle_name_expr, get_operand_value, and the
printk f-string formatter, each emitting the plain 'load i64, ptr @counter'
form the C reference produces. A global therefore works in conditions, binops,
print arguments and as a helper scalar argument with no further changes --
those paths all funnel through eval_expr/get_operand_value.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L1PX8EuP9C3o3veWGA84RF
2026-09-01 15:29:24 +05:30
3d8a211038 Core: Register @bpfglobal variables in a symbol table
globals_processing emitted each global and forgot it, which is why nothing
could ever read one back. Each integer-scalar global now lands in
CompilationContext.bpf_globals as a BpfGlobalSymbol; non-scalar globals get a
clear NotImplementedError instead of emitting something unusable. LICENSE stays
special-cased and unaffected.

Alignment becomes natural (width/8) instead of a blanket 8, matching what clang
emits for the same declarations in tests/c-form/global_vars.bpf.c -- llc
derives the BTF DATASEC layout from these symbols.

Also adds current_func_globals to the context for the upcoming write support.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L1PX8EuP9C3o3veWGA84RF
2026-09-01 15:24:59 +05:30
cd1f2beb98 Tests: Add the ir-first-feature skill and the globals C reference
Captures the development loop this project has always used for new compiler
features: write a minimal C eBPF program exercising only the feature, compile
it to LLVM IR and read that as the specification, diff against what PythonBPF
currently emits, stop for a human decision on the Python syntax, implement
against the reference, and test at the right tier. Recorded as a project skill
so agents follow it too; the syntax step is an explicit hard stop.

tests/c-form/global_vars.bpf.c is the loop's step 1 for global variables: the
four C global classes and nothing else. Its IR established that every global is
an independent symbol accessed by plain load/store, that llc manufactures the
BTF VAR/DATASEC entries from DIGlobalVariable metadata, and that clang folds
const but not const volatile -- the facts the globals design rests on.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L1PX8EuP9C3o3veWGA84RF
2026-09-01 15:20:53 +05:30
926ce3fd8d Bump llvmlite to 0.49 2026-09-01 12:11:03 +05:30
5d0b226e3e Vmlinux gen fix (#97)
* widen bitfields whose declared width exceeds their base type

clang2py can emit a bitfield typed as a smaller ctype than its own
declared width (e.g. a 15-bit field typed ctypes.c_ubyte, which only
has 8 bits) - ctypes rejects these with 'ValueError: number of bits
invalid for bit field'. Surfaced by struct_vmbus_channel_offer_channel
on a kernel with Hyper-V support enabled (not present locally, but
present on GitHub Actions' Azure-hosted runners).

Generalizes the existing c_bool-specific workaround to all integer
ctypes, widening to the smallest standard type that fits.

* fix ruff-format violation in vmlinux-gen.py

* Add CI workflow to run the test suite (#96)

* add CI workflow to run the test suite

Runs make test on every push/PR. Kernel verifier tests need passwordless
sudo and a kernel with BTF/BPF enabled, which isn't guaranteed on every
runner, so the workflow probes for working sudo first and only attempts
them if it's available.

Also add ctypeslib2 to the test extra: make test now regenerates
vmlinux.py via tools/vmlinux-gen.py, which needs clang2py.

* fix CI: bpftool is a virtual package on Ubuntu, install linux-tools instead

* fix CI: locate bpftool binary and add it to PATH manually

linux-tools-generic's update-alternatives symlink for bpftool doesn't
fire on GitHub-hosted runners, since their kernel version has no
matching linux-tools-<version> package.

* pin clang bindings to 16.0.6 to match Ubuntu's default libclang

pip installs the latest 'clang' release by default, whose libclang API
surface is newer than Ubuntu 24.04's apt libclang-16, causing a
LibclangError about an undefined symbol. Older bindings against a
newer libclang stay compatible, so pin the bindings low rather than
the system library.

* DEBUG: dump struct_vmbus_channel_offer_channel on test failure

* remove debug step now that the bitfield issue is fixed

* fix CI: install LLVM 19 from apt.llvm.org, Ubuntu's default is too old

llvmlite>=0.49's ArgumentAttributes only recognizes the LLVM 19+
'captures(none)' spelling of the renamed 'nocapture' attribute.
Ubuntu noble's default llvm/clang packages are LLVM 18, whose llc
can't parse that attribute in the emitted .ll text.

* DEBUG: show real llc stderr on failure

* fix YAML syntax in debug step

* fix CI: install LLVM 22 (matching llvmlite's bundled version), not 19

Verified on CI: LLVM 19's llc still rejects 'captures(none)' as a
parse error ('expected ) at end of argument list'). llvmlite 0.49
bundles LLVM 22.1.0 internally; match that generation instead.

* remove debug step, LLVM 22 fix confirmed working on CI

* avoid running CI twice per push: scope push trigger to master

Branches live in this repo, not forks, so a push to a branch with an
open PR fired both push and pull_request for the same commit. push
now only fires for master (a post-merge check); pull_request already
covers every commit on a feature branch.
2026-08-30 20:57:11 +05:30
3c69ec3cfb Merge pull request #95 from pythonbpf/vmlinux-gen-fix
Fix make test: regenerate vmlinux.py fixture and stop mis-collecting it
2026-08-30 19:54:57 +05:30
36 changed files with 1145 additions and 88 deletions

View File

@ -0,0 +1,103 @@
---
name: ir-first-feature
description: PythonBPF's development loop for implementing a new compiler feature — write a minimal C eBPF reference, compile it to LLVM IR and read that as the spec, stop for a human syntax decision, then implement against the reference. Use whenever adding or extending a PythonBPF language feature (new statement/expression support, map types, globals, helpers, program constructs).
---
# The IR-first feature loop
PythonBPF targets LLVM IR via llvmlite. For any new feature, clang's output for the
equivalent C is the specification — not documentation, not intuition. Follow the loop
in order; do not skip steps because the feature "looks simple".
## 1. Write the C reference
A minimal `.bpf.c` in `tests/c-form/` exercising **only** the target feature. Small
enough that every line of the resulting IR is attributable to the feature. Prefer no
includes (define `SEC` and the `__u*` typedefs by hand) so nothing else pollutes the IR.
Cover each variant of the feature in one file (e.g. for globals: zero-init, initialized,
const, const volatile).
## 2. Compile and read the IR — this is the spec
```bash
clang -target bpf -O2 -g -emit-llvm -S feature.bpf.c -o feature.ll
llc -march=bpf -filetype=obj feature.ll -o feature.o
bpftool btf dump file feature.o # what must come out the far end
```
Read `feature.ll` and answer, in writing: What top-level symbols/globals appear? What
do loads/stores/calls look like in the body? What `!DI*` debug metadata exists, and
what BTF does llc manufacture from it? What did -O2 fold away, and does that folding
carry semantics (it did for `const` globals)?
Version discipline: llvmlite ≥0.49 emits LLVM 21/22-era attribute spellings
(`captures(none)`, not `nocapture`). Use a clang/llc generation that accepts them, and
compare against what `pythonbpf` + the CI's LLVM actually use.
## 3. Diff against current PythonBPF output
Compile the nearest thing PythonBPF can already express and diff the `.ll`s. The delta
is the actual work item — often smaller than expected (machinery like section placement
and BTF generation frequently comes free from llc).
## 4. HARD STOP — syntax is a human decision
Present 2–3 Pythonic syntax candidates with trade-offs (declaration site, usage site,
failure modes, precedents from FastAPI/typing/Triton-style DSLs). **Wait for a human to
choose. Never proceed on your own judgment, and never treat silence as consent.** The
maintainers own the language surface.
## 5. Implement against the reference
Emit IR through the existing passes (`globals_pass`, `expr_pass`, `assign_pass`,
`allocation_pass`, `debuginfo/`). Verify by **diffing your emitted `.ll` against the
clang reference for the same shapes** — "it compiles and llc accepts it" is not the
bar; llc accepts plenty of subtly wrong IR.
### House style: lower, don't desugar
Handlers walk the AST the user wrote and emit IR directly. **Do not synthesize new AST
nodes mid-compilation and feed them back through other handlers** — no
`ast.Assign(ast.BinOp(...))` conjured to make `x += v` reuse the assignment path.
The temptation is legitimate, so know the argument you are declining. Desugaring is a
standard compiler move (CPython itself lowers `x += v` this way), it guarantees semantic
agreement with the composed form, it is the smallest diff, and any later fix to the
composed path applies automatically. Those are real benefits.
They lose in this codebase for structural reasons: the passes communicate through the
source tree. Allocation runs before codegen and walks `Assign` — a synthetic `Assign`
created during codegen is invisible to it, so the two passes silently disagree about
what the function contains (it happened to be harmless for augmented assignment only
because that statement never needs a fresh slot; that is luck, not design). Synthetic
nodes carry no source location, so diagnostics point nowhere. And `ast.dump` in the logs
shows statements the user never typed, which turns every debugging session into an
archaeology exercise.
The resolution is to move sharing down a level: **equivalence should come from shared
value-level helpers, not shared AST.** When two constructs must agree, extract the common
logic into a helper both call — the way binary-op evaluation and augmented assignment
both use `apply_binop` for the operator table and `get_operand_value` for operands —
and let each handler resolve its own target and emit its own store. Two handlers calling
one helper is the idiom; one handler manufacturing input for another is not.
The operator tables themselves — binary operators, comparisons, and the supported
unary/boolean operators — live in exactly one place, `expr/operators.py`. A new operator
is added there first; if it is not in that file, the compiler does not support it.
## 6. Test at the right tier
- Works now → `tests/passing_tests/<category>/`.
- Documents a gap → `tests/kernel_selftest_equivalent/` with a strict xfail in
`tests/test_config.toml` (level `"ir"`, `"llc"`, or `"verifier"`).
- Wrong-input behaviour → `tests/failing_tests/` with a config entry.
- Kernel verifier level runs in CI; locally it needs the user's sudo — ask, don't
assume.
## House guardrails (always)
- **Never read/cat/grep `vmlinux.py` or `vmlinux.h`** — generated, enormous, will
exhaust context. Probe with one-liners:
`.venv/bin/python -c "import vmlinux; print(vmlinux.struct_x._fields_[:3])"`
- Ask the dev which Python binary to use, and remember that for future. The original authors use `.venv/bin/python` as their system python has no llvmlite.
- Atomic commits, `Core:`/`Tests:` subject prefixes, one logical change each.

View File

@ -29,7 +29,7 @@ license = {text = "Apache-2.0"}
requires-python = ">=3.10" requires-python = ">=3.10"
dependencies = [ dependencies = [
"llvmlite>=0.45", "llvmlite>=0.49",
"astpretty", "astpretty",
"pylibbpf" "pylibbpf"
] ]

View File

@ -2,7 +2,7 @@ import ast
import logging import logging
import ctypes import ctypes
from llvmlite import ir from llvmlite import ir
from .local_symbol import LocalSymbol from .symbols import LocalSymbol
from pythonbpf.helper import HelperHandlerRegistry from pythonbpf.helper import HelperHandlerRegistry
from pythonbpf.vmlinux_parser.dependency_node import Field from pythonbpf.vmlinux_parser.dependency_node import Field
from .expr import VmlinuxHandlerRegistry from .expr import VmlinuxHandlerRegistry
@ -49,11 +49,23 @@ def handle_assign_allocation(compilation_context, builder, stmt, local_sym_tab):
continue continue
var_name = target.id var_name = target.id
# Skip if already allocated
# Already bound in this scope: a parameter, an earlier assignment, or a
# `global` declaration (whose slot is the GlobalVariable). No slot needed.
if var_name in local_sym_tab: if var_name in local_sym_tab:
logger.debug(f"Variable {var_name} already allocated, skipping") logger.debug(f"'{var_name}' already bound, no allocation needed")
continue continue
# Not declared `global`, yet named like one: Python creates a local
# that shadows the global for the whole function body, and leaves the
# global untouched. Do the same.
shadows_global = var_name in compilation_context.bpf_globals
if shadows_global:
logger.info(
f"'{var_name}' is assigned without a 'global' declaration, so it "
f"is a local shadowing the @bpfglobal of the same name"
)
# Determine type and allocate based on rval # Determine type and allocate based on rval
if isinstance(rval, ast.Call): if isinstance(rval, ast.Call):
_allocate_for_call( _allocate_for_call(
@ -65,7 +77,9 @@ def handle_assign_allocation(compilation_context, builder, stmt, local_sym_tab):
_allocate_for_binop(builder, var_name, local_sym_tab) _allocate_for_binop(builder, var_name, local_sym_tab)
elif isinstance(rval, ast.Name): elif isinstance(rval, ast.Name):
# Variable-to-variable assignment (b = a) # Variable-to-variable assignment (b = a)
_allocate_for_name(builder, var_name, rval, local_sym_tab) _allocate_for_name(
builder, var_name, rval, local_sym_tab, compilation_context
)
elif isinstance(rval, ast.Attribute): elif isinstance(rval, ast.Attribute):
# Struct field-to-variable assignment (a = dat.fld) # Struct field-to-variable assignment (a = dat.fld)
_allocate_for_attribute( _allocate_for_attribute(
@ -76,6 +90,14 @@ def handle_assign_allocation(compilation_context, builder, stmt, local_sym_tab):
f"Unsupported assignment value type for {var_name}: {type(rval).__name__}" f"Unsupported assignment value type for {var_name}: {type(rval).__name__}"
) )
if shadows_global and var_name in local_sym_tab:
# Where the binding ends, so that a read above it is reported the
# way Python reports it. end_lineno, not lineno, so a read on a
# continuation line of a multi-line binding counts as above it too.
local_sym_tab[var_name].shadows_global_from = (
getattr(stmt, "end_lineno", None) or target.lineno
)
def _allocate_for_call(builder, var_name, rval, local_sym_tab, compilation_context): def _allocate_for_call(builder, var_name, rval, local_sym_tab, compilation_context):
"""Allocate memory for variable assigned from a call.""" """Allocate memory for variable assigned from a call."""
@ -298,21 +320,24 @@ def allocate_temp_pool(builder, max_temps, local_sym_tab):
logger.debug(f"Allocated temp variable: {temp_name}") logger.debug(f"Allocated temp variable: {temp_name}")
def _allocate_for_name(builder, var_name, rval, local_sym_tab): def _allocate_for_name(builder, var_name, rval, local_sym_tab, compilation_context):
"""Allocate memory for variable-to-variable assignment (b = a).""" """Allocate memory for variable-to-variable assignment (b = a)."""
source_var = rval.id source_var = rval.id
if source_var not in local_sym_tab: # Local first, then a BPF global: the copy takes the source's type either
# way (a c_uint32 global gives a c_uint32 local).
if source_var in local_sym_tab:
source_symbol = local_sym_tab[source_var]
elif source_var in compilation_context.bpf_globals:
source_symbol = compilation_context.bpf_globals[source_var]
else:
logger.error(f"Source variable '{source_var}' not found in symbol table") logger.error(f"Source variable '{source_var}' not found in symbol table")
return return
# Get type and metadata from source variable
source_symbol = local_sym_tab[source_var]
# Allocate with same type and alignment # Allocate with same type and alignment
var = _allocate_with_type(builder, var_name, source_symbol.ir_type) var = _allocate_with_type(builder, var_name, source_symbol.ir_type)
local_sym_tab[var_name] = LocalSymbol( local_sym_tab[var_name] = LocalSymbol(
var, source_symbol.ir_type, source_symbol.metadata var, source_symbol.ir_type, getattr(source_symbol, "metadata", None)
) )
logger.info( logger.info(

View File

@ -54,6 +54,14 @@ def handle_struct_field_assignment(
logger.info(f"Copied string to char array {var_name}.{field_name}") logger.info(f"Copied string to char array {var_name}.{field_name}")
return 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):
if val_type.width < field_type.width:
val = builder.sext(val, field_type)
elif val_type.width > field_type.width:
val = builder.trunc(val, field_type)
# Regular assignment # Regular assignment
builder.store(val, field_ptr) builder.store(val, field_ptr)
logger.info(f"Assigned to struct field {var_name}.{field_name}") logger.info(f"Assigned to struct field {var_name}.{field_name}")

View File

@ -5,6 +5,7 @@ from typing import TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from pythonbpf.structs.struct_type import StructType from pythonbpf.structs.struct_type import StructType
from pythonbpf.maps.maps_utils import MapSymbol from pythonbpf.maps.maps_utils import MapSymbol
from pythonbpf.symbols import BpfGlobalSymbol
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -66,6 +67,7 @@ class CompilationContext:
self.global_sym_tab: list[ir.GlobalVariable] = [] self.global_sym_tab: list[ir.GlobalVariable] = []
self.structs_sym_tab: dict[str, "StructType"] = {} self.structs_sym_tab: dict[str, "StructType"] = {}
self.map_sym_tab: dict[str, "MapSymbol"] = {} self.map_sym_tab: dict[str, "MapSymbol"] = {}
self.bpf_globals: dict[str, "BpfGlobalSymbol"] = {}
# Helper management # Helper management
self.scratch_pool = ScratchPoolManager() self.scratch_pool = ScratchPoolManager()

View File

@ -1,6 +1,7 @@
from .expr_pass import eval_expr, handle_expr, get_operand_value from .expr_pass import eval_expr, handle_expr, get_operand_value
from .type_normalization import convert_to_bool, get_base_type_and_depth from .type_normalization import convert_to_bool, get_base_type_and_depth
from .ir_ops import deref_to_depth, access_struct_field from .ir_ops import deref_to_depth, access_struct_field
from .operators import apply_binop
from .call_registry import CallHandlerRegistry from .call_registry import CallHandlerRegistry
from .vmlinux_registry import VmlinuxHandlerRegistry from .vmlinux_registry import VmlinuxHandlerRegistry
@ -10,6 +11,7 @@ __all__ = [
"convert_to_bool", "convert_to_bool",
"get_base_type_and_depth", "get_base_type_and_depth",
"deref_to_depth", "deref_to_depth",
"apply_binop",
"access_struct_field", "access_struct_field",
"get_operand_value", "get_operand_value",
"CallHandlerRegistry", "CallHandlerRegistry",

View File

@ -7,6 +7,7 @@ from typing import Dict
from pythonbpf.type_deducer import ctypes_to_ir, is_ctypes from pythonbpf.type_deducer import ctypes_to_ir, is_ctypes
from .call_registry import CallHandlerRegistry from .call_registry import CallHandlerRegistry
from .ir_ops import deref_to_depth, access_struct_field from .ir_ops import deref_to_depth, access_struct_field
from .operators import apply_binop, UNARY_OPS, BOOL_OPS
from .type_normalization import ( from .type_normalization import (
convert_to_bool, convert_to_bool,
handle_comparator, handle_comparator,
@ -22,12 +23,22 @@ logger: Logger = logging.getLogger(__name__)
# ============================================================================ # ============================================================================
def _handle_name_expr(expr: ast.Name, local_sym_tab: Dict, builder: ir.IRBuilder): def _handle_name_expr(
expr: ast.Name, compilation_context, local_sym_tab: Dict, builder: ir.IRBuilder
):
"""Handle ast.Name expressions.""" """Handle ast.Name expressions."""
if expr.id in local_sym_tab: if expr.id in local_sym_tab:
var = local_sym_tab[expr.id].var sym = local_sym_tab[expr.id]
val = builder.load(var) # A local that shadows a @bpfglobal is unreadable above its binding,
return val, local_sym_tab[expr.id].ir_type # exactly as in Python; for every other local this is a no-op.
sym.check_bound_at(expr.id, expr.lineno)
val = builder.load(sym.var)
return val, sym.ir_type
elif expr.id in compilation_context.bpf_globals:
# A @bpfglobal
sym = compilation_context.bpf_globals[expr.id]
val = builder.load(sym.var)
return val, sym.ir_type
else: else:
# Check if it's a vmlinux enum/constant # Check if it's a vmlinux enum/constant
vmlinux_result = VmlinuxHandlerRegistry.handle_name(expr.id) vmlinux_result = VmlinuxHandlerRegistry.handle_name(expr.id)
@ -78,7 +89,9 @@ def _handle_attribute_expr(
var_ptr, var_type, var_metadata = local_sym_tab[var_name] var_ptr, var_type, var_metadata = local_sym_tab[var_name]
logger.info(f"Loading attribute {attr_name} from variable {var_name}") logger.info(f"Loading attribute {attr_name} from variable {var_name}")
logger.info( logger.info(
f"Variable type: {var_type}, Variable ptr: {var_ptr}, Variable Metadata: {var_metadata}" f"Variable type: {var_type}, Variable ptr: {
var_ptr
}, Variable Metadata: {var_metadata}"
) )
if ( if (
hasattr(var_metadata, "__module__") hasattr(var_metadata, "__module__")
@ -96,7 +109,9 @@ def _handle_attribute_expr(
elif isinstance(var_metadata, Field): elif isinstance(var_metadata, Field):
logger.error( logger.error(
f"Cannot access field '{attr_name}' on already-loaded field value '{var_name}'" f"Cannot access field '{attr_name}' on already-loaded field value '{
var_name
}'"
) )
return None return None
@ -175,6 +190,9 @@ def get_operand_value(func, compilation_context, operand, builder, local_sym_tab
else: else:
val = deref_to_depth(func, builder, var, depth) val = deref_to_depth(func, builder, var, depth)
return val return val
elif operand.id in compilation_context.bpf_globals:
# A @bpfglobal: plain load off the global symbol.
return builder.load(compilation_context.bpf_globals[operand.id].var)
else: else:
# Check if it's a vmlinux enum/constant # Check if it's a vmlinux enum/constant
vmlinux_result = VmlinuxHandlerRegistry.handle_name(operand.id) vmlinux_result = VmlinuxHandlerRegistry.handle_name(operand.id)
@ -223,25 +241,7 @@ def _handle_binary_op_impl(func, compilation_context, rval, builder, local_sym_t
right = builder.sext(right, ir.IntType(64)) right = builder.sext(right, ir.IntType(64))
# Map AST operation nodes to LLVM IR builder methods # Map AST operation nodes to LLVM IR builder methods
op_map = { return apply_binop(builder, op, left, right)
ast.Add: builder.add,
ast.Sub: builder.sub,
ast.Mult: builder.mul,
ast.Div: builder.sdiv,
ast.Mod: builder.srem,
ast.LShift: builder.shl,
ast.RShift: builder.lshr,
ast.BitOr: builder.or_,
ast.BitXor: builder.xor,
ast.BitAnd: builder.and_,
ast.FloorDiv: builder.udiv,
}
if type(op) in op_map:
result = op_map[type(op)](left, right)
return result
else:
raise SyntaxError("Unsupported binary operation")
def _handle_binary_op( def _handle_binary_op(
@ -304,7 +304,9 @@ def _handle_ctypes_call(
# Get the IR type from the value itself # Get the IR type from the value itself
actual_ir_type = value.type actual_ir_type = value.type
logger.info( logger.info(
f"Converting vmlinux field {val_type.name} (IR type: {actual_ir_type}) to {call_type}" f"Converting vmlinux field {val_type.name} (IR type: {actual_ir_type}) to {
call_type
}"
) )
else: else:
actual_ir_type = val_type actual_ir_type = val_type
@ -317,7 +319,9 @@ def _handle_ctypes_call(
if actual_ir_type.width < expected_type.width: if actual_ir_type.width < expected_type.width:
value = builder.sext(value, expected_type) value = builder.sext(value, expected_type)
logger.info( logger.info(
f"Sign-extended from i{actual_ir_type.width} to i{expected_type.width}" f"Sign-extended from i{actual_ir_type.width} to i{
expected_type.width
}"
) )
elif actual_ir_type.width > expected_type.width: elif actual_ir_type.width > expected_type.width:
value = builder.trunc(value, expected_type) value = builder.trunc(value, expected_type)
@ -329,7 +333,9 @@ def _handle_ctypes_call(
pass pass
else: else:
raise ValueError( raise ValueError(
f"Type mismatch: expected {expected_type}, got {actual_ir_type} (original type: {val_type})" f"Type mismatch: expected {expected_type}, got {
actual_ir_type
} (original type: {val_type})"
) )
return value, expected_type return value, expected_type
@ -373,7 +379,7 @@ def _handle_unary_op(
local_sym_tab, local_sym_tab,
): ):
"""Handle ast.UnaryOp expressions.""" """Handle ast.UnaryOp expressions."""
if not isinstance(expr.op, ast.Not) and not isinstance(expr.op, ast.USub): if not isinstance(expr.op, UNARY_OPS):
logger.error("Only 'not' and '-' unary operators are supported") logger.error("Only 'not' and '-' unary operators are supported")
return None return None
@ -516,6 +522,9 @@ def _handle_boolean_op(
): ):
"""Handle `and` and `or` boolean operations.""" """Handle `and` and `or` boolean operations."""
if not isinstance(expr.op, BOOL_OPS):
logger.error(f"Unsupported boolean operator: {type(expr.op).__name__}")
return None
if isinstance(expr.op, ast.And): if isinstance(expr.op, ast.And):
return _handle_and_op(func, builder, expr, local_sym_tab, compilation_context) return _handle_and_op(func, builder, expr, local_sym_tab, compilation_context)
elif isinstance(expr.op, ast.Or): elif isinstance(expr.op, ast.Or):
@ -662,7 +671,7 @@ def eval_expr(
logger.info(f"Evaluating expression: {ast.dump(expr)}") logger.info(f"Evaluating expression: {ast.dump(expr)}")
if isinstance(expr, ast.Name): if isinstance(expr, ast.Name):
return _handle_name_expr(expr, local_sym_tab, builder) return _handle_name_expr(expr, compilation_context, local_sym_tab, builder)
elif isinstance(expr, ast.Constant): elif isinstance(expr, ast.Constant):
return _handle_constant_expr(compilation_context, builder, expr) return _handle_constant_expr(compilation_context, builder, expr)
elif isinstance(expr, ast.Call): elif isinstance(expr, ast.Call):

View File

@ -0,0 +1,55 @@
"""Every Python operator PythonBPF understands, and the IR it maps to.
This is the single registry. Binary operators map to IRBuilder method names,
comparisons map to icmp predicates, and the unary/boolean operators are listed
here even though their lowering is structural (they need convert_to_bool or
short-circuit control flow, so they live in expr_pass): if an operator is not
in this file, the compiler does not support it. Add new operators here first.
"""
import ast
# ast.BinOp.op class -> llvmlite IRBuilder method name.
# Shared by binary-op evaluation and augmented assignment.
BINOP_METHODS = {
ast.Add: "add",
ast.Sub: "sub",
ast.Mult: "mul",
ast.Div: "sdiv",
ast.Mod: "srem",
ast.LShift: "shl",
ast.RShift: "lshr",
ast.BitOr: "or_",
ast.BitXor: "xor",
ast.BitAnd: "and_",
ast.FloorDiv: "udiv",
}
# ast.Compare op class -> icmp predicate string.
COMPARISON_OPS = {
ast.Eq: "==",
ast.NotEq: "!=",
ast.Lt: "<",
ast.LtE: "<=",
ast.Gt: ">",
ast.GtE: ">=",
ast.Is: "==",
ast.IsNot: "!=",
}
# Lowered structurally in expr_pass (need convert_to_bool / control flow).
UNARY_OPS = (ast.Not, ast.USub)
BOOL_OPS = (ast.And, ast.Or)
def apply_binop(builder, op, left, right):
"""Emit the LLVM instruction for a Python binary operator."""
method = BINOP_METHODS.get(type(op))
if method is None:
raise SyntaxError(f"Unsupported binary operation: {type(op).__name__}")
return getattr(builder, method)(left, right)
def comparison_predicate(op):
"""icmp predicate for a Python comparison operator, or None if unsupported."""
return COMPARISON_OPS.get(type(op))

View File

@ -1,21 +1,10 @@
import logging import logging
import ast
from llvmlite import ir from llvmlite import ir
from .ir_ops import deref_to_depth from .ir_ops import deref_to_depth
from .operators import COMPARISON_OPS
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
COMPARISON_OPS = {
ast.Eq: "==",
ast.NotEq: "!=",
ast.Lt: "<",
ast.LtE: "<=",
ast.Gt: ">",
ast.GtE: ">=",
ast.Is: "==",
ast.IsNot: "!=",
}
def get_base_type_and_depth(ir_type): def get_base_type_and_depth(ir_type):
"""Get the base type for pointer types.""" """Get the base type for pointer types."""

View File

@ -11,6 +11,8 @@ from pythonbpf.expr import (
eval_expr, eval_expr,
handle_expr, handle_expr,
convert_to_bool, convert_to_bool,
get_operand_value,
apply_binop,
VmlinuxHandlerRegistry, VmlinuxHandlerRegistry,
) )
from pythonbpf.assign_pass import ( from pythonbpf.assign_pass import (
@ -189,6 +191,100 @@ def handle_assign(func, compilation_context, builder, stmt, local_sym_tab):
logger.error(f"Unsupported assignment target: {ast.dump(target)}") logger.error(f"Unsupported assignment target: {ast.dump(target)}")
def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab):
"""Handle `x += v` and friends by direct lowering: resolve the target's
slot, load it, apply the operator, store back.
No desugaring into synthetic Assign/BinOp nodes: every pass in this
compiler walks the tree the user wrote, and nodes invented mid-codegen are
invisible to the passes that already ran and carry no source locations.
Semantic agreement with `x = x op v` comes from sharing the value-level
helpers instead — the RHS goes through get_operand_value like any other
read, and the operator table is apply_binop, the same one binary-op
evaluation uses.
"""
if isinstance(stmt.target, ast.Name):
name = stmt.target.id
# One table: a declared global is a local_sym_tab entry whose slot is
# the GlobalVariable, so it needs no separate branch.
if name in local_sym_tab:
# `x += v` reads x first, so it needs x to be bound already.
local_sym_tab[name].check_bound_at(name, stmt.lineno)
slot = local_sym_tab[name].var
slot_type = local_sym_tab[name].ir_type
if slot is None:
raise SyntaxError(
f"cannot assign to '{name}': it is the context parameter"
)
elif name in compilation_context.bpf_globals:
# `x += v` binds x as a local and reads it unbound: UnboundLocalError.
raise SyntaxError(
f"local variable '{name}' referenced before assignment; "
f"add 'global {name}' to update the @bpfglobal"
)
else:
raise SyntaxError(f"augmented assignment to undefined variable '{name}'")
elif isinstance(stmt.target, ast.Attribute) and isinstance(
stmt.target.value, ast.Name
):
# NOTE: one level of struct dereference only (`obj.field += v`). A
# nested target (`obj.inner.field += v`) has an Attribute, not a Name,
# as its value and is rejected below; supporting it means walking the
# chain of gep()s, which plain assignment does not do either.
var_name, field_name = stmt.target.value.id, stmt.target.attr
if var_name not in local_sym_tab:
raise SyntaxError(
f"augmented assignment to field of undefined variable '{var_name}'"
)
metadata = local_sym_tab[var_name].metadata
structs_sym_tab = compilation_context.structs_sym_tab
if metadata not in structs_sym_tab:
raise SyntaxError(
f"augmented assignment to '{var_name}.{field_name}' is only "
f"supported for struct fields"
)
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)
slot_type = struct_info.field_type(field_name)
elif isinstance(stmt.target, ast.Attribute):
raise SyntaxError(
f"augmented assignment to a nested struct field "
f"('...{stmt.target.attr}') is not supported yet; only one level "
f"of dereference (obj.field) works so far"
)
else:
raise SyntaxError(
f"Unsupported augmented-assignment target: {ast.dump(stmt.target)}"
)
if not isinstance(slot_type, ir.IntType):
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 = get_operand_value(
func, compilation_context, stmt.value, builder, local_sym_tab
)
if rhs is None:
raise SyntaxError(
f"Failed to evaluate augmented-assignment value: {ast.dump(stmt.value)}"
)
# Same width discipline as binary-op evaluation: compute in i64, narrow
# back to the slot's width on the way out.
if current.type.width < 64:
current = builder.sext(current, ir.IntType(64))
if isinstance(rhs.type, ir.IntType) and rhs.type.width < 64:
rhs = builder.sext(rhs, ir.IntType(64))
result = apply_binop(builder, stmt.op, current, rhs)
if result.type.width > slot_type.width:
result = builder.trunc(result, slot_type)
builder.store(result, slot)
def handle_cond(func, compilation_context, builder, cond, local_sym_tab): def handle_cond(func, compilation_context, builder, cond, local_sym_tab):
val = eval_expr(func, compilation_context, builder, cond, local_sym_tab)[0] val = eval_expr(func, compilation_context, builder, cond, local_sym_tab)[0]
return convert_to_bool(builder, val) return convert_to_bool(builder, val)
@ -238,7 +334,19 @@ def handle_return(builder, stmt, local_sym_tab, ret_type, compilation_context=No
logger.info(f"Handling return statement: {ast.dump(stmt)}") logger.info(f"Handling return statement: {ast.dump(stmt)}")
if stmt.value is None: if stmt.value is None:
return handle_none_return(builder) return handle_none_return(builder)
elif isinstance(stmt.value, ast.Name) and is_xdp_name(stmt.value.id): elif (
isinstance(stmt.value, ast.Name)
and is_xdp_name(stmt.value.id)
and stmt.value.id not in local_sym_tab
and (
compilation_context is None
or stmt.value.id not in compilation_context.bpf_globals
)
):
# The XDP fast path resolves names like XDP_PASS from the helper
# constant table, but only as a fallback: a local or @bpfglobal of the
# same name shadows it, mirroring C (a local shadows an enum constant)
# and the resolution order everywhere else in the compiler.
return handle_xdp_return(stmt, builder, ret_type) return handle_xdp_return(stmt, builder, ret_type)
else: else:
# Fallback for now if ctx not passed, but caller should pass it # Fallback for now if ctx not passed, but caller should pass it
@ -283,13 +391,22 @@ def process_stmt(
elif isinstance(stmt, ast.Assign): elif isinstance(stmt, ast.Assign):
handle_assign(func, compilation_context, builder, stmt, local_sym_tab) handle_assign(func, compilation_context, builder, stmt, local_sym_tab)
elif isinstance(stmt, ast.AugAssign): elif isinstance(stmt, ast.AugAssign):
raise SyntaxError("Augmented assignment not supported") handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab)
elif isinstance(stmt, ast.Global):
logger.debug(f"global declaration of {', '.join(stmt.names)} already bound")
elif isinstance(stmt, ast.If): elif isinstance(stmt, ast.If):
handle_if(func, compilation_context, builder, stmt, local_sym_tab) handle_if(func, compilation_context, builder, stmt, local_sym_tab)
elif isinstance(stmt, ast.Return): elif isinstance(stmt, ast.Return):
did_return = handle_return( did_return = handle_return(
builder, stmt, local_sym_tab, ret_type, compilation_context builder, stmt, local_sym_tab, ret_type, compilation_context
) )
else:
# Silently dropping a statement makes the program mean something other
# than what it says, so say so.
logger.warning(
f"Unsupported statement on line {getattr(stmt, 'lineno', '?')}, "
f"ignored: {type(stmt).__name__}"
)
return did_return return did_return
@ -349,6 +466,38 @@ def process_func_body(
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")
# A `global x` statement binds x in this function's scope to the
# @bpfglobal's storage. It goes into local_sym_tab like any other name,
# flagged, so every read and write resolves it through the one table with
# no separate lookup order to get wrong. Python's rules apply: a parameter
# cannot be declared global, and the name must be a @bpfglobal.
first_use = {}
for node in ast.walk(func_node):
if isinstance(node, ast.Name):
first_use[node.id] = min(first_use.get(node.id, node.lineno), node.lineno)
for node in ast.walk(func_node):
if isinstance(node, ast.Global):
for gname in node.names:
if gname in local_sym_tab:
raise SyntaxError(f"name '{gname}' is parameter and global")
# Python reads the declaration as covering the whole body, and
# rejects a body that used the name before saying so, because
# the two readings of the earlier line disagree.
if first_use.get(gname, node.lineno) < node.lineno:
raise SyntaxError(
f"name '{gname}' is used prior to global declaration"
)
if gname not in compilation_context.bpf_globals:
raise SyntaxError(
f"'global {gname}' in '{func_node.name}': no @bpfglobal "
f"named '{gname}' is declared"
)
sym = compilation_context.bpf_globals[gname]
local_sym_tab[gname] = LocalSymbol(
sym.var, sym.ir_type, None, declared_global=True
)
# pre-allocate dynamic variables # pre-allocate dynamic variables
local_sym_tab = allocate_mem( local_sym_tab = allocate_mem(
compilation_context, compilation_context,

View File

@ -4,9 +4,27 @@ import ast
from logging import Logger from logging import Logger
import logging import logging
from .type_deducer import ctypes_to_ir from .type_deducer import ctypes_to_ir
from .symbols import BpfGlobalSymbol
from .debuginfo import DebugInfoGenerator
from .expr import VmlinuxHandlerRegistry
from .debuginfo import dwarf_constants as dc
logger: Logger = logging.getLogger(__name__) logger: Logger = logging.getLogger(__name__)
_SIGNED_CTYPES = {
"c_int8",
"c_int16",
"c_int32",
"c_int64",
"c_int",
"c_short",
"c_long",
"c_longlong",
"c_byte",
}
_C_NAME_BY_WIDTH = {8: "char", 16: "short", 32: "int", 64: "long long"}
def populate_global_symbol_table(tree, compilation_context): def populate_global_symbol_table(tree, compilation_context):
""" """
@ -68,12 +86,38 @@ def _emit_global(module: ir.Module, node, name):
gvar = ir.GlobalVariable(module, ty, name=name) gvar = ir.GlobalVariable(module, ty, name=name)
gvar.initializer = llvm_init gvar.initializer = llvm_init
gvar.align = 8 # Natural alignment, matching what clang emits for the same declaration
# (align 4 for i32, align 8 for i64). llc derives the BTF DATASEC layout
# from these symbols, so the alignment should mirror the C reference in
# tests/c-form/global_vars.bpf.c.
gvar.align = ty.width // 8 if isinstance(ty, ir.IntType) else 8
gvar.linkage = "dso_local" gvar.linkage = "dso_local"
gvar.global_constant = False gvar.global_constant = False
return gvar return gvar
def _emit_global_debug_info(compilation_context, gvar, name, ctype_name):
"""Attach DIGlobalVariableExpression metadata to a BPF global.
llc's BPF backend manufactures the BTF VAR and DATASEC ('.bss'/'.data')
entries from exactly this metadata (see tests/c-form/global_vars.bpf.c);
without it, libbpf still creates the section maps but neither bpftool nor a
future skeleton can tell which variable lives at which offset.
"""
generator = DebugInfoGenerator(compilation_context.module)
width = gvar.value_type.width
signed = ctype_name in _SIGNED_CTYPES
base = _C_NAME_BY_WIDTH[width]
if width == 8:
encoding = dc.DW_ATE_signed_char if signed else dc.DW_ATE_unsigned_char
else:
encoding = dc.DW_ATE_signed if signed else dc.DW_ATE_unsigned
cname = base if signed else f"unsigned {base}"
di_type = generator.get_basic_type(cname, width, encoding)
dv = generator.create_global_var_debug_info(name, di_type, is_local=False)
gvar.set_metadata("dbg", dv)
def globals_processing(tree, compilation_context): def globals_processing(tree, compilation_context):
"""Process stuff decorated with @bpf and @bpfglobal except license and return the section name""" """Process stuff decorated with @bpf and @bpfglobal except license and return the section name"""
# Local tracking for duplicate checking if needed, or we can iterate context # Local tracking for duplicate checking if needed, or we can iterate context
@ -111,7 +155,33 @@ def globals_processing(tree, compilation_context):
node.body[0].value, (ast.Constant, ast.Name, ast.Call) node.body[0].value, (ast.Constant, ast.Name, ast.Call)
) )
): ):
_emit_global(compilation_context.module, node, name) gvar = _emit_global(compilation_context.module, node, name)
if VmlinuxHandlerRegistry.handle_name(name) is not None:
# C rejects this outright ("redefinition as different
# kind of symbol"); Python's rebinding semantics let
# the global win, and resolution order (local, then
# global, then vmlinux) applies it consistently. Warn
# so the shadowing is at least never silent.
logger.warning(
f"@bpfglobal '{name}' shadows a vmlinux enum "
f"constant of the same name; reads of '{name}' "
f"will use the global"
)
if isinstance(gvar.value_type, ir.IntType):
compilation_context.bpf_globals[name] = BpfGlobalSymbol(
var=gvar,
ir_type=gvar.value_type,
ctype_name=node.returns.id,
)
_emit_global_debug_info(
compilation_context, gvar, name, node.returns.id
)
else:
raise NotImplementedError(
f"Global '{name}': only integer scalar globals are "
f"supported so far; '{node.returns.id}' globals are "
f"planned for a later milestone"
)
else: else:
raise SyntaxError(f"ERROR: Invalid syntax for {name} global") raise SyntaxError(f"ERROR: Invalid syntax for {name} global")

View File

@ -1111,6 +1111,6 @@ def handle_helper_call(
if not map_sym_tab or map_name not in map_sym_tab: if not map_sym_tab or map_name not in map_sym_tab:
raise ValueError(f"Map '{map_name}' not found in symbol table") raise ValueError(f"Map '{map_name}' not found in symbol table")
return invoke_helper(method_name, map_sym_tab[map_name].sym) return invoke_helper(method_name, map_sym_tab[map_name].var)
return None return None

View File

@ -41,7 +41,7 @@ def handle_fstring_print(
fmt_parts, fmt_parts,
exprs, exprs,
local_sym_tab, local_sym_tab,
compilation_context.structs_sym_tab, compilation_context,
) )
else: else:
raise NotImplementedError(f"Unsupported f-string value type: {type(value)}") raise NotImplementedError(f"Unsupported f-string value type: {type(value)}")
@ -80,19 +80,21 @@ def _process_constant_in_fstring(cst, fmt_parts, exprs):
) )
def _process_fval(fval, fmt_parts, exprs, local_sym_tab, struct_sym_tab): def _process_fval(fval, fmt_parts, exprs, local_sym_tab, compilation_context):
"""Process formatted values in f-string.""" """Process formatted values in f-string."""
logger.debug(f"Processing formatted value: {ast.dump(fval)}") logger.debug(f"Processing formatted value: {ast.dump(fval)}")
if isinstance(fval.value, ast.Name): if isinstance(fval.value, ast.Name):
_process_name_in_fval(fval.value, fmt_parts, exprs, local_sym_tab) _process_name_in_fval(
fval.value, fmt_parts, exprs, local_sym_tab, compilation_context
)
elif isinstance(fval.value, ast.Attribute): elif isinstance(fval.value, ast.Attribute):
_process_attr_in_fval( _process_attr_in_fval(
fval.value, fval.value,
fmt_parts, fmt_parts,
exprs, exprs,
local_sym_tab, local_sym_tab,
struct_sym_tab, compilation_context.structs_sym_tab,
) )
else: else:
raise NotImplementedError( raise NotImplementedError(
@ -100,11 +102,16 @@ def _process_fval(fval, fmt_parts, exprs, local_sym_tab, struct_sym_tab):
) )
def _process_name_in_fval(name_node, fmt_parts, exprs, local_sym_tab): def _process_name_in_fval(
name_node, fmt_parts, exprs, local_sym_tab, compilation_context
):
"""Process name nodes in formatted values.""" """Process name nodes in formatted values."""
if local_sym_tab and name_node.id in local_sym_tab: if local_sym_tab and name_node.id in local_sym_tab:
_, var_type, tmp = local_sym_tab[name_node.id] _, var_type, tmp = local_sym_tab[name_node.id]
_populate_fval(var_type, name_node, fmt_parts, exprs) _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
_populate_fval(var_type, name_node, fmt_parts, exprs)
else: else:
# Try to resolve through vmlinux registry if not in local symbol table # Try to resolve through vmlinux registry if not in local symbol table
result = VmlinuxHandlerRegistry.handle_name(name_node.id) result = VmlinuxHandlerRegistry.handle_name(name_node.id)

View File

@ -1,15 +0,0 @@
import llvmlite.ir as ir
from dataclasses import dataclass
from typing import Any
@dataclass
class LocalSymbol:
var: ir.AllocaInstr
ir_type: ir.Type
metadata: Any = None
def __iter__(self):
yield self.var
yield self.ir_type
yield self.metadata

View File

@ -50,7 +50,12 @@ def create_bpf_map(compilation_context, map_name, map_params):
map_global.align = 8 map_global.align = 8
logger.info(f"Created BPF map: {map_name} with params {map_params}") logger.info(f"Created BPF map: {map_name} with params {map_params}")
return MapSymbol(type=map_params["type"], sym=map_global, params=map_params) return MapSymbol(
var=map_global,
ir_type=map_global.value_type,
type=map_params["type"],
params=map_params,
)
def _parse_map_params(rval, expected_args=None): def _parse_map_params(rval, expected_args=None):
@ -112,7 +117,7 @@ def process_ringbuf_map(map_name, rval, compilation_context):
map_global = create_bpf_map(compilation_context, map_name, map_params) map_global = create_bpf_map(compilation_context, map_name, map_params)
create_ringbuf_debug_info( create_ringbuf_debug_info(
compilation_context, compilation_context,
map_global.sym, map_global.var,
map_name, map_name,
map_params, map_params,
) )
@ -131,7 +136,7 @@ def process_hash_map(map_name, rval, compilation_context):
# Generate debug info for BTF # Generate debug info for BTF
create_map_debug_info( create_map_debug_info(
compilation_context, compilation_context,
map_global.sym, map_global.var,
map_name, map_name,
map_params, map_params,
) )
@ -150,7 +155,7 @@ def process_perf_event_map(map_name, rval, compilation_context):
# Generate debug info for BTF # Generate debug info for BTF
create_map_debug_info( create_map_debug_info(
compilation_context, compilation_context,
map_global.sym, map_global.var,
map_name, map_name,
map_params, map_params,
) )

View File

@ -1,16 +1,15 @@
from collections.abc import Callable from collections.abc import Callable
from dataclasses import dataclass from dataclasses import dataclass
from llvmlite import ir
from typing import Any from typing import Any
from .map_types import BPFMapType from .map_types import BPFMapType
from ..symbols import Symbol
@dataclass @dataclass
class MapSymbol: class MapSymbol(Symbol):
"""Class representing a symbol on the map""" """A BPF map: var is the map's GlobalVariable in the .maps section."""
type: BPFMapType type: BPFMapType = BPFMapType.UNSPEC
sym: ir.GlobalVariable
params: dict[str, Any] | None = None params: dict[str, Any] | None = None

69
pythonbpf/symbols.py Normal file
View File

@ -0,0 +1,69 @@
"""Symbols: what a name in a BPF program resolves to.
Every symbol table in the compiler maps a name to one of these. The base class
carries what all of them share -- the storage behind the name and its IR type;
subclasses add what each kind of name needs on top.
"""
from dataclasses import dataclass
from typing import Any
import llvmlite.ir as ir
@dataclass
class Symbol:
"""The storage a name resolves to, and the type of what is stored there.
`var` is a pointer to that storage: an alloca for a local, a GlobalVariable
for a BPF global or a map, or None for the context parameter (which arrives
as func.args[0] rather than living in a slot).
"""
var: ir.Value | None
ir_type: ir.Type | None
@dataclass
class LocalSymbol(Symbol):
"""One name visible in a BPF function's scope.
`declared_global` marks a name bound by a `global` statement: its var is
the @bpfglobal's GlobalVariable rather than an alloca.
`shadows_global_from` is set when this local's name is also the name of a
@bpfglobal and the function did not declare it `global`: Python makes such
a name a local for the whole body, shadowing the global, and the value is
the line where its first binding ends.
"""
metadata: Any = None
declared_global: bool = False
shadows_global_from: int | None = None
def check_bound_at(self, name: str, lineno: int) -> None:
"""Python's UnboundLocalError, at compile time: a local that shadows a
@bpfglobal is unreadable above its binding. No-op for any other local."""
if self.shadows_global_from is None or lineno > self.shadows_global_from:
return
raise SyntaxError(
f"local variable '{name}' referenced before its assignment on line "
f"{self.shadows_global_from}; add 'global {name}' to use the @bpfglobal"
)
def __iter__(self):
# Three fields on purpose: several call sites tuple-unpack a symbol.
yield self.var
yield self.ir_type
yield self.metadata
@dataclass
class BpfGlobalSymbol(Symbol):
"""A mutable BPF global variable declared with @bpfglobal.
Lands in .bss (zero initializer) or .data (non-zero); libbpf exposes the
section to userspace as a global-data map.
"""
ctype_name: str = ""

View File

@ -3,7 +3,7 @@ from typing import Any
import ctypes import ctypes
from llvmlite import ir from llvmlite import ir
from pythonbpf.local_symbol import LocalSymbol from pythonbpf.symbols import LocalSymbol
from pythonbpf.vmlinux_parser.assignment_info import AssignmentType from pythonbpf.vmlinux_parser.assignment_info import AssignmentType
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)

View File

@ -0,0 +1,22 @@
/* Minimal reference: the four C global-variable classes, nothing else.
* No headers, so every line of IR is attributable. */
#define SEC(name) __attribute__((section(name), used))
typedef unsigned int __u32;
typedef unsigned long long __u64;
__u64 counter; /* zero-init -> .bss, mutable */
__u64 total = 7; /* init -> .data, mutable */
const __u32 version = 3; /* const -> .rodata, clang folds */
const volatile __u32 filter_pid; /* cfg knob -> .rodata, never folded */
SEC("tracepoint/syscalls/sys_enter_nanosleep")
int prog(void *ctx)
{
if (filter_pid == 0)
return 0;
counter += 1;
total += version;
return (int)counter;
}
char _license[] SEC("license") = "GPL";

View File

@ -0,0 +1,29 @@
# `counter += 1` without `global counter` binds `counter` as a local and reads
# it in the same statement, which is UnboundLocalError in Python. Plain
# assignment shadows the global instead (see passing_tests/globals/shadowing.py);
# this shape cannot, because it reads before it binds.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64, c_uint64
@bpf
@bpfglobal
def counter() -> c_uint64:
return c_uint64(0)
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def prog(ctx: c_void_p) -> c_int64:
counter += 1 # noqa: F823, F841 -- missing `global counter` on purpose; this is
# the UnboundLocalError shape, and the compiler must reject it just as loudly
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,25 @@
# Only integer scalar globals are supported in milestone 1; anything else must
# be a clear NotImplementedError, not a half-emitted symbol.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64, c_double
@bpf
@bpfglobal
def ratio() -> c_double:
return c_double(0.5)
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def prog(ctx: c_void_p) -> c_int64:
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,29 @@
# Declaring a parameter `global` is a SyntaxError in Python itself
# ("name 'ctx' is parameter and global"), and the compiler must say the same:
# otherwise reads (local first) and writes would resolve `ctx` to different
# storage.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64, c_uint64
@bpf
@bpfglobal
def ctx() -> c_uint64:
return c_uint64(0)
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def prog(ctx: c_void_p) -> c_int64: # noqa: F811 -- the collision is the test
global ctx # noqa: F811
ctx += 1
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,29 @@
# The assignment below makes `counter` a local for the whole function, so the
# read above it is an UnboundLocalError in Python -- not a read of the global.
# There is no runtime here in which to raise that, so the compiler rejects the
# program instead of silently loading an uninitialised slot.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64, c_uint64
@bpf
@bpfglobal
def counter() -> c_uint64:
return c_uint64(7)
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def prog(ctx: c_void_p) -> c_int64:
print(f"counter {counter}") # noqa: F821, F823 -- reads a local bound below
counter = 1 # noqa: F841 -- ...here, which is what makes the read unbound
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,19 @@
# `global x` naming something that is not a @bpfglobal is a compile error.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def prog(ctx: c_void_p) -> c_int64:
global nosuch
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,35 @@
# Augmented assignment to a struct field: one GEP, load, op, store. Also a
# non-add operator and a sub-64-bit field, which exercises the narrow-on-store
# path of the direct lowering.
from pythonbpf import bpf, section, bpfglobal, compile, struct
from ctypes import c_void_p, c_int64, c_uint64, c_uint32
@bpf
@struct
class data_t:
pid: c_uint64
hits: c_uint32
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def prog(ctx: c_void_p) -> c_int64:
x = 5
x -= 1
dat = data_t()
dat.pid = 10
dat.pid += x
dat.hits = 1
dat.hits <<= 2
print(f"pid {dat.pid} hits {dat.hits} x {x}")
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,31 @@
# The canonical selftest idiom: a per-object event counter. `counter += 1`
# desugars to load/add/store on the global; the local augassign checks the
# desugaring path for stack variables too.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64, c_uint64
@bpf
@bpfglobal
def counter() -> c_uint64:
return c_uint64(0)
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def tick(ctx: c_void_p) -> c_int64:
global counter
counter += 1
x = 5
x += 2
print(f"count {counter} x {x}")
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,34 @@
# Section placement needs no marker: a zero initializer lands the global in
# .bss, a non-zero one in .data, decided by LLVM exactly as for C. Mixed
# widths and signedness also exercise the BTF basic-type emission.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64, c_uint64, c_int32
@bpf
@bpfglobal
def zeroed() -> c_uint64:
return c_uint64(0)
@bpf
@bpfglobal
def preset() -> c_int32:
return c_int32(42)
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def prog(ctx: c_void_p) -> c_int64:
global zeroed
zeroed = preset + 1
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,30 @@
# Reading a global needs no declaration, in every shape a read can take --
# including `x = a_global`, which resolves through the allocation pass rather
# than the expression evaluator and so needs the globals table there too.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64, c_uint64
@bpf
@bpfglobal
def threshold() -> c_uint64:
return c_uint64(42)
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def prog(ctx: c_void_p) -> c_int64:
limit = threshold
doubled = threshold * 2
if threshold > 10:
print(f"limit {limit} doubled {doubled}")
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,28 @@
# A @bpfglobal read in a condition and in a print. Reads need no marker;
# they compile to a plain `load i64, ptr @expected_pid`.
from pythonbpf import bpf, section, bpfglobal, compile
from pythonbpf.helper import pid
from ctypes import c_void_p, c_int64, c_uint64
@bpf
@bpfglobal
def expected_pid() -> c_uint64:
return c_uint64(0)
@bpf
@section("tracepoint/syscalls/sys_enter_nanosleep")
def trace(ctx: c_void_p) -> c_int64:
if expected_pid == pid():
print(f"matched {expected_pid}")
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,38 @@
# Python's scoping rule, applied to BPF globals: assigning a name without a
# `global` statement creates a local that shadows the global for the whole
# function body, and leaves the global's storage alone. `tick` therefore writes
# a stack slot, and `read_back` still sees the initializer.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64, c_uint64
@bpf
@bpfglobal
def counter() -> c_uint64:
return c_uint64(7)
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def tick(ctx: c_void_p) -> c_int64:
counter = 1 # noqa: F841 -- no `global`, so this is a local; that is the test
counter = counter + 1
print(f"local counter {counter}")
return c_int64(0)
@bpf
@section("tracepoint/syscalls/sys_enter_execve")
def read_back(ctx: c_void_p) -> c_int64:
# No assignment here, so the bare name is the global: still 7.
print(f"global counter {counter}")
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,41 @@
# The test_autoattach.c shape: two programs on different attach points writing
# flags into shared global state. Both write the same section's globals.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64, c_uint64
@bpf
@bpfglobal
def prog1_called() -> c_uint64:
return c_uint64(0)
@bpf
@bpfglobal
def prog2_called() -> c_uint64:
return c_uint64(0)
@bpf
@section("raw_tp/sys_enter")
def prog1(ctx: c_void_p) -> c_int64:
global prog1_called
prog1_called = 1
return c_int64(0)
@bpf
@section("raw_tp/sys_exit")
def prog2(ctx: c_void_p) -> c_int64:
global prog2_called
prog2_called = 1
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,36 @@
# The get_cgroup_id_kern.c shape from the kernel selftests: read one global,
# write another, gated on a pid check. Writes require Python's own `global`
# statement and compile to `store i64 %v, ptr @cg_id`.
from pythonbpf import bpf, section, bpfglobal, compile
from pythonbpf.helper import pid, get_current_cgroup_id
from ctypes import c_void_p, c_int64, c_uint64
@bpf
@bpfglobal
def expected_pid() -> c_uint64:
return c_uint64(0)
@bpf
@bpfglobal
def cg_id() -> c_uint64:
return c_uint64(0)
@bpf
@section("tracepoint/syscalls/sys_enter_nanosleep")
def trace(ctx: c_void_p) -> c_int64:
global cg_id
if expected_pid == pid():
cg_id = get_current_cgroup_id()
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,22 @@
# A local named after an XDP action must shadow the helper constant table,
# in return position too. clang agrees: a local legally shadows an enum
# constant, and the local's value is what returns (tests/c-form reference).
# Before the fix this returned the hardcoded 2 while XDP_PASS held 55.
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def prog(ctx: c_void_p) -> c_int64:
XDP_PASS = 55
return XDP_PASS
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -0,0 +1,41 @@
# Name-resolution order under collision with vmlinux enum constants:
# local wins over global wins over vmlinux, consistently in expressions,
# f-strings, and returns.
#
# clang's take on the same collisions (tests/c-form): a local shadowing an
# enum constant is legal and wins; a file-scope variable colliding with one is
# a hard error. PythonBPF follows Python's rebinding semantics instead for the
# global case -- the @bpfglobal wins -- and logs a compile-time warning so the
# shadowing is never silent.
# XDP_ABORTED's import is load-bearing despite being "unused": it is what
# registers the enum with the compiler, so the local below has something to
# shadow. Python-level unused is the point.
from vmlinux import XDP_ABORTED, XDP_TX # noqa: F401
from pythonbpf import bpf, section, bpfglobal, compile
from ctypes import c_void_p, c_int64, c_uint64
# Shadows the vmlinux enum constant XDP_TX (warns at compile time; reads of
# XDP_TX below resolve to this global, value 77, not the enum value 3).
@bpf
@bpfglobal
def XDP_TX() -> c_uint64: # noqa: F811 -- the collision is the test
return c_uint64(77)
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def prog(ctx: c_void_p) -> c_int64:
XDP_ABORTED = 55 # noqa: F811 -- local shadows the enum (value 0)
x = XDP_ABORTED + XDP_TX
print(f"local {XDP_ABORTED} global {XDP_TX}")
return c_int64(x)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()

View File

@ -32,3 +32,13 @@
"failing_tests/vmlinux/assignment_handling.py" = {reason = "Assigning vmlinux enum value (XDP_PASS) to a local variable not yet supported", level = "ir"} "failing_tests/vmlinux/assignment_handling.py" = {reason = "Assigning vmlinux enum value (XDP_PASS) to a local variable not yet supported", level = "ir"}
"failing_tests/xdp_pass.py" = {reason = "XDP program using vmlinux structs (struct_xdp_md) and complex map/struct interaction not yet supported", level = "ir"} "failing_tests/xdp_pass.py" = {reason = "XDP program using vmlinux structs (struct_xdp_md) and complex map/struct interaction not yet supported", level = "ir"}
"failing_tests/globals_read_before_shadow.py" = {reason = "Reading a name above the assignment that makes it a local shadowing a global is UnboundLocalError in Python, and a compile error here", level = "ir"}
"failing_tests/globals_undeclared_name.py" = {reason = "`global x` naming something that is not a @bpfglobal is a compile error", level = "ir"}
"failing_tests/globals_bad_type.py" = {reason = "Non-integer-scalar globals are not supported in milestone 1 (NotImplementedError by design)", level = "ir"}
"failing_tests/globals_augassign_shadowing.py" = {reason = "`x += 1` on a global name without `global` binds a local and reads it unbound: UnboundLocalError in Python, a compile error here", level = "ir"}
"failing_tests/globals_parameter_and_global.py" = {reason = "A parameter may not be declared global (Python: name is parameter and global)", level = "ir"}

81
tests/test_globals_ir.py Normal file
View File

@ -0,0 +1,81 @@
"""
Global variables: where the loads and stores go.
Levels 1 and 2 only prove that the passing_tests/globals cases compile. What
those cases are *about* is which storage a name resolves to: the @bpfglobal's
symbol, or a stack slot that shadows it. This test reads the IR of each BPF
function and checks exactly that, so the scoping rules are pinned rather than
inferred from "it compiled".
Storage is identified by the operand: `@"name"` is the global's symbol, and
`%"name"` is the alloca of a local of the same name.
"""
import re
from pathlib import Path
import pytest
from tests.framework.compiler import run_ir_generation
GLOBALS_DIR = Path(__file__).parent / "passing_tests" / "globals"
def _function_bodies(ir_text: str) -> dict[str, str]:
"""Map each defined function's name to the text of its body."""
return {
m.group(1): m.group(2)
for m in re.finditer(r'define [^\n]*@"(\w+)"[^\n]*\n\{(.*?)\n\}', ir_text, re.S)
}
def _stores_to(body: str, operand: str) -> int:
return len(re.findall(rf"store i\d+ [^,]+, i\d+\* {re.escape(operand)}", body))
def _loads_from(body: str, operand: str) -> int:
return len(re.findall(rf"load i\d+, i\d+\* {re.escape(operand)}", body))
# file -> {function: [(operand, expected stores, expected loads)]}
# Expectations are exact counts, so an accidental extra access is caught too.
CASES = {
# `global counter` writes through: load, add, store on the symbol, no slot
# (the second load is the print of the new value).
"augassign_counter.py": {
"tick": [('@"counter"', 1, 2), ('%"counter"', 0, 0)],
},
# `global cg_id` inside an if: the store still targets the symbol.
"write_scalar.py": {
"trace": [('@"cg_id"', 1, 0), ('%"cg_id"', 0, 0)],
},
# Reads need no declaration and resolve to the symbol.
"copy_to_local.py": {
"prog": [('@"threshold"', 0, 3), ('%"threshold"', 0, 0)],
},
# Python's scoping rule: without `global`, `counter = 1` binds a local for
# the whole body of `tick`, so every access there is the stack slot and the
# symbol is untouched; `read_back`, which assigns nothing, reads the symbol.
"shadowing.py": {
"tick": [('%"counter"', 2, 2), ('@"counter"', 0, 0)],
"read_back": [('@"counter"', 0, 1), ('%"counter"', 0, 0)],
},
}
@pytest.mark.parametrize("name", list(CASES))
def test_globals_ir_storage(name, tmp_path):
ll_path = tmp_path / name.replace(".py", ".ll")
run_ir_generation(GLOBALS_DIR / name, ll_path)
bodies = _function_bodies(ll_path.read_text())
for func, expectations in CASES[name].items():
assert func in bodies, f"{name}: no function '{func}' in the IR"
body = bodies[func]
for operand, stores, loads in expectations:
assert _stores_to(body, operand) == stores, (
f"{name}::{func}: expected {stores} store(s) to {operand}"
)
assert _loads_from(body, operand) == loads, (
f"{name}::{func}: expected {loads} load(s) from {operand}"
)