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
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
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
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
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
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
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
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
- make test/test-cov/test-verifier now depend on a 'vmlinux' target that
regenerates vmlinux.py from the running kernel's BTF and symlinks it
into every directory under tests/, replacing the stale, duplicated
vmlinux.py fixtures that used to be committed there.
- collector.py now skips the 'vmlinux.py' filename when collecting BPF
test cases, since it's a fixture module, not a test program - it was
previously being mis-collected and compiled as a bogus test.
- functions_pass.py: llvmlite >=0.49 renamed the 'nocapture' argument
attribute to 'captures(none)'.
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) <noreply@anthropic.com>
Style only, no behaviour change and no IR change. Keeps `ruff check --select
SIM` clean on the files this branch touches.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The previous commits emit `llvm.pt_regs:0:136$0:17:0` for `ctx.cs`, which llc
happily turns into a CO-RE relocation, but the local BTF it is resolved
against described member 17 as a NAMED, EMPTY composite:
'_0' type_id=4 bits_offset=1088
[4] STRUCT '(anon)' size=8 vlen=0
libbpf walks a CO-RE access string by member index into the local type and
then matches by field NAME in the target type, so both halves of that break
it: index 0 into a vlen=0 composite has nothing to land on, and a local
member called `_0` cannot be paired with the kernel's anonymous one. The
object would build cleanly and then fail to load.
Emit anonymous members the way a C compiler does: unnamed, with a real
DW_TAG_union_type (or structure, for an anonymous struct) carrying their
members in declaration order. The emitted BTF now reads
'(anon)' type_id=4 bits_offset=1088
[4] UNION '(anon)' size=8 vlen=3
'cs' ... 'csx' ... 'fred_cs' ...
which is the same shape clang produces for the equivalent C and the same
shape `bpftool btf dump file /sys/kernel/btf/vmlinux` reports.
Gated on the struct declaring `_anonymous_`, and it bails back to the old
opaque member for anything it cannot describe faithfully. Across every
vmlinux/xdp test program the set of emitted globals, every relocation string
and every instruction are unchanged; the only diffs are the new DWARF nodes
and the DWARF node renumbering they cause, in the two pt_regs programs.
This is the one part of the fix that cannot be verified without loading a
program, so it is kept as its own commit.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Reading a context field narrower than a register was hardcoded to
struct_xdp_md's i32 fields in three places that had to agree with each other:
the destination alloca in allocation_pass, the zext in load_ctx_field, and
the store in assign_pass. struct pt_regs' cs and ss are 2 bytes, so a second
special case would have been needed.
Replace all three with the general rule: a context field is loaded at its
natural width and zero-extended to i64, so its destination is i64.
allocation_pass gains the same context discriminator load_ctx_field uses
(a context argument has no alloca of its own), so non-context field reads,
which go through load_struct_field and bpf_probe_read_kernel, keep their
natural width and are untouched.
struct_xdp_md's generated IR is byte-identical, as is every other vmlinux/xdp
test program's; the only diff in the whole corpus remains the four new globals
from the previous commit.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A field lifted out of an anonymous member needs an access string that walks
into that member, so `struct pt_regs.cs` is `llvm.pt_regs:0:136$0:17:0`
(member 0 of anonymous member 17) rather than the flat `$0:<index>` form.
This is byte-for-byte what clang emits for the equivalent C, verified against
`__builtin_preserve_access_index(ctx->cs)` on a struct with the same shape,
and the indices and offsets agree with `bpftool btf dump file
/sys/kernel/btf/vmlinux`.
Only fields carrying an access path take the new path; every other field
keeps the existing flat and indexed/array forms unchanged. The only .ll diff
across all vmlinux/xdp test programs is four brand new globals for cs, csx,
ss and ssx. No pre-existing relocation string changes.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
On this kernel `struct pt_regs` wraps `cs` and `ss` in anonymous unions.
ctypes lifts those names onto the parent class, exactly as C does, but the
parser only walked the top-level `_fields_`, so `cs` and `ss` were unknown to
the compiler and `ctx.cs` blew up.
Register the members of an anonymous member as fields of the parent, one
level deep, taking the ABSOLUTE offset ctypes reports on the parent (no
arithmetic) and recording the access path (anonymous member index, member
index). The anonymous member itself stays registered as before.
Deliberately conservative: only scalar ctypes members are flattened. Nested
vmlinux structs (`fred_cs`, `fred_ss`) and bitfields are skipped with a
warning rather than half-registered, and a flattened member never overwrites
an existing top-level field of the same name. Overlapping members are kept as
distinct fields, since `cs` and `csx` both legitimately live at offset 136.
Flattened fields are not yet emitted: IR generation and DWARF generation skip
them, and critically they do not consume a top-level field index, so existing
CO-RE names are untouched. Every vmlinux/xdp test program still compiles to a
byte-identical .ll. Entirely inert for any struct without `_anonymous_`.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Carries the chain of member indices from the enclosing struct down to a
field, so a field that does not sit at the top level of the struct can still
describe where it lives. Defaults to None, which keeps meaning "this field is
a plain top-level member".
Pure data, nothing reads it yet, generated IR is unchanged.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
has_field() consulted hasattr() on the ctypes class while get_field_type()
indexed the parsed members dict. For any member ctypes exposes but the
vmlinux parser never registered, has_field() said True and get_field_type()
then died with a raw KeyError.
Both now consult the parsed members dict, and a lookup that misses raises a
ValueError that distinguishes "no such field" from "field exists in
vmlinux.py but the parser does not support it yet".
get_field_index() additionally derives the index from the ctypes _fields_
list (the C declaration order) instead of the insertion order of the parsed
members dict, so it no longer depends on the two happening to coincide.
No change to generated IR: every vmlinux/xdp test program compiles to a
byte-identical .ll.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
_allocate_for_attribute reached for `metadata.__name__` whenever the
base symbol was not a known user struct, but `metadata` is only a struct
class for struct-typed symbols. For a symbol carrying None (any plainly
typed local) or a ctypes class (a `c_void_p` context parameter), that
raised AttributeError instead of reporting the unsupported access.
Resolve the name via getattr and fall through to the existing
"struct type not found" diagnostic when there is none.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
process_func_body only entered the context parameter into local_sym_tab
when its annotation was a vmlinux struct, so a program declared as
`def prog(ctx: c_void_p)` had no `ctx` symbol at all. Passing `ctx` to a
helper that takes a raw pointer -- probe_read(dst, size, ctx) -- failed
with "Variable 'ctx' not found in local symbol table".
Register the parameter for plain ctypes annotations too, keeping `var`
as None: that is the established sentinel meaning "this symbol is the
context parameter, read it from func.args[0]" (see
VmlinuxHandler.handle_vmlinux_struct_field). Metadata holds the
annotated Python type, mirroring the vmlinux branch.
Teach the consumer side accordingly: get_or_create_ptr_from_arg now
recognises the sentinel and hands back the function's first argument
instead of an alloca. The special case lives at the call site rather
than inside get_var_ptr_from_name so that helper stays a pure symbol
table lookup -- the call site already has `func` and `builder` in scope,
and get_var_ptr_from_name has no other callers to update.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>