Compare commits

..

6 Commits

Author SHA1 Message Date
6b76b74a3b add CI workflow to run the test suite
Runs make test on every push to master and every pull_request. 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 there.

Ubuntu's default apt packages need three adjustments to actually run
this: bpftool is a virtual package provided by linux-tools-generic
whose binary needs to be found and put on PATH manually; ctypeslib2's
clang bindings default to the latest PyPI release, which doesn't match
Ubuntu's libclang-16, so pin to clang==16.0.6 (older bindings stay
forward-compatible with a newer system libclang); and llvmlite>=0.49
emits IR using the 'captures(none)' attribute spelling, matching the
LLVM 22.1.0 it bundles internally, which Ubuntu's default LLVM 18 (and
even 19) can't parse - install a matching-generation LLVM 22 from
apt.llvm.org instead of the distro default.

Also add ctypeslib2 and a pinned clang to the test extra: make test
now regenerates vmlinux.py via tools/vmlinux-gen.py, which needs
clang2py, and that dependency was previously only installed ad hoc in
local dev venvs.
2026-08-30 20:54:10 +05:30
5c05b11153 fix ruff-format violation in vmlinux-gen.py 2026-08-30 20:50:38 +05:30
c02b769b15 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.
2026-08-30 20:23:12 +05:30
559d0570ff regenerate and symlink a single master vmlinux.py for make test
- 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)'.
2026-08-30 19:49:28 +05:30
7b704cbe0b disambiguate clang2py's generic anonymous-field names in vmlinux-gen.py
Prevents ctypes _fields_ assignment collisions when multiple anonymous
struct/union members across different structs get the same generic
'_N' name from clang2py.
2026-08-30 19:49:28 +05:30
03b1232a77 Merge pull request #91 from pythonbpf/fix/register-state-dump-keyerror
Fix register state dump keyerror for register_state_dump test
2026-08-30 19:48:27 +05:30
6 changed files with 268 additions and 12 deletions

92
.github/workflows/test.yml vendored Normal file
View File

@ -0,0 +1,92 @@
# Runs the pytest suite (IR generation + LLC compilation). Kernel verifier
# tests additionally need passwordless sudo and a kernel with BTF/BPF
# enabled, which isn't guaranteed on every runner, so we probe for working
# sudo first and only attempt them if it's there.
#
# `push` is scoped to master only: branches here live in this repo rather
# than forks, so a push to a branch with an open PR would otherwise fire
# both `push` and `pull_request` for the same commit, running everything
# twice. `pull_request` covers feature branches; `push` still gives master
# a post-merge check.
name: Test
on:
workflow_dispatch:
push:
branches: [master]
pull_request:
jobs:
test:
name: Test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
- name: Install system dependencies
run: |
sudo apt-get update
sudo apt-get install -y lsb-release wget software-properties-common gnupg linux-tools-common linux-tools-generic
# Ubuntu's default `llvm`/`clang` packages (LLVM 18 on noble) are
# too old to assemble the IR llvmlite>=0.49 emits: llvmlite's
# ArgumentAttributes only knows the 'captures(none)' spelling of
# the renamed 'nocapture' attribute, matching the LLVM 22.1.0 it
# bundles internally - and an llc from an older LLVM (verified:
# 19 still rejects it as a parse error) can't read that attribute
# in the .ll text. Install a matching-generation LLVM from
# apt.llvm.org instead of the distro default, and make its tools
# the ones found on PATH.
wget https://apt.llvm.org/llvm.sh
chmod +x llvm.sh
sudo ./llvm.sh 22 all
sudo ln -sf /usr/bin/clang-22 /usr/local/bin/clang
sudo ln -sf /usr/bin/llc-22 /usr/local/bin/llc
clang --version
llc --version
# bpftool isn't an installable package by itself on Ubuntu: it's a
# virtual package provided by linux-tools-common + a kernel-flavor
# linux-tools-<flavor> package. The runner's exact kernel version
# has no matching linux-tools-<version> package, so the
# update-alternatives symlink for `bpftool` doesn't get set up;
# find whatever binary the generic-flavor package installed and
# put it on PATH ourselves.
bpftool_bin=$(sudo find /usr/lib/linux-tools* -name bpftool -type f 2>/dev/null | head -1)
if [ -z "$bpftool_bin" ]; then
echo "::error::Could not find a bpftool binary after installing linux-tools-generic"
exit 1
fi
sudo ln -sf "$bpftool_bin" /usr/local/bin/bpftool
bpftool version
- name: Install uv
run: pip install uv
- name: Install project
run: uv pip install --system -e ".[test]"
- name: Run test suite
run: make test
- name: Check whether sudo is usable
id: sudo-check
run: |
if sudo -n true 2>/dev/null; then
echo "Passwordless sudo is available."
echo "available=true" >> "$GITHUB_OUTPUT"
else
echo "No passwordless sudo on this runner; kernel verifier tests will be skipped."
echo "available=false" >> "$GITHUB_OUTPUT"
fi
- name: Run kernel verifier tests
if: steps.sudo-check.outputs.available == 'true'
run: |
sudo -v
make test-verifier

View File

@ -6,18 +6,29 @@ clean:
rm -rf examples/*.ll examples/*.o rm -rf examples/*.ll examples/*.o
rm -rf htmlcov .coverage rm -rf htmlcov .coverage
test: # Regenerate the master vmlinux.py from the running kernel's BTF, then
# symlink it into every directory under tests/ so both pytest (which
# resolves "import vmlinux" via pythonpath=["."]) and any test file run
# standalone from its own directory see the same, always-fresh fixture.
vmlinux:
python3 tools/vmlinux-gen.py -o vmlinux.py
@find tests -type d -not -path '*/__pycache__*' | while read -r d; do \
target=$$(python3 -c "import os,sys; print(os.path.relpath('vmlinux.py', sys.argv[1]))" "$$d"); \
ln -sf "$$target" "$$d/vmlinux.py"; \
done
test: vmlinux
pytest tests/ -W ignore::DeprecationWarning -v --tb=short -m "not verifier" pytest tests/ -W ignore::DeprecationWarning -v --tb=short -m "not verifier"
test-cov: test-cov: vmlinux
pytest tests/ -W ignore::DeprecationWarning -v --tb=short -m "not verifier" \ pytest tests/ -W ignore::DeprecationWarning -v --tb=short -m "not verifier" \
--cov=pythonbpf --cov-report=term-missing --cov-report=html --cov=pythonbpf --cov-report=term-missing --cov-report=html
test-verifier: test-verifier: vmlinux
@echo "NOTE: verifier tests shell out to 'sudo bpftool'; run 'sudo -v' first so" @echo "NOTE: verifier tests shell out to 'sudo bpftool'; run 'sudo -v' first so"
@echo " the timestamp does not lapse mid-run. bpftool must be installed." @echo " the timestamp does not lapse mid-run. bpftool must be installed."
pytest tests/test_verifier.py -W ignore::DeprecationWarning -v --tb=short -m verifier pytest tests/test_verifier.py -W ignore::DeprecationWarning -v --tb=short -m verifier
all: clean install all: clean install
.PHONY: all clean install test test-cov test-verifier .PHONY: all clean install test test-cov test-verifier vmlinux

View File

@ -44,6 +44,14 @@ docs = [
test = [ test = [
"pytest>=8.0", "pytest>=8.0",
"pytest-cov>=5.0", "pytest-cov>=5.0",
"ctypeslib2",
# Pinned rather than left to ctypeslib2's own (unpinned) dependency: pip
# installs the latest release by default, and its libclang API surface
# can be newer than the system libclang (e.g. Ubuntu 24.04 ships
# libclang-16), which fails with a LibclangError about an undefined
# symbol. Older bindings against a newer libclang stay compatible, so
# pin to an old-enough release instead of pinning apt's libclang.
"clang==16.0.6",
] ]
[tool.setuptools.packages.find] [tool.setuptools.packages.find]

View File

@ -403,7 +403,7 @@ def process_bpf_chunk(func_node, compilation_context, return_type):
if func_node.args.args: if func_node.args.args:
# Only look at the first argument for now # Only look at the first argument for now
param = func.args[0] param = func.args[0]
param.add_attribute("nocapture") param.add_attribute("captures(none)")
probe_string = get_probe_string(func_node) probe_string = get_probe_string(func_node)
if probe_string is not None: if probe_string is not None:

View File

@ -35,6 +35,10 @@ def collect_all_test_files() -> list[BpfTestCase]:
cases = [] cases = []
for subdir in ("passing_tests", "failing_tests"): for subdir in ("passing_tests", "failing_tests"):
for py_file in sorted((TESTS_DIR / subdir).rglob("*.py")): for py_file in sorted((TESTS_DIR / subdir).rglob("*.py")):
if py_file.name == "vmlinux.py":
# Not a test case: the per-directory symlink to the master
# vmlinux fixture module, kept alongside tests that import it.
continue
rel = str(py_file.relative_to(TESTS_DIR)) rel = str(py_file.relative_to(TESTS_DIR))
needs_vmlinux = _is_vmlinux_test(rel) needs_vmlinux = _is_vmlinux_test(rel)

View File

@ -247,25 +247,166 @@ class BTFConverter:
# Replace ('_20', ctypes.c_char, 8) with ('_20', ctypes.c_uint8, 8) # Replace ('_20', ctypes.c_char, 8) with ('_20', ctypes.c_uint8, 8)
data = re.sub(r"(ctypes\.c_char)(\s*,\s*\d+\))", r"ctypes.c_uint8\2", data) data = re.sub(r"(ctypes\.c_char)(\s*,\s*\d+\))", r"ctypes.c_uint8\2", data)
# below to replace those c_bool with bitfield greater than 8 # Some bitfields come out of clang2py with a declared width that
def repl(m): # exceeds their own base type's bit width (e.g. a 15-bit field typed
name, bits = m.groups() # as ctypes.c_ubyte, which only has 8 bits) - ctypes rejects these
return ( # outright with "ValueError: number of bits invalid for bit field".
f"('{name}', ctypes.c_uint32, {bits})" if int(bits) > 8 else m.group(0) # Widen the base type to the smallest standard integer type that can
) # actually hold the declared width.
bitfield_type_widths = {
"c_bool": 8,
"c_byte": 8,
"c_ubyte": 8,
"c_int8": 8,
"c_uint8": 8,
"c_short": 16,
"c_ushort": 16,
"c_int16": 16,
"c_uint16": 16,
"c_int": 32,
"c_uint": 32,
"c_int32": 32,
"c_uint32": 32,
"c_long": 64,
"c_ulong": 64,
"c_longlong": 64,
"c_ulonglong": 64,
"c_int64": 64,
"c_uint64": 64,
}
promoted_type_for_width = {
8: "c_uint8",
16: "c_uint16",
32: "c_uint32",
64: "c_uint64",
}
data = re.sub(r"\('([^']+)',\s*ctypes\.c_bool,\s*(\d+)\)", repl, data) def widen_oversized_bitfields(m):
name, base_type, bits = m.group(1), m.group(2), int(m.group(3))
type_width = bitfield_type_widths.get(base_type)
if type_width is None or bits <= type_width:
return m.group(0)
for width in (8, 16, 32, 64):
if bits <= width:
return (
f"('{name}', ctypes.{promoted_type_for_width[width]}, {bits})"
)
return m.group(0)
data = re.sub(
r"\('([^']+)',\s*ctypes\.([a-zA-Z0-9_]+),\s*(\d+)\)",
widen_oversized_bitfields,
data,
)
# Remove ctypes. prefix from invalid entries # Remove ctypes. prefix from invalid entries
invalid_ctypes = ["bpf_iter_state", "_cache_type", "fs_context_purpose"] invalid_ctypes = ["bpf_iter_state", "_cache_type", "fs_context_purpose"]
for name in invalid_ctypes: for name in invalid_ctypes:
data = re.sub(rf"\bctypes\.{name}\b", name, data) data = re.sub(rf"\bctypes\.{name}\b", name, data)
data = self.disambiguate_anonymous_field_names(data)
with open(self.output_file, "w") as f: with open(self.output_file, "w") as f:
f.write(data) f.write(data)
self.log(f"Saved final output to {self.output_file}") self.log(f"Saved final output to {self.output_file}")
def disambiguate_anonymous_field_names(self, data):
"""Make clang2py's generic '_N' field names globally unique per struct/union.
clang2py names both (a) unnamed anonymous struct/union members that go
into `_anonymous_`, and (b) other unnamed/reserved members, using the
same per-struct sequential scheme ('_0', '_1', ...). ctypes flattens
anonymous members by promoting their field names onto the parent class,
so if a struct has an anonymous member (say '_0') whose type itself has
a field also named '_1', and that same struct has ANOTHER anonymous
member named '_1', the promoted name collides with the parent's own
field key. ctypes then fails with a cryptic
"type object 'c_ulong' has no attribute '_fields_'" (or similar) when
`_fields_` is assigned. Prefixing every generic '_N' key with its
owning struct/union name keeps these names unique across the whole
file, so promoted names can never collide with a sibling's own key.
"""
self.log("Disambiguating generic anonymous-field names...")
def sanitize(name):
return re.sub(r"[^0-9A-Za-z_]", "_", name)
lines = data.split("\n")
class_re = re.compile(r"^class\s+(\w+)\(")
stmt_fields_re = re.compile(r"^(\w+)\._fields_\s*=\s*\[\s*$")
inline_fields_re = re.compile(r"^\s+_fields_\s*=\s*\[\s*$")
anon_stmt_re = re.compile(r"^(\w+)\._anonymous_\s*=\s*\((.*)\)\s*$")
anon_inline_re = re.compile(r"^(\s+)_anonymous_\s*=\s*\((.*)\)\s*$")
key_re = re.compile(r"(\('_)([0-9]+)(',)")
last_class = None
out = []
i = 0
n = len(lines)
renamed_count = 0
while i < n:
line = lines[i]
m_class = class_re.match(line)
if m_class:
last_class = m_class.group(1)
out.append(line)
i += 1
continue
m_anon = anon_stmt_re.match(line)
if m_anon:
cls, body = m_anon.group(1), m_anon.group(2)
prefix = sanitize(cls)
new_body, cnt = re.subn(
r"'_([0-9]+)'", lambda mm: f"'_{prefix}_{mm.group(1)}'", body
)
renamed_count += cnt
out.append(f"{cls}._anonymous_ = ({new_body})")
i += 1
continue
m_anon_inline = anon_inline_re.match(line)
if m_anon_inline and last_class:
indent, body = m_anon_inline.group(1), m_anon_inline.group(2)
prefix = sanitize(last_class)
new_body, cnt = re.subn(
r"'_([0-9]+)'", lambda mm: f"'_{prefix}_{mm.group(1)}'", body
)
renamed_count += cnt
out.append(f"{indent}_anonymous_ = ({new_body})")
i += 1
continue
m_stmt = stmt_fields_re.match(line)
m_inline = inline_fields_re.match(line) if not m_stmt else None
if m_stmt or m_inline:
cls = m_stmt.group(1) if m_stmt else last_class
prefix = sanitize(cls) if cls else None
out.append(line)
i += 1
while i < n and lines[i].strip() != "]":
fl = lines[i]
if prefix:
fl, cnt = key_re.subn(
lambda mm: f"{mm.group(1)}{prefix}_{mm.group(2)}{mm.group(3)}",
fl,
)
renamed_count += cnt
out.append(fl)
i += 1
if i < n:
out.append(lines[i]) # closing ']'
i += 1
continue
out.append(line)
i += 1
self.log(f"Renamed {renamed_count} generic field keys")
return "\n".join(out)
def cleanup(self): def cleanup(self):
"""Remove temporary files if not keeping them.""" """Remove temporary files if not keeping them."""
if not self.keep_intermediate and self.temp_dir != ".": if not self.keep_intermediate and self.temp_dir != ".":