Commit Graph

1057 Commits

Author SHA1 Message Date
869cf61869 Examples: Draw bpfsnake's terminal board exactly as the bpftrace script does
The terminal mode prints the original's 12x50 board of #, $ and @ from
the top-left corner and exits when the snake dies. Both modes go back to
the original's board size and BEGIN state, since the walls live in the
kernel's tick.
2026-09-26 02:14:14 +05:30
bc56dd821a Examples: Let bpfsnake draw in the terminal with --terminal
Both front ends share one Game that queues turns, drives the kernel's
tick and reads the maps back. The terminal one reads keys in cbreak mode
(an arrow's last byte is already the kernel's key code) and draws on the
alternate screen, so it needs no pygame; pygame is imported only for the
window.
2026-09-25 18:53:00 +05:30
851c7efea4 Examples: Draw bpfsnake with pygame and steer it from the window
A pygame window takes the keyboard from the terminal, so the pty_write
probe would never see a key. Python writes the key code into the state
map instead, one queued turn per tick, ignoring reversals. The board
grows to 20x30 with food anywhere inside the walls, and the snake to 32.
2026-09-25 18:45:09 +05:30
cba2c894b3 Examples: Port bpfsnake, the game logic in eBPF and the board in Python 2026-09-25 18:25:54 +05:30
35d176692f Tests: probe_read_kernel into a scalar, shared ctx names, map value compares 2026-09-25 18:25:54 +05:30
1dfb22d3dc Core: Compare map values by value, not by address
With a map lookup on both sides, both operands are pointers of one type,
so the depth-normalising path emitted a pointer compare. Load both sides
through get_typed_operand instead, which also picks the predicate from
the map's declared value sign.
2026-09-25 18:25:53 +05:30
95a986e6bb Core: Give each function its own context DILocalVariable
add_debug_info caches nodes by operands, so a second program with a
same-named context of the same vmlinux type got the first one's variable,
already scoped to the first function. Scoping it again made a metadata
cycle that llvmlite recursed on forever.
2026-09-25 18:25:30 +05:30
d992493288 Core: Let probe_read_kernel read into a scalar, from a register address
A non-char-array destination is sized from its pointee, and a 64-bit
integer source (a pt_regs field) is the address to read from, as with
(void *)ctx->si in C. Also export probe_read_kernel from pythonbpf.helper;
it had an emitter but no importable name.
2026-09-25 18:25:30 +05:30
107f035014 Merge #106 (loops) for bpfsnake
# Conflicts:
#	tests/test_config.toml
2026-09-25 18:11:13 +05:30
cb1952db17 Merge #105 (selftest roadmap tests, ArrayMap, narrow ctx stores) for bpfsnake 2026-09-25 18:09:13 +05:30
49ed2cf127 Core: Report an unknown name in an operand as undefined
get_typed_operand fell through its Name branch for a name that is not a
local, a global or a vmlinux constant, and raised the generic
"Unsupported operand type" meant for unknown node kinds. Since return
goes through it, forgetting `from vmlinux import XDP_PASS` produced that
message; it says "Undefined variable XDP_PASS" now, like every other
read.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-25 10:28:56 +05:30
ad6adb14c9 x 2026-09-25 10:26:22 +05:30
3a984dd9e2 Revert "Core: Export every XDP action from pythonbpf.helper"
This reverts commit 55fb6d6b9a.
2026-09-25 10:15:49 +05:30
55fb6d6b9a Core: Export every XDP action from pythonbpf.helper
helpers.py defined all five and return_utils mapped them, but only
XDP_DROP and XDP_PASS were exported, so the xdp_tx port had to import
XDP_TX from vmlinux and live under vmlinux/, skipped on any host without
a generated module. It imports from pythonbpf.helper and lives under
xdp/ now, returning XDP_TX bare like its siblings and the C original,
which is the shape the return fast path resolves without vmlinux.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-25 01:25:35 +05:30
d64932774c Docs: Refresh the audit numbers after the classifier fixes
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-25 01:18:56 +05:30
49e74858a6 Tests: Let a verifier-level xfail name the rejection it expects
Every xfail is strict with raises=Exception, so a verifier-level
negative fixture counted any rejection as the expected one, including
one caused by a codegen regression, or by bpftool failing. A verifier
entry may now carry match = "..."; the harness attaches it as a
verifier_match marker and test_kernel_verifier fails, through
pytest.fail (not swallowed by raises=Exception), when the program is
rejected for any other reason. xdp_devmap_helpers pins its documented
"invalid bpf_context access".

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-25 01:18:54 +05:30
3de9832792 Core: Implement ArrayMap as BPF_MAP_TYPE_ARRAY
process_array_map was a stub raising NotImplementedError while ArrayMap
was exported from pythonbpf.maps as if usable. The lowering is the hash
map's with a different type constant: the same lookup/update/delete
helpers, and the kernel fixes the key at a 4-byte index. The lookup
allocation path accepts ARRAY alongside HASH, the audit tool lists
ARRAY as supported, and the array_map_lookup_update case is a passing
test now instead of a strict xfail.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-25 01:18:52 +05:30
efe58fc396 Core: Treat an integer vmlinux field as its IntTy in assignments
The Field branch of handle_variable_assignment rebuilt the field's type
by name and duplicated the integer convert() path, and ctypes_to_ir
raises NotImplementedError for a pointer or array ctype before the
logged error is reached. An integer Field is now normalised to its
declared IntTy (field_int_type) before the integer path, in both
variable and struct-field assignment, so ctx fields go through the same
convert() call as everything else; the Field branch keeps only the
non-integer error.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-25 01:17:00 +05:30
057b68c4d7 Core: Let every integer ctypes constructor declare a slot of its width
_allocate_for_call recognised only c_int32, c_int64, c_uint32, c_uint64
and c_void_p, so queue = c_uint16(0) fell through to an i64 slot and a
later store of a u32 field into it never narrowed. Any integer ctypes
constructor now declares a slot of its width, which is what the
ctx_field_narrow_store test claimed to pin; the IR assertion pins it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-25 01:16:26 +05:30
cf80aadd35 Tools: Fix four classifier mistakes in the selftest audit
- The subprog_call pattern also matched SEC("?..."), so every
  non-autoloaded program counted as a BPF-to-BPF call blocker, in
  contradiction with the soft rule for the same syntax.
- The kfunc pattern matched any bpf_xdp_* or bpf_skb_* call, which are
  ordinary helpers (bpf_skb_store_bytes is in SUPPORTED_HELPERS). Only
  the kfunc families keep those prefixes; an unsupported helper is still
  a hard blocker, classified as one.
- strip_comments removed // inside string literals, truncating section
  names like SEC("uprobe//proc/self/exe:func") and classifying the file
  as a shim. Strings are matched first and kept.
- Every bpf_map_* helper not in SUPPORTED_HELPERS was dropped before the
  unsupported-helper test, so bpf_map_push_elem and friends never showed
  up as blockers. The membership test classifies them now.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-25 01:15:58 +05:30
598e3b4efa Tests: Skip vmlinux tests only when vmlinux.py is absent
except Exception turned every import-time defect in the generated module
into a skip of every vmlinux test, so CI could pass with no vmlinux
coverage. ImportError (no module) skips; anything else propagates.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-25 01:15:55 +05:30
89b7eb6d27 Tests: Indent the loop C reference with spaces
The remove-tabs pre-commit hook rejects tab indentation outside docs/ and
Makefiles, which failed the Format job.
2026-09-25 00:37:05 +05:30
5fb3c8ded4 Tests: Loops pass now, plus the cases the lowering promises
- passing_tests/loops/: the seven range/while/break/continue/nested tests
  move over from failing_tests/, joined by rebinding the loop variable, a
  negative step, loop else-branches, and a helper-bounded loop over a
  @bpfglobal that survives -O2 as a real loop for the verifier.
- failing_tests/loops/: break outside a loop, and a non-literal range step.
- for_map_items stays xfail: map iteration needs its own design.
- c-form/loops.bpf.c: the clang reference the lowering was checked against.
2026-09-25 00:30:10 +05:30
24e7febd8d Core: Lower for-over-range and while loops, with break and continue
`for i in range(...)` steps a hidden induction counter, allocated in the
entry block next to the loop variable, and copies it into the variable each
iteration, so rebinding the variable in the body leaves the trip count alone
as in Python (and the loop stays visibly bounded for the verifier). The
counter is 64-bit, signed unless the bounds make C's arithmetic unsigned.
Bounds are evaluated once, before the loop; the step must be a nonzero
integer literal, because its sign picks the loop test.

`while` re-evaluates its test at the top of each iteration. `break` and
`continue` branch through a loop-target stack on the compilation context;
outside a loop they are a SyntaxError, as in Python. A loop's else-branch
runs on normal exit only. Anything but range() as the iterable is rejected
with NotImplementedError.

The allocation pass now descends into loop bodies and counts helper temps in
loop headers. Checked against clang -O2 on tests/c-form/loops.bpf.c: the
constant-bound cases fold to the same ret, and a helper-bounded loop gets the
same rotated loop.
2026-09-25 00:19:52 +05:30
919d99477f Core: Lower if-branches in the function's return type
handle_if processed its branches without passing ret_type down, so a
return inside an if fell back to process_stmt's i64 default: a -> c_int32
function got `ret i64 7`, which llc rejects. The branches now go through
process_block, which threads ret_type and stops at a statement that ends
the block instead of emitting after its terminator.
2026-09-25 00:19:40 +05:30
c340ebf82c Tests: Annotated assignment passes now 2026-09-25 00:11:35 +05:30
7ecc737cf9 Core: Lower annotated assignment (x: c_int32 = 0)
The annotation types the slot, so `x: c_int32 = 0` is an i32 where the
literal alone would give an i64; the store goes through the same
handle_variable_assignment plain assignment uses. A bare `x: T` makes the
slot and binds nothing.

The already-bound and global-shadowing bookkeeping that Assign allocation did
inline moves into _bind_name, which both statements now call.
2026-09-25 00:11:35 +05:30
298c140ee7 Tests: Port five more selftests found by re-running the corpus audit
veristat_foo (three socket programs) is clean. test_perf_link,
test_enable_stats and test_cgroup_link count with __sync_fetch_and_add, which
becomes a plain `x += 1` tagged WORKAROUND(atomics) for a mechanical sweep
once atomics exist. connect4_dropper compares against bpf_htons(port), written
out as shifts on the low 16 bits. All five pass at IR, llc and verifier level,
and bring perf_event, raw_tracepoint/sys_enter, cgroup_skb/egress and
cgroup/connect4 under test.

The porting notes gain the third batch, the atomics tag, the current blocker
histogram from the checked-in audit tool, and how to re-run it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DLMW3X7opqAPH6bjmTVkr7
2026-09-24 16:31:15 +00:00
e0d4d1eada Tools: Check in the selftest corpus classifier
The porting assessment was produced by a one-off script that scored every
program under tools/testing/selftests/bpf/progs against the compiler's
envelope; the notes recommended keeping it so the numbers can be regenerated
after each feature lands. This is that script, rebuilt: it strips comments,
skips include-shims and header-only fixtures, and reports per program the
hard blockers (language gaps) and soft flags (porting costs), with a
histogram and a near-miss listing. The helper, map and construct lists at
the top are the envelope and are maintained by hand.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DLMW3X7opqAPH6bjmTVkr7
2026-09-24 16:31:15 +00:00
5e70b8f0fc Tests: Port sixteen more kernel selftests now that scalar globals exist
Every program on the selftest audit's Tier 1 and Tier 2 lists that the compiler
can express today: xdp_dummy, priv_prog, test_xdp_link, xdp_tx, tc_dummy,
test_tc_bpf, cgroup_mprog, cgroup_skb_direct_packet_access, test_signed_loader,
test_signed_loader_data, test_netfilter_link_attach, kprobe_multi_empty,
uprobe_multi_bench, uprobe_multi_usdt, test_link_pinning and
test_xdp_devmap_helpers. Fifteen pass at every level, bringing tc, tcx,
cgroup/getsockopt, cgroup_skb, socket, netfilter, kprobe.multi, uprobe.multi,
usdt and tp_btf program types under test for the first time.

test_xdp_devmap_helpers is a negative fixture upstream: reading egress_ifindex
is only legal with expected_attach_type = BPF_XDP_DEVMAP and the driver asserts
the plain load fails. It is a strict verifier-level xfail here for the same
reason, until expected_attach_type can be expressed.

The porting notes record the batch and why each remaining program on the two
lists is still out of reach.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DLMW3X7opqAPH6bjmTVkr7
2026-09-24 15:59:35 +00:00
0bdea85020 Core: Store a context field into a narrower slot through convert()
A sub-register context field is loaded zero-extended to i64, and the
assignment path accepted it only into a 64-bit slot or one whose type was
exactly the field's declared type. The second case never worked in practice:
`data_end = skb.data_end` into a c_uint32 global died in llvmlite with
"cannot store i64 to i32*" because the value was still i64.

Route the store through convert(), sizing from the physical value and signing
from the field, like every other integer store since the signedness work: a
no-op into an i64 slot, a trunc into anything narrower. Found by porting
cgroup_skb_direct_packet_access.c, which is that exact statement.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DLMW3X7opqAPH6bjmTVkr7
2026-09-24 15:59:35 +00:00
3ffba47a80 Tests: Replace the WORKAROUND(globals) HashMaps with real @bpfglobal scalars
The selftest spike substituted a one-entry HashMap for every upstream global
because PythonBPF had no global variable support. Integer-scalar @bpfglobal
support has since landed, so the three affected ports now declare the upstream
globals directly: get_cgroup_id reads expected_pid and writes cg_id, autoattach
shares prog1_called/prog2_called between two programs, and perf_skip reads ip.
perf_skip stays a strict xfail on the nested ctx.regs.ip access.

Update the tests README and porting notes accordingly; the WORKAROUND tag no
longer exists in the tree.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DLMW3X7opqAPH6bjmTVkr7
2026-09-24 15:15:58 +00:00
708b5afa48 Merge remote-tracking branch 'origin/master' into claude/pythonbpf-state-replication-g23gij
# Conflicts:
#	tests/test_config.toml
2026-09-24 15:14:21 +00:00
dc628ee5b5 Merge pull request #101 from pythonbpf/feat/integer-signedness
integer signedness made consistent.
2026-09-24 19:59:05 +05:30
f727bfc65e Docs: Note the packet-pointer-field gotcha, with the planned mechanism
xdp_md.data/data_end/data_meta and __sk_buff.data/data_end are u32 in
C and packet pointers to the verifier, so arithmetic on them directly
is rejected as 32-bit pointer arithmetic, for C and for us alike. A
TODO at the point where a field's rank is decided describes the planned
fix (64-bit pointer rank for those fields, no cast needed), and the
user guide documents the workaround until then: copy to a local or cast
through c_void_p.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 19:56:30 +05:30
6caab6f704 Tests: Rank the ctx-field case on a scalar field, not the packet pointer
xdp_md.data is a u32 in C, but the verifier tracks it as a packet
pointer and rejects 32-bit arithmetic on it: "R0 32-bit pointer
arithmetic prohibited", the same for a C program, which is why C casts
it through (void *)(long) first. The u32 ranking the test pins is the
correct one; it just has to be pinned on a field that is a scalar to the
verifier too. ingress_ifindex is.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 19:53:30 +05:30
6b19bf6732 Tests: Unsigned augmented assignment, helper results, map values, ctx field rank
One IR-shape case per fix: u32 >>= / //= / %= emit lshr/udiv/urem;
ktime() >> 1 and pid() // 3 emit lshr/udiv; p >> 63 on a c_uint64 map
value is lshr; ctx.data - c_int32 is a u32 subtraction with the
trunc/zext pair rather than a 64-bit one.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 19:31:11 +05:30
e35d4c0327 Core: Pass the result sign to the operator in augmented assignment
The binary-operation path chooses sdiv/udiv, srem/urem and ashr/lshr from
the promoted type; the augmented-assignment path computed the same
promoted type and then called apply_binop without it, so u32 >>= 4 was
an ashr and u32 //= 3 an sdiv. Same call as the binop path now.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 19:30:37 +05:30
9cd8e1037a Core: Review nits on the signedness branch
- A global's descriptor is built from the loaded value, not from None.
- get_operand_value, the [0] wrapper over get_typed_operand, had no
  callers left; removed with its export.
- infer_int_type's map branch names the map's declared value type for
  what it is (value_ctype), says that the key argument plays no part,
  and applies only to lookup: update and delete return a status, not a
  value of the map's type.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 19:30:37 +05:30
532dc0f808 Core: Rank ctx fields and map values by their declared types
Two descriptors were built from the physical value instead of the
declaration. A sub-register vmlinux field is widened to i64 by
load_ctx_field, and its descriptor took that width, so ctx.data - k with
a c_int32 k was a 64-bit subtraction where C makes it a u32 one. A
map-lookup local dereferenced past its slot took the physical pointee
(i64, signed by default) and dropped the map's declared value ctype kept
in the symbol's metadata, so p >> 63 on a c_uint64 value was an ashr.
Both now read the declaration; the physical width still comes from the
value, as everywhere else.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 19:30:37 +05:30
26604b9846 Core: Give a helper call's value the sign its registry entry declares
The registry types ktime, pid, uid, random, cgroup_id and smp_processor_id
as unsigned, and undeclared locals initialised from them already took
that sign. The expression value did not: each emitter returns
(value, plain i64), so ktime() >> 1 was an ashr and pid() // 3 an sdiv.
The dispatcher now substitutes the registered descriptor when the widths
agree, in one place instead of in every emitter.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 19:30:37 +05:30
c52a5f592d Merge branch 'master' into feat/integer-signedness 2026-09-24 17:09:54 +05:30
78ec75a4d1 Tests: Bool widening and narrowing
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 16:53:03 +05:30
a230b440b9 Core: Give bools C's rules: widen to 0 or 1, narrow by comparing with zero
A bool is ir.IntType(1), so convert() handled it as a 1-bit integer: a
bool slot's plain descriptor read as signed and True sign-extended to
-1 on the way out, and an integer narrowed to a bool by truncation, so
2 became false. Both predate this branch. C widens a bool to 0 or 1 and
narrows to it with != 0, and Python's truthiness agrees on the second.

signedness() now answers unsigned for any 1-bit integer whatever it is
wrapped in, convert() narrows to width 1 with icmp ne 0, and a bool
constant's slot carries the unsigned descriptor like the comparison
results already do.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 16:52:59 +05:30
3179549760 Add LLVM optimizer (#104)
* Add LLVM optimizer

* expr_pass: add bpf_passthrough attributes to make tests pass
2026-09-23 21:05:33 +05:30
8290fecac2 tests: Add loop and AnnAssign xfail tests (#103)
- process_stmt now raises NotImplementedError on an unsupported statement
  instead of warning: a dropped statement silently changes what the
  program means (a for/while loop compiled to nothing).
- failing_tests/loops/: 8 xfail tests for for/while/break/continue/nested
  loops and map iteration
- failing_tests/assign/annotated_assign.py: xfail for `x: c_int64 = 0`
  (ast.AnnAssign is not handled)
2026-09-23 18:08:27 +05:30
eaaa12eecb Tests: Return of a map value, return of a struct, enum-constant rank
return/map_value.py is the C shape `if (p) return *p;`; return_struct.py
is the type error convert() now raises; vmlinux/enum_rank.py pins the
u32 trunc/zext pair for `XDP_PASS - k`. test_signedness_ir.py takes
paths under passing_tests so it can assert on all three, and skips the
vmlinux case when vmlinux.py is not importable, as the harness does.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-18 17:52:30 +05:30
ca92f2ab77 Core: Rank an enum constant as C's int, not as i64
An enum constant has type int in C whatever the enum's underlying type
is; clang emits `sub nsw i32` + sext for `XDP_PASS - k` and reserves the
enum's u32 for variables of the enum type. The vmlinux handler was
typing constants as i64, which made `XDP_PASS - k` with an unsigned k a
signed 64-bit operation instead of C's u32 one. The constant's C rank
is now decided once, in type_deducer.int_literal_type, shared by
literals and enum constants, and the handler returns it as the
descriptor so both operand typing and local inference read it from
the source.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-18 17:52:28 +05:30
8e802e8532 Core: Return through the same value path as every other consumer
A pointer used where a value is expected is dereferenced to it, with a
null check, in helper arguments, printk arguments, binary-operation
operands and comparisons, all through deref_to_depth. return was the
one consumer that never joined that convention, so `return p` on a map
lookup emitted `ret i64*` and left it to llc to reject. handle_return
now goes through get_typed_operand, which is that path, and converts
the result to the declared return type like the augmented-assignment
store does.

convert() no longer passes a non-integer through silently: every
caller either checks both sides or is on an integer-only path, so what
reaches that branch is a type error, and it is raised with both types
named instead of surfacing from llc with an IR line number. Returning
a struct value is the case that now fails at compile time.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-18 17:52:23 +05:30
359ddbd031 Merge remote-tracking branch 'origin/master' into feat/integer-signedness 2026-09-18 17:46:35 +05:30