mirror of
https://github.com/varun-r-mallya/Python-BPF.git
synced 2026-12-06 09:58:34 +00:00
Compare commits
14 Commits
tests/loop
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| b076ef4f2b | |||
| ad7a8567b1 | |||
| c308704dc5 | |||
| f2e6fba645 | |||
| 37fe5d7a9a | |||
| d093516c1d | |||
| 47586a49ad | |||
| f5eb809f4b | |||
| 28536c2c07 | |||
| 4c57a4e834 | |||
| dde720f46e | |||
| 4d2bf6842c | |||
| b843b8f343 | |||
| de259c8e86 |
@ -1,14 +1,15 @@
|
|||||||
|
<p align="center">
|
||||||
<picture>
|
<picture>
|
||||||
<source
|
<source
|
||||||
media="(prefers-color-scheme: light)"
|
media="(prefers-color-scheme: light)"
|
||||||
srcset="https://github.com/user-attachments/assets/f3738131-d7cb-4b5c-8699-c7010295a159"
|
srcset="https://github.com/user-attachments/assets/f3738131-d7cb-4b5c-8699-c7010295a159"
|
||||||
width="450"
|
width="450">
|
||||||
alt="Light‐mode image">
|
|
||||||
<img
|
<img
|
||||||
src="https://github.com/user-attachments/assets/b175bf39-23cb-475d-a6e1-7b5c99a1ed72"
|
src="https://github.com/user-attachments/assets/b175bf39-23cb-475d-a6e1-7b5c99a1ed72"
|
||||||
width="450"
|
width="450"
|
||||||
alt="Dark‐mode image">
|
alt="PythonBPF logo">
|
||||||
</picture>
|
</picture>
|
||||||
|
</p>
|
||||||
<!-- Badges -->
|
<!-- Badges -->
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<!-- PyPI -->
|
<!-- PyPI -->
|
||||||
@ -28,7 +29,7 @@
|
|||||||
|
|
||||||
Python-BPF is an LLVM IR generator for eBPF programs written in Python. It uses [llvmlite](https://github.com/numba/llvmlite) to generate LLVM IR and then compiles to LLVM object files. These object files can be loaded into the kernel for execution. Python-BPF performs compilation without relying on BCC.
|
Python-BPF is an LLVM IR generator for eBPF programs written in Python. It uses [llvmlite](https://github.com/numba/llvmlite) to generate LLVM IR and then compiles to LLVM object files. These object files can be loaded into the kernel for execution. Python-BPF performs compilation without relying on BCC.
|
||||||
|
|
||||||
> **Note**: This project is under active development and not ready for production use.
|
> **Note**: This project is under active development.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@ -96,9 +96,10 @@ def LICENSE() -> str:
|
|||||||
return "GPL"
|
return "GPL"
|
||||||
```
|
```
|
||||||
|
|
||||||
* The Linux kernel requires BPF programs to declare a license
|
* The Linux kernel reads a license from every BPF program
|
||||||
* Most kernel features require GPL-compatible licenses
|
* Most kernel features require GPL-compatible licenses
|
||||||
* This is defined as a BPF global variable
|
* This is defined as a BPF global variable
|
||||||
|
* If you leave it out, PythonBPF uses `"GPL"` and logs a warning saying so
|
||||||
|
|
||||||
### Compilation and Execution
|
### Compilation and Execution
|
||||||
|
|
||||||
@ -197,7 +198,7 @@ def xdp_pass(ctx: c_void_p) -> c_int64:
|
|||||||
|
|
||||||
## Best Practices
|
## Best Practices
|
||||||
|
|
||||||
1. **Always include a LICENSE** - Required by the kernel
|
1. **Declare a LICENSE** - Without one, PythonBPF defaults to `"GPL"` and warns
|
||||||
2. **Use type hints** - Required by PythonBPF to generate correct code
|
2. **Use type hints** - Required by PythonBPF to generate correct code
|
||||||
3. **Return the correct type** - Match the expected return type for your program type
|
3. **Return the correct type** - Match the expected return type for your program type
|
||||||
4. **Test incrementally** - Start simple and add complexity gradually
|
4. **Test incrementally** - Start simple and add complexity gradually
|
||||||
|
|||||||
@ -281,9 +281,10 @@ BPF global variables are values that:
|
|||||||
|
|
||||||
### Common Global Variables
|
### Common Global Variables
|
||||||
|
|
||||||
#### LICENSE (Required)
|
#### LICENSE
|
||||||
|
|
||||||
Every BPF program must declare a license:
|
Every BPF program carries a license, which the kernel reads when the program is
|
||||||
|
loaded. Declare it as a string global:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
@bpf
|
@bpf
|
||||||
@ -292,14 +293,24 @@ def LICENSE() -> str:
|
|||||||
return "GPL"
|
return "GPL"
|
||||||
```
|
```
|
||||||
|
|
||||||
Valid licenses include:
|
If a program defines no `LICENSE`, PythonBPF uses `"GPL"`, the kernel's own
|
||||||
|
license, and logs a warning:
|
||||||
|
|
||||||
|
```text
|
||||||
|
No LICENSE defined; defaulting to "GPL". Define @bpf @bpfglobal def LICENSE() -> str to choose another license.
|
||||||
|
```
|
||||||
|
|
||||||
|
Define `LICENSE` yourself to choose a different license or to silence the
|
||||||
|
warning. The kernel treats these as GPL-compatible:
|
||||||
* `"GPL"` - GNU General Public License
|
* `"GPL"` - GNU General Public License
|
||||||
* `"GPL v2"` - GPL version 2
|
* `"GPL v2"` - GPL version 2
|
||||||
|
* `"GPL and additional rights"`
|
||||||
* `"Dual BSD/GPL"` - Dual licensed
|
* `"Dual BSD/GPL"` - Dual licensed
|
||||||
* `"Dual MIT/GPL"` - Dual licensed
|
* `"Dual MIT/GPL"` - Dual licensed
|
||||||
|
* `"Dual MPL/GPL"` - Dual licensed
|
||||||
|
|
||||||
```{warning}
|
```{warning}
|
||||||
Many BPF features require a GPL-compatible license. Using a non-GPL license may prevent your program from loading or accessing certain kernel features.
|
Many BPF features require a GPL-compatible license. A program with any other license may not call GPL-only helpers, including `bpf_trace_printk`, which `print()` uses; the verifier rejects it with "cannot call GPL-restricted function from non-GPL compatible program".
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Custom Global Variables
|
#### Custom Global Variables
|
||||||
|
|||||||
@ -69,7 +69,7 @@ def my_function(ctx: c_void_p) -> c_int64:
|
|||||||
# BPF logic here
|
# BPF logic here
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
# License (required)
|
# License (optional: without one, PythonBPF uses "GPL" and logs a warning)
|
||||||
@bpf
|
@bpf
|
||||||
@bpfglobal
|
@bpfglobal
|
||||||
def LICENSE() -> str:
|
def LICENSE() -> str:
|
||||||
|
|||||||
@ -842,5 +842,13 @@ def handle_expr(
|
|||||||
call,
|
call,
|
||||||
local_sym_tab,
|
local_sym_tab,
|
||||||
)
|
)
|
||||||
|
elif any(isinstance(node, ast.Call) for node in ast.walk(call)):
|
||||||
|
# A docstring or a bare name has no effect and can be dropped; an
|
||||||
|
# expression with a call in it (`f() if c else g()`, `a() or b()`)
|
||||||
|
# does, and dropping it would silently lose the call.
|
||||||
|
raise NotImplementedError(
|
||||||
|
f"Unsupported expression statement on line {expr.lineno}: "
|
||||||
|
f"{type(call).__name__}; write it as an if statement or assignment"
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
logger.info("Unsupported expression type")
|
logger.debug(f"Dropping expression statement without effect: {ast.dump(call)}")
|
||||||
|
|||||||
@ -113,6 +113,14 @@ def convert_to_bool(builder, val):
|
|||||||
"""Convert a value to boolean."""
|
"""Convert a value to boolean."""
|
||||||
if val.type == ir.IntType(1):
|
if val.type == ir.IntType(1):
|
||||||
return val
|
return val
|
||||||
|
if not isinstance(val.type, (ir.IntType, ir.PointerType)):
|
||||||
|
# C rejects `if (s)` on a struct, and Python would call any object
|
||||||
|
# true; either way it is never what was meant.
|
||||||
|
kind = "struct" if isinstance(val.type, ir.BaseStructType) else "value"
|
||||||
|
raise TypeError(
|
||||||
|
f"a {kind} of type {val.type} has no truth value: test one of its "
|
||||||
|
"fields instead"
|
||||||
|
)
|
||||||
if isinstance(val.type, ir.PointerType):
|
if isinstance(val.type, ir.PointerType):
|
||||||
zero = ir.Constant(val.type, None)
|
zero = ir.Constant(val.type, None)
|
||||||
else:
|
else:
|
||||||
|
|||||||
@ -67,6 +67,11 @@ def get_or_create_ptr_from_arg(
|
|||||||
else:
|
else:
|
||||||
# Stack space is already allocated
|
# Stack space is already allocated
|
||||||
ptr = get_var_ptr_from_name(arg.id, local_sym_tab)
|
ptr = get_var_ptr_from_name(arg.id, local_sym_tab)
|
||||||
|
if symbol is not None and isinstance(symbol.ir_type, ir.PointerType):
|
||||||
|
# The slot holds a pointer (a map lookup result, or a local
|
||||||
|
# rebound to point at a temporary): the helper wants that
|
||||||
|
# pointer, not the address of the slot it is kept in.
|
||||||
|
ptr = builder.load(ptr)
|
||||||
elif isinstance(arg, ast.Constant) and isinstance(arg.value, int):
|
elif isinstance(arg, ast.Constant) and isinstance(arg.value, int):
|
||||||
int_width = 64 # Default to i64
|
int_width = 64 # Default to i64
|
||||||
if expected_type and isinstance(expected_type, ir.IntType):
|
if expected_type and isinstance(expected_type, ir.IntType):
|
||||||
|
|||||||
@ -5,6 +5,11 @@ import logging
|
|||||||
|
|
||||||
logger: Logger = logging.getLogger(__name__)
|
logger: Logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# The license a program gets when it declares none. The kernel is GPL, and a
|
||||||
|
# program whose license is not GPL-compatible may not call GPL-only helpers
|
||||||
|
# (bpf_trace_printk, which `print` lowers to, is one).
|
||||||
|
DEFAULT_LICENSE = "GPL"
|
||||||
|
|
||||||
|
|
||||||
def emit_license(module: ir.Module, license_str: str):
|
def emit_license(module: ir.Module, license_str: str):
|
||||||
license_bytes = license_str.encode("utf8") + b"\x00"
|
license_bytes = license_str.encode("utf8") + b"\x00"
|
||||||
@ -24,7 +29,10 @@ def emit_license(module: ir.Module, license_str: str):
|
|||||||
|
|
||||||
|
|
||||||
def license_processing(tree, compilation_context):
|
def license_processing(tree, compilation_context):
|
||||||
"""Process the LICENSE function decorated with @bpf and @bpfglobal and return the section name"""
|
"""Process the LICENSE function decorated with @bpf and @bpfglobal and return the section name.
|
||||||
|
|
||||||
|
A program without one gets DEFAULT_LICENSE, with a warning.
|
||||||
|
"""
|
||||||
count = 0
|
count = 0
|
||||||
for node in tree.body:
|
for node in tree.body:
|
||||||
if isinstance(node, ast.FunctionDef) and node.name == "LICENSE":
|
if isinstance(node, ast.FunctionDef) and node.name == "LICENSE":
|
||||||
@ -52,4 +60,10 @@ def license_processing(tree, compilation_context):
|
|||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
raise SyntaxError("ERROR: Multiple LICENSE globals defined")
|
raise SyntaxError("ERROR: Multiple LICENSE globals defined")
|
||||||
return None
|
|
||||||
|
logger.warning(
|
||||||
|
f'No LICENSE defined; defaulting to "{DEFAULT_LICENSE}". Define '
|
||||||
|
"@bpf @bpfglobal def LICENSE() -> str to choose another license."
|
||||||
|
)
|
||||||
|
emit_license(compilation_context.module, DEFAULT_LICENSE)
|
||||||
|
return "LICENSE"
|
||||||
|
|||||||
60
tests/c-form/map_update_from_lookup.bpf.c
Normal file
60
tests/c-form/map_update_from_lookup.bpf.c
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
/* Reference for passing a map lookup result to a helper. `prev` is a local
|
||||||
|
* holding the pointer bpf_map_lookup_elem returned; bpf_map_update_elem gets
|
||||||
|
* that pointer (the map value), loaded from prev's slot. It never gets &prev,
|
||||||
|
* the slot's own address, which would make the map store a stack address.
|
||||||
|
* The clang -O0 IR for this file is the specification for the pointer depth
|
||||||
|
* that tests/test_signedness_ir.py checks:
|
||||||
|
* copy() mirrors passing_tests/helpers/map_update_from_lookup.py
|
||||||
|
* rebind() mirrors passing_tests/vmlinux/named_arg.py, where `prev = prev + 1`
|
||||||
|
* rebinds prev to a stack temporary holding the sum; the helper
|
||||||
|
* still gets the pointer loaded from prev's slot. */
|
||||||
|
#define SEC(name) __attribute__((section(name), used))
|
||||||
|
#define __uint(name, val) int (*name)[val]
|
||||||
|
#define __type(name, val) typeof(val) *name
|
||||||
|
typedef long long __s64;
|
||||||
|
|
||||||
|
#define BPF_MAP_TYPE_HASH 1
|
||||||
|
#define BPF_ANY 0
|
||||||
|
#define XDP_PASS 2
|
||||||
|
|
||||||
|
static void *(*bpf_map_lookup_elem)(void *map, const void *key) = (void *)1;
|
||||||
|
static long (*bpf_map_update_elem)(void *map, const void *key,
|
||||||
|
const void *value, __s64 flags) = (void *)2;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
__uint(type, BPF_MAP_TYPE_HASH);
|
||||||
|
__uint(max_entries, 2);
|
||||||
|
__type(key, __s64);
|
||||||
|
__type(value, __s64);
|
||||||
|
} count SEC(".maps");
|
||||||
|
|
||||||
|
SEC("tracepoint/syscalls/sys_enter_getpid")
|
||||||
|
__s64 copy(void *ctx)
|
||||||
|
{
|
||||||
|
__s64 key = 0;
|
||||||
|
__s64 *prev = bpf_map_lookup_elem(&count, &key);
|
||||||
|
if (prev) {
|
||||||
|
key = 1;
|
||||||
|
bpf_map_update_elem(&count, &key, prev, BPF_ANY);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
SEC("xdp")
|
||||||
|
__s64 rebind(void *ctx)
|
||||||
|
{
|
||||||
|
__s64 key = 0;
|
||||||
|
__s64 tmp;
|
||||||
|
__s64 *prev = bpf_map_lookup_elem(&count, &key);
|
||||||
|
if (prev) {
|
||||||
|
tmp = *prev + 1;
|
||||||
|
prev = &tmp;
|
||||||
|
bpf_map_update_elem(&count, &key, prev, BPF_ANY);
|
||||||
|
return XDP_PASS;
|
||||||
|
}
|
||||||
|
tmp = 1;
|
||||||
|
bpf_map_update_elem(&count, &key, &tmp, BPF_ANY);
|
||||||
|
return XDP_PASS;
|
||||||
|
}
|
||||||
|
|
||||||
|
char LICENSE[] SEC("license") = "GPL";
|
||||||
@ -1,10 +1,10 @@
|
|||||||
from pythonbpf import bpf, struct, section, bpfglobal, compile
|
from pythonbpf import bpf, struct, section, bpfglobal, compile
|
||||||
from ctypes import c_void_p, c_int64, c_uint64
|
from ctypes import c_void_p, c_int64, c_uint64
|
||||||
|
|
||||||
# NOTE: Decided against fixing this
|
# Negative test: `dat` is a struct value, and a struct has no truth value
|
||||||
# as one workaround is to just check any field of the struct
|
# (C rejects `if (s)`; Python would call any object true). It is a compile
|
||||||
# in the if statement. Ugly but works.
|
# error that says to test one of the struct's fields instead. A *pointer* to
|
||||||
# Might fix in future.
|
# a struct, such as a map lookup result, is a valid condition (non-null).
|
||||||
|
|
||||||
|
|
||||||
@bpf
|
@bpf
|
||||||
@ -1,14 +0,0 @@
|
|||||||
from pythonbpf import compile, bpf, section
|
|
||||||
from ctypes import c_void_p, c_int64
|
|
||||||
|
|
||||||
|
|
||||||
# FAILS WHEN THERE IS NO LICENSE. which is wrong.
|
|
||||||
@bpf
|
|
||||||
@section("sometag1")
|
|
||||||
def sometag(ctx: c_void_p) -> c_int64:
|
|
||||||
a = 1 + 2
|
|
||||||
print(f"{a}")
|
|
||||||
return c_int64(0)
|
|
||||||
|
|
||||||
|
|
||||||
compile()
|
|
||||||
23
tests/failing_tests/license_non_gpl.py
Normal file
23
tests/failing_tests/license_non_gpl.py
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
# A license that is not GPL-compatible may not call GPL-only helpers: `print`
|
||||||
|
# lowers to bpf_trace_printk, so the verifier rejects this program. The
|
||||||
|
# counterpart of passing_tests/license_default.py, which proves the default
|
||||||
|
# license is GPL.
|
||||||
|
|
||||||
|
from pythonbpf import compile, bpf, bpfglobal, section
|
||||||
|
from ctypes import c_void_p, c_int64
|
||||||
|
|
||||||
|
|
||||||
|
@bpf
|
||||||
|
@section("tracepoint/syscalls/sys_enter_getpid")
|
||||||
|
def sometag(ctx: c_void_p) -> c_int64:
|
||||||
|
print("hello")
|
||||||
|
return c_int64(0)
|
||||||
|
|
||||||
|
|
||||||
|
@bpf
|
||||||
|
@bpfglobal
|
||||||
|
def LICENSE() -> str:
|
||||||
|
return "Proprietary"
|
||||||
|
|
||||||
|
|
||||||
|
compile()
|
||||||
@ -1,45 +0,0 @@
|
|||||||
from pythonbpf import bpf, map, section, bpfglobal, compile
|
|
||||||
from vmlinux import XDP_PASS
|
|
||||||
from pythonbpf.maps import HashMap
|
|
||||||
|
|
||||||
from ctypes import c_void_p, c_int64
|
|
||||||
|
|
||||||
# NOTE: I have decided to not fix this example for now.
|
|
||||||
# The issue is in line 31, where we are passing an expression.
|
|
||||||
# The update helper expects a pointer type. But the problem is
|
|
||||||
# that we must allocate the space for said pointer in the first
|
|
||||||
# basic block. As that usage is in a different basic block, we
|
|
||||||
# are unable to cast the expression to a pointer type. (as we never
|
|
||||||
# allocated space for it).
|
|
||||||
# Shall we change our space allocation logic? That allows users to
|
|
||||||
# spam the same helper with the same args, and still run out of
|
|
||||||
# stack space. So we consider this usage invalid for now.
|
|
||||||
# Might fix it later.
|
|
||||||
|
|
||||||
|
|
||||||
@bpf
|
|
||||||
@map
|
|
||||||
def count() -> HashMap:
|
|
||||||
return HashMap(key=c_int64, value=c_int64, max_entries=1)
|
|
||||||
|
|
||||||
|
|
||||||
@bpf
|
|
||||||
@section("xdp")
|
|
||||||
def hello_world(ctx: c_void_p) -> c_int64:
|
|
||||||
prev = count.lookup(0)
|
|
||||||
if prev:
|
|
||||||
count.update(0, prev + 1)
|
|
||||||
return XDP_PASS
|
|
||||||
else:
|
|
||||||
count.update(0, 1)
|
|
||||||
|
|
||||||
return XDP_PASS
|
|
||||||
|
|
||||||
|
|
||||||
@bpf
|
|
||||||
@bpfglobal
|
|
||||||
def LICENSE() -> str:
|
|
||||||
return "GPL"
|
|
||||||
|
|
||||||
|
|
||||||
compile()
|
|
||||||
@ -1,54 +0,0 @@
|
|||||||
from pythonbpf import bpf, map, section, bpfglobal, compile_to_ir
|
|
||||||
from pythonbpf.maps import HashMap
|
|
||||||
from vmlinux import XDP_PASS
|
|
||||||
from vmlinux import TASK_COMM_LEN # noqa: F401
|
|
||||||
|
|
||||||
from vmlinux import struct_qspinlock # noqa: F401
|
|
||||||
|
|
||||||
# from vmlinux import struct_trace_event_raw_sys_enter # noqa: F401
|
|
||||||
# from vmlinux import struct_posix_cputimers # noqa: F401
|
|
||||||
from vmlinux import struct_xdp_md
|
|
||||||
|
|
||||||
# from vmlinux import struct_trace_event_raw_sys_enter # noqa: F401
|
|
||||||
# from vmlinux import struct_ring_buffer_per_cpu # noqa: F401
|
|
||||||
# from vmlinux import struct_request # noqa: F401
|
|
||||||
from ctypes import c_int64
|
|
||||||
|
|
||||||
# Instructions to how to run this program
|
|
||||||
# 1. Install PythonBPF: pip install pythonbpf
|
|
||||||
# 2. Run the program: python examples/xdp_pass.py
|
|
||||||
# 3. Run the program with sudo: sudo tools/check.sh run examples/xdp_pass.o
|
|
||||||
# 4. Attach object file to any network device with something like ./check.sh xdp examples/xdp_pass.o tailscale0
|
|
||||||
# 5. send traffic through the device and observe effects
|
|
||||||
|
|
||||||
|
|
||||||
@bpf
|
|
||||||
@map
|
|
||||||
def count() -> HashMap:
|
|
||||||
return HashMap(key=c_int64, value=c_int64, max_entries=1)
|
|
||||||
|
|
||||||
|
|
||||||
@bpf
|
|
||||||
@section("xdp")
|
|
||||||
def hello_world(ctx: struct_xdp_md) -> c_int64:
|
|
||||||
key = 0
|
|
||||||
one = 1
|
|
||||||
prev = count().lookup(key)
|
|
||||||
if prev:
|
|
||||||
prevval = prev + 1
|
|
||||||
print(f"count: {prevval}")
|
|
||||||
count().update(key, prevval)
|
|
||||||
return XDP_PASS
|
|
||||||
else:
|
|
||||||
count().update(key, one)
|
|
||||||
|
|
||||||
return XDP_PASS
|
|
||||||
|
|
||||||
|
|
||||||
@bpf
|
|
||||||
@bpfglobal
|
|
||||||
def LICENSE() -> str:
|
|
||||||
return "GPL"
|
|
||||||
|
|
||||||
|
|
||||||
compile_to_ir("xdp_pass.py", "xdp_pass.ll")
|
|
||||||
@ -3,13 +3,9 @@ from ctypes import c_void_p, c_int64, c_uint64
|
|||||||
from pythonbpf.maps import HashMap
|
from pythonbpf.maps import HashMap
|
||||||
|
|
||||||
|
|
||||||
# NOTE: This example tries to reinterpret the variable `x` to a different type.
|
# `x` is first bound to a map lookup (a pointer) and then rebound to an integer,
|
||||||
# We do not allow this for now, as stack allocations are typed and have to be
|
# as Python allows; the comparison sees the integer. This was once refused
|
||||||
# done in the first basic block. Allowing re-interpretation would require
|
# because stack slots are typed, and now works.
|
||||||
# re-allocation of stack space (possibly in a new basic block), which is not
|
|
||||||
# supported in eBPF yet.
|
|
||||||
# We can allow bitcasts in cases where the width of the types is the same in
|
|
||||||
# the future. But for now, we do not allow any re-interpretation of variables.
|
|
||||||
|
|
||||||
|
|
||||||
@bpf
|
@bpf
|
||||||
@ -2,10 +2,8 @@ from pythonbpf import bpf, map, section, bpfglobal, compile
|
|||||||
from ctypes import c_void_p, c_int64, c_uint64
|
from ctypes import c_void_p, c_int64, c_uint64
|
||||||
from pythonbpf.maps import HashMap
|
from pythonbpf.maps import HashMap
|
||||||
|
|
||||||
# NOTE: Decided against fixing this
|
# A map lookup used directly in a comparison: the value is null-checked and
|
||||||
# as a workaround is assigning the result of lookup to a variable
|
# dereferenced, and a missing key takes the else branch.
|
||||||
# and then using that variable in the if statement.
|
|
||||||
# Might fix in future.
|
|
||||||
|
|
||||||
|
|
||||||
@bpf
|
@bpf
|
||||||
31
tests/passing_tests/helpers/map_update_from_lookup.py
Normal file
31
tests/passing_tests/helpers/map_update_from_lookup.py
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
# A map lookup result passed straight to map.update(): the helper gets the
|
||||||
|
# pointer the local holds (the map value), as bpf_map_update_elem(&m, &k, prev, 0)
|
||||||
|
# would in C, not the address of the local's slot.
|
||||||
|
|
||||||
|
from pythonbpf import bpf, map, section, bpfglobal, compile
|
||||||
|
from pythonbpf.maps import HashMap
|
||||||
|
from ctypes import c_void_p, c_int64
|
||||||
|
|
||||||
|
|
||||||
|
@bpf
|
||||||
|
@map
|
||||||
|
def count() -> HashMap:
|
||||||
|
return HashMap(key=c_int64, value=c_int64, max_entries=2)
|
||||||
|
|
||||||
|
|
||||||
|
@bpf
|
||||||
|
@section("tracepoint/syscalls/sys_enter_getpid")
|
||||||
|
def copy(ctx: c_void_p) -> c_int64:
|
||||||
|
prev = count.lookup(0)
|
||||||
|
if prev:
|
||||||
|
count.update(1, prev)
|
||||||
|
return c_int64(0)
|
||||||
|
|
||||||
|
|
||||||
|
@bpf
|
||||||
|
@bpfglobal
|
||||||
|
def LICENSE() -> str:
|
||||||
|
return "GPL"
|
||||||
|
|
||||||
|
|
||||||
|
compile()
|
||||||
17
tests/passing_tests/license_default.py
Normal file
17
tests/passing_tests/license_default.py
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
# No LICENSE: the program gets "GPL", with a warning. `print` lowers to
|
||||||
|
# bpf_trace_printk, which is GPL-only, so the verifier only accepts this
|
||||||
|
# program if the default license reaches the kernel.
|
||||||
|
|
||||||
|
from pythonbpf import compile, bpf, section
|
||||||
|
from ctypes import c_void_p, c_int64
|
||||||
|
|
||||||
|
|
||||||
|
@bpf
|
||||||
|
@section("tracepoint/syscalls/sys_enter_getpid")
|
||||||
|
def sometag(ctx: c_void_p) -> c_int64:
|
||||||
|
a = 1 + 2
|
||||||
|
print(f"{a}")
|
||||||
|
return c_int64(0)
|
||||||
|
|
||||||
|
|
||||||
|
compile()
|
||||||
37
tests/passing_tests/vmlinux/direct_assign.py
Normal file
37
tests/passing_tests/vmlinux/direct_assign.py
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
from pythonbpf import bpf, map, section, bpfglobal, compile
|
||||||
|
from vmlinux import XDP_PASS
|
||||||
|
from pythonbpf.maps import HashMap
|
||||||
|
|
||||||
|
from ctypes import c_void_p, c_int64
|
||||||
|
|
||||||
|
# An expression (`prev + 1`) passed straight to map.update(): it is evaluated
|
||||||
|
# into a scratch slot and the helper gets that slot's address. This was once
|
||||||
|
# refused for want of a slot allocated up front, and now works.
|
||||||
|
|
||||||
|
|
||||||
|
@bpf
|
||||||
|
@map
|
||||||
|
def count() -> HashMap:
|
||||||
|
return HashMap(key=c_int64, value=c_int64, max_entries=1)
|
||||||
|
|
||||||
|
|
||||||
|
@bpf
|
||||||
|
@section("xdp")
|
||||||
|
def hello_world(ctx: c_void_p) -> c_int64:
|
||||||
|
prev = count.lookup(0)
|
||||||
|
if prev:
|
||||||
|
count.update(0, prev + 1)
|
||||||
|
return XDP_PASS
|
||||||
|
else:
|
||||||
|
count.update(0, 1)
|
||||||
|
|
||||||
|
return XDP_PASS
|
||||||
|
|
||||||
|
|
||||||
|
@bpf
|
||||||
|
@bpfglobal
|
||||||
|
def LICENSE() -> str:
|
||||||
|
return "GPL"
|
||||||
|
|
||||||
|
|
||||||
|
compile()
|
||||||
@ -4,12 +4,11 @@ from pythonbpf.maps import HashMap
|
|||||||
|
|
||||||
from ctypes import c_void_p, c_int64
|
from ctypes import c_void_p, c_int64
|
||||||
|
|
||||||
# NOTE: This example exposes the problems with our typing system.
|
# `prev` starts as a map lookup result (a pointer) and is rebound to
|
||||||
# We can't do steps on line 25 and 27.
|
# `prev + 1`, which lives in a temporary that `prev` then points at. The update
|
||||||
# prev is of type i64**. For prev + 1, we deref it down to i64
|
# must store the incremented value: the helper gets the pointer the local
|
||||||
# To assign it back to prev, we need to go back to i64**.
|
# holds, not the address of the local's own slot (that used to store a kernel
|
||||||
# We cannot allocate space for the intermediate type now.
|
# stack address into the map).
|
||||||
# We probably need to track the ref/deref chain for each variable.
|
|
||||||
|
|
||||||
|
|
||||||
@bpf
|
@bpf
|
||||||
41
tests/passing_tests/vmlinux/xdp_pass.py
Normal file
41
tests/passing_tests/vmlinux/xdp_pass.py
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
# Counts packets in a one-entry map and lets every packet through. It used to
|
||||||
|
# be an xfail, but the only thing failing was the old `count().lookup(...)`
|
||||||
|
# spelling of a map call; `count.lookup(...)` is the current one.
|
||||||
|
|
||||||
|
from pythonbpf import bpf, map, section, bpfglobal, compile
|
||||||
|
from pythonbpf.maps import HashMap
|
||||||
|
from vmlinux import XDP_PASS
|
||||||
|
from vmlinux import struct_xdp_md
|
||||||
|
from ctypes import c_int64
|
||||||
|
|
||||||
|
|
||||||
|
@bpf
|
||||||
|
@map
|
||||||
|
def count() -> HashMap:
|
||||||
|
return HashMap(key=c_int64, value=c_int64, max_entries=1)
|
||||||
|
|
||||||
|
|
||||||
|
@bpf
|
||||||
|
@section("xdp")
|
||||||
|
def hello_world(ctx: struct_xdp_md) -> c_int64:
|
||||||
|
key = 0
|
||||||
|
one = 1
|
||||||
|
prev = count.lookup(key)
|
||||||
|
if prev:
|
||||||
|
prevval = prev + 1
|
||||||
|
print(f"count: {prevval}")
|
||||||
|
count.update(key, prevval)
|
||||||
|
return XDP_PASS
|
||||||
|
else:
|
||||||
|
count.update(key, one)
|
||||||
|
|
||||||
|
return XDP_PASS
|
||||||
|
|
||||||
|
|
||||||
|
@bpf
|
||||||
|
@bpfglobal
|
||||||
|
def LICENSE() -> str:
|
||||||
|
return "GPL"
|
||||||
|
|
||||||
|
|
||||||
|
compile()
|
||||||
@ -15,18 +15,19 @@
|
|||||||
|
|
||||||
[xfail]
|
[xfail]
|
||||||
|
|
||||||
"failing_tests/conditionals/struct_ptr.py" = {reason = "Struct pointer used directly as boolean condition not supported", level = "ir"}
|
"failing_tests/conditionals/struct_value.py" = {reason = "A struct value has no truth value (C rejects `if (s)`): a compile error naming the struct", level = "ir"}
|
||||||
|
|
||||||
|
"failing_tests/conditionals/oneline.py" = {reason = "A conditional expression used as a statement (`f() if c else g()`) is not lowered: a compile error rather than silently dropping both calls; write it as an if statement", level = "ir"}
|
||||||
|
|
||||||
"failing_tests/return_struct.py" = {reason = "Returning a struct value from an integer function is a type error (nothing to dereference to an integer)", level = "ir"}
|
"failing_tests/return_struct.py" = {reason = "Returning a struct value from an integer function is a type error (nothing to dereference to an integer)", level = "ir"}
|
||||||
|
|
||||||
"failing_tests/license.py" = {reason = "Missing LICENSE global produces IR that llc rejects — should be caught earlier with a clear error message", level = "llc"}
|
"failing_tests/license_non_gpl.py" = {reason = "Negative fixture: a non-GPL license may not call the GPL-only bpf_trace_printk that print lowers to", level = "verifier", match = "cannot call GPL-restricted function from non-GPL compatible program"}
|
||||||
|
|
||||||
"failing_tests/undeclared_values.py" = {reason = "Undeclared variable used in f-string — should raise SyntaxError (correct behaviour, test documents it)", level = "ir"}
|
"failing_tests/undeclared_values.py" = {reason = "Undeclared variable used in f-string — should raise SyntaxError (correct behaviour, test documents it)", level = "ir"}
|
||||||
|
|
||||||
"failing_tests/vmlinux/args_test.py" = {reason = "struct_trace_event_raw_sys_enter args field access not supported", level = "ir"}
|
"failing_tests/vmlinux/args_test.py" = {reason = "struct_trace_event_raw_sys_enter args field access not supported", level = "ir"}
|
||||||
|
|
||||||
|
|
||||||
"failing_tests/vmlinux/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_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"}
|
||||||
|
|
||||||
|
|||||||
42
tests/test_license_ir.py
Normal file
42
tests/test_license_ir.py
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
"""
|
||||||
|
The license section: a program without LICENSE gets "GPL", with a warning,
|
||||||
|
and an explicit LICENSE is emitted as written, with no warning.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from tests.framework.compiler import run_ir_generation
|
||||||
|
|
||||||
|
TESTS_DIR = Path(__file__).parent
|
||||||
|
|
||||||
|
|
||||||
|
def _license_global(text):
|
||||||
|
"""The LICENSE global as compile_to_ir emits it: NUL-terminated bytes."""
|
||||||
|
data = text.encode() + b"\x00"
|
||||||
|
elems = ", ".join(f"i8 {b}" for b in data)
|
||||||
|
return (
|
||||||
|
f'@"LICENSE" = dso_local global [{len(data)} x i8] [{elems}], section "license"'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _license_ir(name, tmp_path, caplog):
|
||||||
|
ll_path = tmp_path / "output.ll"
|
||||||
|
with caplog.at_level(logging.WARNING, logger="pythonbpf.license_pass"):
|
||||||
|
run_ir_generation(TESTS_DIR / name, ll_path)
|
||||||
|
warnings = [
|
||||||
|
r.getMessage() for r in caplog.records if r.name == "pythonbpf.license_pass"
|
||||||
|
]
|
||||||
|
return ll_path.read_text(), warnings
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_license_defaults_to_gpl(tmp_path, caplog):
|
||||||
|
ir, warnings = _license_ir("passing_tests/license_default.py", tmp_path, caplog)
|
||||||
|
assert _license_global("GPL") in ir
|
||||||
|
assert any('defaulting to "GPL"' in w for w in warnings), warnings
|
||||||
|
|
||||||
|
|
||||||
|
def test_explicit_license_is_kept(tmp_path, caplog):
|
||||||
|
ir, warnings = _license_ir("failing_tests/license_non_gpl.py", tmp_path, caplog)
|
||||||
|
assert _license_global("Proprietary") in ir
|
||||||
|
assert not warnings, warnings
|
||||||
@ -19,6 +19,13 @@ from tests.framework.compiler import run_ir_generation
|
|||||||
PASSING_DIR = Path(__file__).parent / "passing_tests"
|
PASSING_DIR = Path(__file__).parent / "passing_tests"
|
||||||
HAVE_VMLINUX = importlib.util.find_spec("vmlinux") is not None
|
HAVE_VMLINUX = importlib.util.find_spec("vmlinux") is not None
|
||||||
|
|
||||||
|
# The value argument of a map update is the very SSA value loaded from prev's
|
||||||
|
# slot, not merely some load of prev elsewhere in the function.
|
||||||
|
UPDATE_WITH_LOADED_PREV = (
|
||||||
|
r'(%"[^"]+") = load i64\*, i64\*\* %"prev"\n(?:.*\n)*?'
|
||||||
|
r'.*call i64 %"[^"]+"\(\{[^}]*\}\* @"count", i64\* %"[^"]+", i64\* \1, i64 0\)'
|
||||||
|
)
|
||||||
|
|
||||||
# path under passing_tests -> (patterns that must appear, patterns that must not)
|
# path under passing_tests -> (patterns that must appear, patterns that must not)
|
||||||
CASES = {
|
CASES = {
|
||||||
"signedness/widen_unsigned.py": (
|
"signedness/widen_unsigned.py": (
|
||||||
@ -112,6 +119,20 @@ CASES = {
|
|||||||
[r"deref_0_not_null", r"ret i64 %"],
|
[r"deref_0_not_null", r"ret i64 %"],
|
||||||
[r"ret i64\*"],
|
[r"ret i64\*"],
|
||||||
),
|
),
|
||||||
|
# A local holding a pointer is passed to a helper as that pointer, loaded
|
||||||
|
# from its slot; the slot's own address (an i64**) would make the map store
|
||||||
|
# a kernel address instead of the value. The reference is
|
||||||
|
# tests/c-form/map_update_from_lookup.bpf.c: at -O0 clang passes
|
||||||
|
# bpf_map_update_elem the result of `load ptr, ptr <prev's slot>` in both
|
||||||
|
# copy() and rebind().
|
||||||
|
"helpers/map_update_from_lookup.py": (
|
||||||
|
[UPDATE_WITH_LOADED_PREV],
|
||||||
|
[r'i64\*\* %"prev", i64 0\)'],
|
||||||
|
),
|
||||||
|
"vmlinux/named_arg.py": (
|
||||||
|
[UPDATE_WITH_LOADED_PREV],
|
||||||
|
[r'i64\*\* %"prev", i64 0\)'],
|
||||||
|
),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user