mirror of
https://github.com/varun-r-mallya/Python-BPF.git
synced 2026-02-11 15:40:56 +00:00
Compare commits
3 Commits
6881d2e960
...
a2b1a8baff
| Author | SHA1 | Date | |
|---|---|---|---|
| a2b1a8baff | |||
| 22289821f9 | |||
| d86dd683f4 |
1
.gitignore
vendored
1
.gitignore
vendored
@ -7,3 +7,4 @@ __pycache__/
|
|||||||
*.ll
|
*.ll
|
||||||
*.o
|
*.o
|
||||||
.ipynb_checkpoints/
|
.ipynb_checkpoints/
|
||||||
|
vmlinux.py
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
PythonBPF - A Python frontend for eBPF programs.
|
PythonBPF - A Python frontend for eBPF programs.
|
||||||
|
|
||||||
This package provides decorators and compilation tools to write BPF programs
|
This package provides decorators and compilation tools to write BPF programs
|
||||||
in Python syntax and compile them to eBPF bytecode that can run in the kernel.
|
in Python syntax and compile them to LLVM IR that can be compiled to eBPF bytecode.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from .decorators import bpf, map, section, bpfglobal, struct
|
from .decorators import bpf, map, section, bpfglobal, struct
|
||||||
|
|||||||
@ -44,12 +44,12 @@ def get_operand_value(operand, builder, local_sym_tab):
|
|||||||
def handle_binary_op_impl(rval, builder, local_sym_tab):
|
def handle_binary_op_impl(rval, builder, local_sym_tab):
|
||||||
"""
|
"""
|
||||||
Handle binary operations and emit corresponding LLVM IR instructions.
|
Handle binary operations and emit corresponding LLVM IR instructions.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
rval: The AST BinOp node representing the binary operation
|
rval: The AST BinOp node representing the binary operation
|
||||||
builder: LLVM IR builder for emitting instructions
|
builder: LLVM IR builder for emitting instructions
|
||||||
local_sym_tab: Symbol table mapping variable names to their IR representations
|
local_sym_tab: Symbol table mapping variable names to their IR representations
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The LLVM IR value representing the result of the binary operation
|
The LLVM IR value representing the result of the binary operation
|
||||||
"""
|
"""
|
||||||
@ -83,13 +83,13 @@ def handle_binary_op_impl(rval, builder, local_sym_tab):
|
|||||||
def handle_binary_op(rval, builder, var_name, local_sym_tab):
|
def handle_binary_op(rval, builder, var_name, local_sym_tab):
|
||||||
"""
|
"""
|
||||||
Handle binary operations and optionally store the result to a variable.
|
Handle binary operations and optionally store the result to a variable.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
rval: The AST BinOp node representing the binary operation
|
rval: The AST BinOp node representing the binary operation
|
||||||
builder: LLVM IR builder for emitting instructions
|
builder: LLVM IR builder for emitting instructions
|
||||||
var_name: Optional variable name to store the result
|
var_name: Optional variable name to store the result
|
||||||
local_sym_tab: Symbol table mapping variable names to their IR representations
|
local_sym_tab: Symbol table mapping variable names to their IR representations
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
A tuple of (result_value, result_type)
|
A tuple of (result_value, result_type)
|
||||||
"""
|
"""
|
||||||
|
|||||||
@ -47,7 +47,7 @@ def find_bpf_chunks(tree):
|
|||||||
def processor(source_code, filename, module):
|
def processor(source_code, filename, module):
|
||||||
"""
|
"""
|
||||||
Process Python source code and convert BPF-decorated functions to LLVM IR.
|
Process Python source code and convert BPF-decorated functions to LLVM IR.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
source_code: The Python source code to process
|
source_code: The Python source code to process
|
||||||
filename: The name of the source file
|
filename: The name of the source file
|
||||||
@ -74,12 +74,12 @@ def processor(source_code, filename, module):
|
|||||||
def compile_to_ir(filename: str, output: str, loglevel=logging.INFO):
|
def compile_to_ir(filename: str, output: str, loglevel=logging.INFO):
|
||||||
"""
|
"""
|
||||||
Compile a Python BPF program to LLVM IR.
|
Compile a Python BPF program to LLVM IR.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
filename: Path to the Python source file containing BPF programs
|
filename: Path to the Python source file containing BPF programs
|
||||||
output: Path where the LLVM IR (.ll) file will be written
|
output: Path where the LLVM IR (.ll) file will be written
|
||||||
loglevel: Logging level for compilation messages
|
loglevel: Logging level for compilation messages
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Path to the generated LLVM IR file
|
Path to the generated LLVM IR file
|
||||||
"""
|
"""
|
||||||
@ -158,13 +158,13 @@ def compile_to_ir(filename: str, output: str, loglevel=logging.INFO):
|
|||||||
def compile(loglevel=logging.INFO) -> bool:
|
def compile(loglevel=logging.INFO) -> bool:
|
||||||
"""
|
"""
|
||||||
Compile the calling Python BPF program to an object file.
|
Compile the calling Python BPF program to an object file.
|
||||||
|
|
||||||
This function should be called from a Python file containing BPF programs.
|
This function should be called from a Python file containing BPF programs.
|
||||||
It will compile the calling file to LLVM IR and then to a BPF object file.
|
It will compile the calling file to LLVM IR and then to a BPF object file.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
loglevel: Logging level for compilation messages
|
loglevel: Logging level for compilation messages
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
True if compilation succeeded, False otherwise
|
True if compilation succeeded, False otherwise
|
||||||
"""
|
"""
|
||||||
@ -203,13 +203,13 @@ def compile(loglevel=logging.INFO) -> bool:
|
|||||||
def BPF(loglevel=logging.INFO) -> BpfProgram:
|
def BPF(loglevel=logging.INFO) -> BpfProgram:
|
||||||
"""
|
"""
|
||||||
Compile the calling Python BPF program and return a BpfProgram object.
|
Compile the calling Python BPF program and return a BpfProgram object.
|
||||||
|
|
||||||
This function compiles the calling file's BPF programs to an object file
|
This function compiles the calling file's BPF programs to an object file
|
||||||
and loads it into a BpfProgram object for immediate use.
|
and loads it into a BpfProgram object for immediate use.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
loglevel: Logging level for compilation messages
|
loglevel: Logging level for compilation messages
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
A BpfProgram object that can be used to load and attach BPF programs
|
A BpfProgram object that can be used to load and attach BPF programs
|
||||||
"""
|
"""
|
||||||
|
|||||||
@ -10,15 +10,15 @@ from typing import Any, List
|
|||||||
class DebugInfoGenerator:
|
class DebugInfoGenerator:
|
||||||
"""
|
"""
|
||||||
Generator for DWARF/BTF debug information in LLVM IR modules.
|
Generator for DWARF/BTF debug information in LLVM IR modules.
|
||||||
|
|
||||||
This class provides methods to create debug metadata for BPF programs,
|
This class provides methods to create debug metadata for BPF programs,
|
||||||
including types, structs, globals, and compilation units.
|
including types, structs, globals, and compilation units.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, module):
|
def __init__(self, module):
|
||||||
"""
|
"""
|
||||||
Initialize the debug info generator.
|
Initialize the debug info generator.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
module: LLVM IR module to attach debug info to
|
module: LLVM IR module to attach debug info to
|
||||||
"""
|
"""
|
||||||
@ -28,7 +28,7 @@ class DebugInfoGenerator:
|
|||||||
def generate_file_metadata(self, filename, dirname):
|
def generate_file_metadata(self, filename, dirname):
|
||||||
"""
|
"""
|
||||||
Generate file metadata for debug info.
|
Generate file metadata for debug info.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
filename: Name of the source file
|
filename: Name of the source file
|
||||||
dirname: Directory containing the source file
|
dirname: Directory containing the source file
|
||||||
@ -46,7 +46,7 @@ class DebugInfoGenerator:
|
|||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Generate debug compile unit metadata.
|
Generate debug compile unit metadata.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
language: DWARF language code (e.g., DW_LANG_C11)
|
language: DWARF language code (e.g., DW_LANG_C11)
|
||||||
producer: Compiler/producer string
|
producer: Compiler/producer string
|
||||||
@ -114,11 +114,11 @@ class DebugInfoGenerator:
|
|||||||
def _compute_array_size(base_type: Any, count: int) -> int:
|
def _compute_array_size(base_type: Any, count: int) -> int:
|
||||||
"""
|
"""
|
||||||
Compute the size of an array in bits.
|
Compute the size of an array in bits.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
base_type: The base type of the array
|
base_type: The base type of the array
|
||||||
count: Number of elements in the array
|
count: Number of elements in the array
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Total size in bits
|
Total size in bits
|
||||||
"""
|
"""
|
||||||
|
|||||||
@ -5,6 +5,7 @@ import llvmlite.ir as ir
|
|||||||
|
|
||||||
class DwarfBehaviorEnum:
|
class DwarfBehaviorEnum:
|
||||||
"""DWARF module flag behavior constants for LLVM."""
|
"""DWARF module flag behavior constants for LLVM."""
|
||||||
|
|
||||||
ERROR_IF_MISMATCH = ir.Constant(ir.IntType(32), 1)
|
ERROR_IF_MISMATCH = ir.Constant(ir.IntType(32), 1)
|
||||||
WARNING_IF_MISMATCH = ir.Constant(ir.IntType(32), 2)
|
WARNING_IF_MISMATCH = ir.Constant(ir.IntType(32), 2)
|
||||||
OVERRIDE_USE_LARGEST = ir.Constant(ir.IntType(32), 7)
|
OVERRIDE_USE_LARGEST = ir.Constant(ir.IntType(32), 7)
|
||||||
|
|||||||
@ -33,13 +33,14 @@ def struct(cls):
|
|||||||
def section(name: str):
|
def section(name: str):
|
||||||
"""
|
"""
|
||||||
Decorator to specify the ELF section name for a BPF program.
|
Decorator to specify the ELF section name for a BPF program.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
name: The section name (e.g., 'xdp', 'tracepoint/syscalls/sys_enter_execve')
|
name: The section name (e.g., 'xdp', 'tracepoint/syscalls/sys_enter_execve')
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
A decorator function that marks the function with the section name
|
A decorator function that marks the function with the section name
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def wrapper(fn):
|
def wrapper(fn):
|
||||||
"""Decorator that sets the section name on the function."""
|
"""Decorator that sets the section name on the function."""
|
||||||
fn._section = name
|
fn._section = name
|
||||||
|
|||||||
@ -342,7 +342,7 @@ def eval_expr(
|
|||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Evaluate an expression and return its LLVM IR value and type.
|
Evaluate an expression and return its LLVM IR value and type.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
func: The LLVM IR function being built
|
func: The LLVM IR function being built
|
||||||
module: The LLVM IR module
|
module: The LLVM IR module
|
||||||
@ -351,7 +351,7 @@ def eval_expr(
|
|||||||
local_sym_tab: Local symbol table
|
local_sym_tab: Local symbol table
|
||||||
map_sym_tab: Map symbol table
|
map_sym_tab: Map symbol table
|
||||||
structs_sym_tab: Struct symbol table
|
structs_sym_tab: Struct symbol table
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
A tuple of (value, type) or None if evaluation fails
|
A tuple of (value, type) or None if evaluation fails
|
||||||
"""
|
"""
|
||||||
|
|||||||
@ -26,10 +26,10 @@ COMPARISON_OPS = {
|
|||||||
def _get_base_type_and_depth(ir_type):
|
def _get_base_type_and_depth(ir_type):
|
||||||
"""
|
"""
|
||||||
Get the base type and pointer depth for an LLVM IR type.
|
Get the base type and pointer depth for an LLVM IR type.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
ir_type: The LLVM IR type to analyze
|
ir_type: The LLVM IR type to analyze
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
A tuple of (base_type, depth) where depth is the number of pointer levels
|
A tuple of (base_type, depth) where depth is the number of pointer levels
|
||||||
"""
|
"""
|
||||||
@ -44,13 +44,13 @@ def _get_base_type_and_depth(ir_type):
|
|||||||
def _deref_to_depth(func, builder, val, target_depth):
|
def _deref_to_depth(func, builder, val, target_depth):
|
||||||
"""
|
"""
|
||||||
Dereference a pointer to a certain depth with null checks.
|
Dereference a pointer to a certain depth with null checks.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
func: The LLVM IR function being built
|
func: The LLVM IR function being built
|
||||||
builder: LLVM IR builder
|
builder: LLVM IR builder
|
||||||
val: The pointer value to dereference
|
val: The pointer value to dereference
|
||||||
target_depth: Number of levels to dereference
|
target_depth: Number of levels to dereference
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The dereferenced value, or None if dereferencing fails
|
The dereferenced value, or None if dereferencing fails
|
||||||
"""
|
"""
|
||||||
@ -101,13 +101,13 @@ def _deref_to_depth(func, builder, val, target_depth):
|
|||||||
def _normalize_types(func, builder, lhs, rhs):
|
def _normalize_types(func, builder, lhs, rhs):
|
||||||
"""
|
"""
|
||||||
Normalize types for comparison by casting or dereferencing as needed.
|
Normalize types for comparison by casting or dereferencing as needed.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
func: The LLVM IR function being built
|
func: The LLVM IR function being built
|
||||||
builder: LLVM IR builder
|
builder: LLVM IR builder
|
||||||
lhs: Left-hand side value
|
lhs: Left-hand side value
|
||||||
rhs: Right-hand side value
|
rhs: Right-hand side value
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
A tuple of (normalized_lhs, normalized_rhs) or (None, None) on error
|
A tuple of (normalized_lhs, normalized_rhs) or (None, None) on error
|
||||||
"""
|
"""
|
||||||
@ -138,11 +138,11 @@ def _normalize_types(func, builder, lhs, rhs):
|
|||||||
def convert_to_bool(builder, val):
|
def convert_to_bool(builder, val):
|
||||||
"""
|
"""
|
||||||
Convert an LLVM IR value to a boolean (i1) type.
|
Convert an LLVM IR value to a boolean (i1) type.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
builder: LLVM IR builder
|
builder: LLVM IR builder
|
||||||
val: The value to convert
|
val: The value to convert
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
An i1 boolean value
|
An i1 boolean value
|
||||||
"""
|
"""
|
||||||
@ -158,14 +158,14 @@ def convert_to_bool(builder, val):
|
|||||||
def handle_comparator(func, builder, op, lhs, rhs):
|
def handle_comparator(func, builder, op, lhs, rhs):
|
||||||
"""
|
"""
|
||||||
Handle comparison operations between two values.
|
Handle comparison operations between two values.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
func: The LLVM IR function being built
|
func: The LLVM IR function being built
|
||||||
builder: LLVM IR builder
|
builder: LLVM IR builder
|
||||||
op: The AST comparison operator node
|
op: The AST comparison operator node
|
||||||
lhs: Left-hand side value
|
lhs: Left-hand side value
|
||||||
rhs: Right-hand side value
|
rhs: Right-hand side value
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
A tuple of (result, ir.IntType(1)) or None on error
|
A tuple of (result, ir.IntType(1)) or None on error
|
||||||
"""
|
"""
|
||||||
|
|||||||
@ -27,12 +27,13 @@ logger = logging.getLogger(__name__)
|
|||||||
class LocalSymbol:
|
class LocalSymbol:
|
||||||
"""
|
"""
|
||||||
Represents a local variable in a BPF function.
|
Represents a local variable in a BPF function.
|
||||||
|
|
||||||
Attributes:
|
Attributes:
|
||||||
var: LLVM IR alloca instruction for the variable
|
var: LLVM IR alloca instruction for the variable
|
||||||
ir_type: LLVM IR type of the variable
|
ir_type: LLVM IR type of the variable
|
||||||
metadata: Optional metadata (e.g., struct type name)
|
metadata: Optional metadata (e.g., struct type name)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
var: ir.AllocaInstr
|
var: ir.AllocaInstr
|
||||||
ir_type: ir.Type
|
ir_type: ir.Type
|
||||||
metadata: Any = None
|
metadata: Any = None
|
||||||
@ -262,7 +263,7 @@ def handle_cond(
|
|||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Evaluate a condition expression and convert it to a boolean value.
|
Evaluate a condition expression and convert it to a boolean value.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
func: The LLVM IR function being built
|
func: The LLVM IR function being built
|
||||||
module: The LLVM IR module
|
module: The LLVM IR module
|
||||||
@ -271,7 +272,7 @@ def handle_cond(
|
|||||||
local_sym_tab: Local symbol table
|
local_sym_tab: Local symbol table
|
||||||
map_sym_tab: Map symbol table
|
map_sym_tab: Map symbol table
|
||||||
structs_sym_tab: Struct symbol table
|
structs_sym_tab: Struct symbol table
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
LLVM IR boolean value representing the condition result
|
LLVM IR boolean value representing the condition result
|
||||||
"""
|
"""
|
||||||
@ -332,13 +333,13 @@ def handle_if(
|
|||||||
def handle_return(builder, stmt, local_sym_tab, ret_type):
|
def handle_return(builder, stmt, local_sym_tab, ret_type):
|
||||||
"""
|
"""
|
||||||
Handle return statements in BPF functions.
|
Handle return statements in BPF functions.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
builder: LLVM IR builder
|
builder: LLVM IR builder
|
||||||
stmt: The AST Return node
|
stmt: The AST Return node
|
||||||
local_sym_tab: Local symbol table
|
local_sym_tab: Local symbol table
|
||||||
ret_type: Expected return type
|
ret_type: Expected return type
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
True if a return was emitted, False otherwise
|
True if a return was emitted, False otherwise
|
||||||
"""
|
"""
|
||||||
@ -375,7 +376,7 @@ def process_stmt(
|
|||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Process a single statement in a BPF function.
|
Process a single statement in a BPF function.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
func: The LLVM IR function being built
|
func: The LLVM IR function being built
|
||||||
module: The LLVM IR module
|
module: The LLVM IR module
|
||||||
@ -386,7 +387,7 @@ def process_stmt(
|
|||||||
structs_sym_tab: Struct symbol table
|
structs_sym_tab: Struct symbol table
|
||||||
did_return: Whether a return has been emitted
|
did_return: Whether a return has been emitted
|
||||||
ret_type: Expected return type
|
ret_type: Expected return type
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
True if a return was emitted, False otherwise
|
True if a return was emitted, False otherwise
|
||||||
"""
|
"""
|
||||||
@ -426,10 +427,10 @@ def allocate_mem(
|
|||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Pre-allocate stack memory for local variables in a BPF function.
|
Pre-allocate stack memory for local variables in a BPF function.
|
||||||
|
|
||||||
This function scans the function body and creates alloca instructions
|
This function scans the function body and creates alloca instructions
|
||||||
for all local variables before processing the function statements.
|
for all local variables before processing the function statements.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
module: The LLVM IR module
|
module: The LLVM IR module
|
||||||
builder: LLVM IR builder
|
builder: LLVM IR builder
|
||||||
@ -439,7 +440,7 @@ def allocate_mem(
|
|||||||
map_sym_tab: Map symbol table
|
map_sym_tab: Map symbol table
|
||||||
local_sym_tab: Local symbol table to populate
|
local_sym_tab: Local symbol table to populate
|
||||||
structs_sym_tab: Struct symbol table
|
structs_sym_tab: Struct symbol table
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Updated local symbol table
|
Updated local symbol table
|
||||||
"""
|
"""
|
||||||
@ -638,7 +639,7 @@ def process_bpf_chunk(func_node, module, return_type, map_sym_tab, structs_sym_t
|
|||||||
def func_proc(tree, module, chunks, map_sym_tab, structs_sym_tab):
|
def func_proc(tree, module, chunks, map_sym_tab, structs_sym_tab):
|
||||||
"""
|
"""
|
||||||
Process all BPF function chunks and generate LLVM IR.
|
Process all BPF function chunks and generate LLVM IR.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
tree: The Python AST (not used in current implementation)
|
tree: The Python AST (not used in current implementation)
|
||||||
module: The LLVM IR module to add functions to
|
module: The LLVM IR module to add functions to
|
||||||
@ -673,13 +674,13 @@ def func_proc(tree, module, chunks, map_sym_tab, structs_sym_tab):
|
|||||||
def infer_return_type(func_node: ast.FunctionDef):
|
def infer_return_type(func_node: ast.FunctionDef):
|
||||||
"""
|
"""
|
||||||
Infer the return type of a BPF function from annotations or return statements.
|
Infer the return type of a BPF function from annotations or return statements.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
func_node: The AST function node
|
func_node: The AST function node
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
String representation of the return type (e.g., 'c_int64')
|
String representation of the return type (e.g., 'c_int64')
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
TypeError: If func_node is not a FunctionDef
|
TypeError: If func_node is not a FunctionDef
|
||||||
"""
|
"""
|
||||||
|
|||||||
@ -21,11 +21,11 @@ global_sym_tab = []
|
|||||||
def populate_global_symbol_table(tree, module: ir.Module):
|
def populate_global_symbol_table(tree, module: ir.Module):
|
||||||
"""
|
"""
|
||||||
Populate the global symbol table with BPF functions, maps, and globals.
|
Populate the global symbol table with BPF functions, maps, and globals.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
tree: The Python AST to scan for global symbols
|
tree: The Python AST to scan for global symbols
|
||||||
module: The LLVM IR module (not used in current implementation)
|
module: The LLVM IR module (not used in current implementation)
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
False (legacy return value)
|
False (legacy return value)
|
||||||
"""
|
"""
|
||||||
@ -52,12 +52,12 @@ def populate_global_symbol_table(tree, module: ir.Module):
|
|||||||
def emit_global(module: ir.Module, node, name):
|
def emit_global(module: ir.Module, node, name):
|
||||||
"""
|
"""
|
||||||
Emit a BPF global variable into the LLVM IR module.
|
Emit a BPF global variable into the LLVM IR module.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
module: The LLVM IR module to add the global variable to
|
module: The LLVM IR module to add the global variable to
|
||||||
node: The AST function node containing the global definition
|
node: The AST function node containing the global definition
|
||||||
name: The name of the global variable
|
name: The name of the global variable
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The created global variable
|
The created global variable
|
||||||
"""
|
"""
|
||||||
@ -146,7 +146,7 @@ def globals_processing(tree, module):
|
|||||||
def emit_llvm_compiler_used(module: ir.Module, names: list[str]):
|
def emit_llvm_compiler_used(module: ir.Module, names: list[str]):
|
||||||
"""
|
"""
|
||||||
Emit the @llvm.compiler.used global to prevent LLVM from optimizing away symbols.
|
Emit the @llvm.compiler.used global to prevent LLVM from optimizing away symbols.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
module: The LLVM IR module to add the compiler.used metadata to
|
module: The LLVM IR module to add the compiler.used metadata to
|
||||||
names: List of function/global names that must be preserved
|
names: List of function/global names that must be preserved
|
||||||
@ -172,7 +172,7 @@ def emit_llvm_compiler_used(module: ir.Module, names: list[str]):
|
|||||||
def globals_list_creation(tree, module: ir.Module):
|
def globals_list_creation(tree, module: ir.Module):
|
||||||
"""
|
"""
|
||||||
Collect all BPF symbols and emit @llvm.compiler.used metadata.
|
Collect all BPF symbols and emit @llvm.compiler.used metadata.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
tree: The Python AST to scan for symbols
|
tree: The Python AST to scan for symbols
|
||||||
module: The LLVM IR module to add metadata to
|
module: The LLVM IR module to add metadata to
|
||||||
|
|||||||
@ -25,6 +25,7 @@ logger: Logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
class BPFHelperID(Enum):
|
class BPFHelperID(Enum):
|
||||||
"""Enumeration of BPF helper function IDs."""
|
"""Enumeration of BPF helper function IDs."""
|
||||||
|
|
||||||
BPF_MAP_LOOKUP_ELEM = 1
|
BPF_MAP_LOOKUP_ELEM = 1
|
||||||
BPF_MAP_UPDATE_ELEM = 2
|
BPF_MAP_UPDATE_ELEM = 2
|
||||||
BPF_MAP_DELETE_ELEM = 3
|
BPF_MAP_DELETE_ELEM = 3
|
||||||
@ -263,7 +264,7 @@ def bpf_perf_event_output_handler(
|
|||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Emit LLVM IR for bpf_perf_event_output helper function call.
|
Emit LLVM IR for bpf_perf_event_output helper function call.
|
||||||
|
|
||||||
This allows sending data to userspace via a perf event array.
|
This allows sending data to userspace via a perf event array.
|
||||||
"""
|
"""
|
||||||
if len(call.args) != 1:
|
if len(call.args) != 1:
|
||||||
|
|||||||
@ -46,14 +46,14 @@ class HelperHandlerRegistry:
|
|||||||
def get_var_ptr_from_name(var_name, local_sym_tab):
|
def get_var_ptr_from_name(var_name, local_sym_tab):
|
||||||
"""
|
"""
|
||||||
Get a pointer to a variable from the symbol table.
|
Get a pointer to a variable from the symbol table.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
var_name: Name of the variable to look up
|
var_name: Name of the variable to look up
|
||||||
local_sym_tab: Local symbol table
|
local_sym_tab: Local symbol table
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Pointer to the variable
|
Pointer to the variable
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValueError: If the variable is not found
|
ValueError: If the variable is not found
|
||||||
"""
|
"""
|
||||||
@ -65,12 +65,12 @@ def get_var_ptr_from_name(var_name, local_sym_tab):
|
|||||||
def create_int_constant_ptr(value, builder, int_width=64):
|
def create_int_constant_ptr(value, builder, int_width=64):
|
||||||
"""
|
"""
|
||||||
Create a pointer to an integer constant.
|
Create a pointer to an integer constant.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
value: The integer value
|
value: The integer value
|
||||||
builder: LLVM IR builder
|
builder: LLVM IR builder
|
||||||
int_width: Width of the integer in bits (default: 64)
|
int_width: Width of the integer in bits (default: 64)
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Pointer to the allocated integer constant
|
Pointer to the allocated integer constant
|
||||||
"""
|
"""
|
||||||
@ -85,15 +85,15 @@ def create_int_constant_ptr(value, builder, int_width=64):
|
|||||||
def get_or_create_ptr_from_arg(arg, builder, local_sym_tab):
|
def get_or_create_ptr_from_arg(arg, builder, local_sym_tab):
|
||||||
"""
|
"""
|
||||||
Extract or create pointer from call arguments.
|
Extract or create pointer from call arguments.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
arg: The AST argument node
|
arg: The AST argument node
|
||||||
builder: LLVM IR builder
|
builder: LLVM IR builder
|
||||||
local_sym_tab: Local symbol table
|
local_sym_tab: Local symbol table
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Pointer to the argument value
|
Pointer to the argument value
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
NotImplementedError: If the argument type is not supported
|
NotImplementedError: If the argument type is not supported
|
||||||
"""
|
"""
|
||||||
@ -112,15 +112,15 @@ def get_or_create_ptr_from_arg(arg, builder, local_sym_tab):
|
|||||||
def get_flags_val(arg, builder, local_sym_tab):
|
def get_flags_val(arg, builder, local_sym_tab):
|
||||||
"""
|
"""
|
||||||
Extract or create flags value from call arguments.
|
Extract or create flags value from call arguments.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
arg: The AST argument node for flags
|
arg: The AST argument node for flags
|
||||||
builder: LLVM IR builder
|
builder: LLVM IR builder
|
||||||
local_sym_tab: Local symbol table
|
local_sym_tab: Local symbol table
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Integer flags value or LLVM IR value
|
Integer flags value or LLVM IR value
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValueError: If a variable is not found in symbol table
|
ValueError: If a variable is not found in symbol table
|
||||||
NotImplementedError: If the argument type is not supported
|
NotImplementedError: If the argument type is not supported
|
||||||
@ -145,13 +145,13 @@ def get_flags_val(arg, builder, local_sym_tab):
|
|||||||
def simple_string_print(string_value, module, builder, func):
|
def simple_string_print(string_value, module, builder, func):
|
||||||
"""
|
"""
|
||||||
Prepare arguments for bpf_printk from a simple string value.
|
Prepare arguments for bpf_printk from a simple string value.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
string_value: The string to print
|
string_value: The string to print
|
||||||
module: LLVM IR module
|
module: LLVM IR module
|
||||||
builder: LLVM IR builder
|
builder: LLVM IR builder
|
||||||
func: The LLVM IR function being built
|
func: The LLVM IR function being built
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
List of arguments for bpf_printk
|
List of arguments for bpf_printk
|
||||||
"""
|
"""
|
||||||
@ -172,7 +172,7 @@ def handle_fstring_print(
|
|||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Handle f-string formatting for bpf_printk emitter.
|
Handle f-string formatting for bpf_printk emitter.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
joined_str: AST JoinedStr node representing the f-string
|
joined_str: AST JoinedStr node representing the f-string
|
||||||
module: LLVM IR module
|
module: LLVM IR module
|
||||||
@ -180,10 +180,10 @@ def handle_fstring_print(
|
|||||||
func: The LLVM IR function being built
|
func: The LLVM IR function being built
|
||||||
local_sym_tab: Local symbol table
|
local_sym_tab: Local symbol table
|
||||||
struct_sym_tab: Struct symbol table
|
struct_sym_tab: Struct symbol table
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
List of arguments for bpf_printk
|
List of arguments for bpf_printk
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
NotImplementedError: If f-string contains unsupported value types
|
NotImplementedError: If f-string contains unsupported value types
|
||||||
"""
|
"""
|
||||||
|
|||||||
@ -12,7 +12,7 @@ import ctypes
|
|||||||
def ktime():
|
def ktime():
|
||||||
"""
|
"""
|
||||||
Get the current kernel time in nanoseconds.
|
Get the current kernel time in nanoseconds.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
A c_int64 stub value (actual implementation is in BPF runtime)
|
A c_int64 stub value (actual implementation is in BPF runtime)
|
||||||
"""
|
"""
|
||||||
@ -22,7 +22,7 @@ def ktime():
|
|||||||
def pid():
|
def pid():
|
||||||
"""
|
"""
|
||||||
Get the current process ID (PID).
|
Get the current process ID (PID).
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
A c_int32 stub value (actual implementation is in BPF runtime)
|
A c_int32 stub value (actual implementation is in BPF runtime)
|
||||||
"""
|
"""
|
||||||
|
|||||||
@ -16,11 +16,11 @@ logger: Logger = logging.getLogger(__name__)
|
|||||||
def emit_license(module: ir.Module, license_str: str):
|
def emit_license(module: ir.Module, license_str: str):
|
||||||
"""
|
"""
|
||||||
Emit a LICENSE global variable into the LLVM IR module.
|
Emit a LICENSE global variable into the LLVM IR module.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
module: The LLVM IR module to add the LICENSE variable to
|
module: The LLVM IR module to add the LICENSE variable to
|
||||||
license_str: The license string (e.g., 'GPL')
|
license_str: The license string (e.g., 'GPL')
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The created global variable
|
The created global variable
|
||||||
"""
|
"""
|
||||||
|
|||||||
@ -6,19 +6,20 @@ These are used for type checking and map definition; the actual BPF maps
|
|||||||
are generated as LLVM IR during compilation.
|
are generated as LLVM IR during compilation.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
# This file provides type and function hints only and does not actually give any functionality.
|
# This file provides type and function hints only and does not actually give any functionality.
|
||||||
class HashMap:
|
class HashMap:
|
||||||
"""
|
"""
|
||||||
A BPF hash map for storing key-value pairs.
|
A BPF hash map for storing key-value pairs.
|
||||||
|
|
||||||
This is a type hint class used during compilation. The actual BPF map
|
This is a type hint class used during compilation. The actual BPF map
|
||||||
implementation is generated as LLVM IR.
|
implementation is generated as LLVM IR.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, key, value, max_entries):
|
def __init__(self, key, value, max_entries):
|
||||||
"""
|
"""
|
||||||
Initialize a HashMap definition.
|
Initialize a HashMap definition.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
key: The ctypes type for keys (e.g., c_int64)
|
key: The ctypes type for keys (e.g., c_int64)
|
||||||
value: The ctypes type for values (e.g., c_int64)
|
value: The ctypes type for values (e.g., c_int64)
|
||||||
@ -32,10 +33,10 @@ class HashMap:
|
|||||||
def lookup(self, key):
|
def lookup(self, key):
|
||||||
"""
|
"""
|
||||||
Look up a value by key in the map.
|
Look up a value by key in the map.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
key: The key to look up
|
key: The key to look up
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The value if found, None otherwise
|
The value if found, None otherwise
|
||||||
"""
|
"""
|
||||||
@ -47,10 +48,10 @@ class HashMap:
|
|||||||
def delete(self, key):
|
def delete(self, key):
|
||||||
"""
|
"""
|
||||||
Delete an entry from the map by key.
|
Delete an entry from the map by key.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
key: The key to delete
|
key: The key to delete
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
KeyError: If the key is not found in the map
|
KeyError: If the key is not found in the map
|
||||||
"""
|
"""
|
||||||
@ -63,12 +64,12 @@ class HashMap:
|
|||||||
def update(self, key, value, flags=None):
|
def update(self, key, value, flags=None):
|
||||||
"""
|
"""
|
||||||
Update or insert a key-value pair in the map.
|
Update or insert a key-value pair in the map.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
key: The key to update
|
key: The key to update
|
||||||
value: The new value
|
value: The new value
|
||||||
flags: Optional flags for update behavior
|
flags: Optional flags for update behavior
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
KeyError: If the key is not found in the map
|
KeyError: If the key is not found in the map
|
||||||
"""
|
"""
|
||||||
@ -81,14 +82,14 @@ class HashMap:
|
|||||||
class PerfEventArray:
|
class PerfEventArray:
|
||||||
"""
|
"""
|
||||||
A BPF perf event array for sending data to userspace.
|
A BPF perf event array for sending data to userspace.
|
||||||
|
|
||||||
This is a type hint class used during compilation.
|
This is a type hint class used during compilation.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, key_size, value_size):
|
def __init__(self, key_size, value_size):
|
||||||
"""
|
"""
|
||||||
Initialize a PerfEventArray definition.
|
Initialize a PerfEventArray definition.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
key_size: The size/type for keys
|
key_size: The size/type for keys
|
||||||
value_size: The size/type for values
|
value_size: The size/type for values
|
||||||
@ -100,7 +101,7 @@ class PerfEventArray:
|
|||||||
def output(self, data):
|
def output(self, data):
|
||||||
"""
|
"""
|
||||||
Output data to the perf event array.
|
Output data to the perf event array.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
data: The data to output
|
data: The data to output
|
||||||
"""
|
"""
|
||||||
@ -110,14 +111,14 @@ class PerfEventArray:
|
|||||||
class RingBuf:
|
class RingBuf:
|
||||||
"""
|
"""
|
||||||
A BPF ring buffer for efficient data transfer to userspace.
|
A BPF ring buffer for efficient data transfer to userspace.
|
||||||
|
|
||||||
This is a type hint class used during compilation.
|
This is a type hint class used during compilation.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, max_entries):
|
def __init__(self, max_entries):
|
||||||
"""
|
"""
|
||||||
Initialize a RingBuf definition.
|
Initialize a RingBuf definition.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
max_entries: Maximum number of entries the ring buffer can hold
|
max_entries: Maximum number of entries the ring buffer can hold
|
||||||
"""
|
"""
|
||||||
@ -126,14 +127,14 @@ class RingBuf:
|
|||||||
def reserve(self, size: int, flags=0):
|
def reserve(self, size: int, flags=0):
|
||||||
"""
|
"""
|
||||||
Reserve space in the ring buffer.
|
Reserve space in the ring buffer.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
size: Size in bytes to reserve
|
size: Size in bytes to reserve
|
||||||
flags: Optional reservation flags
|
flags: Optional reservation flags
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
0 as a placeholder (actual implementation is in BPF runtime)
|
0 as a placeholder (actual implementation is in BPF runtime)
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValueError: If size exceeds max_entries
|
ValueError: If size exceeds max_entries
|
||||||
"""
|
"""
|
||||||
@ -144,7 +145,7 @@ class RingBuf:
|
|||||||
def submit(self, data, flags=0):
|
def submit(self, data, flags=0):
|
||||||
"""
|
"""
|
||||||
Submit data to the ring buffer.
|
Submit data to the ring buffer.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
data: The data to submit
|
data: The data to submit
|
||||||
flags: Optional submission flags
|
flags: Optional submission flags
|
||||||
|
|||||||
@ -29,10 +29,10 @@ def maps_proc(tree, module, chunks):
|
|||||||
def is_map(func_node):
|
def is_map(func_node):
|
||||||
"""
|
"""
|
||||||
Check if a function node is decorated with @map.
|
Check if a function node is decorated with @map.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
func_node: The AST function node to check
|
func_node: The AST function node to check
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
True if the function is decorated with @map, False otherwise
|
True if the function is decorated with @map, False otherwise
|
||||||
"""
|
"""
|
||||||
@ -44,6 +44,7 @@ def is_map(func_node):
|
|||||||
|
|
||||||
class BPFMapType(Enum):
|
class BPFMapType(Enum):
|
||||||
"""Enumeration of BPF map types."""
|
"""Enumeration of BPF map types."""
|
||||||
|
|
||||||
UNSPEC = 0
|
UNSPEC = 0
|
||||||
HASH = 1
|
HASH = 1
|
||||||
ARRAY = 2
|
ARRAY = 2
|
||||||
@ -84,12 +85,12 @@ class BPFMapType(Enum):
|
|||||||
def create_bpf_map(module, map_name, map_params):
|
def create_bpf_map(module, map_name, map_params):
|
||||||
"""
|
"""
|
||||||
Create a BPF map in the module with given parameters and debug info.
|
Create a BPF map in the module with given parameters and debug info.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
module: The LLVM IR module to add the map to
|
module: The LLVM IR module to add the map to
|
||||||
map_name: The name of the BPF map
|
map_name: The name of the BPF map
|
||||||
map_params: Dictionary of map parameters (type, key_size, value_size, max_entries)
|
map_params: Dictionary of map parameters (type, key_size, value_size, max_entries)
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The created global variable representing the map
|
The created global variable representing the map
|
||||||
"""
|
"""
|
||||||
|
|||||||
@ -11,17 +11,17 @@ from llvmlite import ir
|
|||||||
class StructType:
|
class StructType:
|
||||||
"""
|
"""
|
||||||
Wrapper class for LLVM IR struct types with field access helpers.
|
Wrapper class for LLVM IR struct types with field access helpers.
|
||||||
|
|
||||||
Attributes:
|
Attributes:
|
||||||
ir_type: The LLVM IR struct type
|
ir_type: The LLVM IR struct type
|
||||||
fields: Dictionary mapping field names to their types
|
fields: Dictionary mapping field names to their types
|
||||||
size: Total size of the struct in bytes
|
size: Total size of the struct in bytes
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, ir_type, fields, size):
|
def __init__(self, ir_type, fields, size):
|
||||||
"""
|
"""
|
||||||
Initialize a StructType.
|
Initialize a StructType.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
ir_type: The LLVM IR struct type
|
ir_type: The LLVM IR struct type
|
||||||
fields: Dictionary mapping field names to their types
|
fields: Dictionary mapping field names to their types
|
||||||
@ -34,10 +34,10 @@ class StructType:
|
|||||||
def field_idx(self, field_name):
|
def field_idx(self, field_name):
|
||||||
"""
|
"""
|
||||||
Get the index of a field in the struct.
|
Get the index of a field in the struct.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
field_name: The name of the field
|
field_name: The name of the field
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The zero-based index of the field
|
The zero-based index of the field
|
||||||
"""
|
"""
|
||||||
@ -46,10 +46,10 @@ class StructType:
|
|||||||
def field_type(self, field_name):
|
def field_type(self, field_name):
|
||||||
"""
|
"""
|
||||||
Get the LLVM IR type of a field.
|
Get the LLVM IR type of a field.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
field_name: The name of the field
|
field_name: The name of the field
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The LLVM IR type of the field
|
The LLVM IR type of the field
|
||||||
"""
|
"""
|
||||||
@ -58,12 +58,12 @@ class StructType:
|
|||||||
def gep(self, builder, ptr, field_name):
|
def gep(self, builder, ptr, field_name):
|
||||||
"""
|
"""
|
||||||
Generate a GEP (GetElementPtr) instruction to access a struct field.
|
Generate a GEP (GetElementPtr) instruction to access a struct field.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
builder: LLVM IR builder
|
builder: LLVM IR builder
|
||||||
ptr: Pointer to the struct
|
ptr: Pointer to the struct
|
||||||
field_name: Name of the field to access
|
field_name: Name of the field to access
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
A pointer to the field
|
A pointer to the field
|
||||||
"""
|
"""
|
||||||
@ -77,13 +77,13 @@ class StructType:
|
|||||||
def field_size(self, field_name):
|
def field_size(self, field_name):
|
||||||
"""
|
"""
|
||||||
Calculate the size of a field in bytes.
|
Calculate the size of a field in bytes.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
field_name: The name of the field
|
field_name: The name of the field
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The size of the field in bytes
|
The size of the field in bytes
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
TypeError: If the field type is not supported
|
TypeError: If the field type is not supported
|
||||||
"""
|
"""
|
||||||
|
|||||||
@ -35,10 +35,10 @@ def structs_proc(tree, module, chunks):
|
|||||||
def is_bpf_struct(cls_node):
|
def is_bpf_struct(cls_node):
|
||||||
"""
|
"""
|
||||||
Check if a class node is decorated with @struct.
|
Check if a class node is decorated with @struct.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
cls_node: The AST class node to check
|
cls_node: The AST class node to check
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
True if the class is decorated with @struct, False otherwise
|
True if the class is decorated with @struct, False otherwise
|
||||||
"""
|
"""
|
||||||
@ -51,11 +51,11 @@ def is_bpf_struct(cls_node):
|
|||||||
def process_bpf_struct(cls_node, module):
|
def process_bpf_struct(cls_node, module):
|
||||||
"""
|
"""
|
||||||
Process a single BPF struct definition and create its LLVM IR representation.
|
Process a single BPF struct definition and create its LLVM IR representation.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
cls_node: The AST class node representing the struct
|
cls_node: The AST class node representing the struct
|
||||||
module: The LLVM IR module (not used in current implementation)
|
module: The LLVM IR module (not used in current implementation)
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
A StructType object containing the struct's type information
|
A StructType object containing the struct's type information
|
||||||
"""
|
"""
|
||||||
@ -71,13 +71,13 @@ def process_bpf_struct(cls_node, module):
|
|||||||
def parse_struct_fields(cls_node):
|
def parse_struct_fields(cls_node):
|
||||||
"""
|
"""
|
||||||
Parse fields of a struct class node.
|
Parse fields of a struct class node.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
cls_node: The AST class node representing the struct
|
cls_node: The AST class node representing the struct
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
A dictionary mapping field names to their LLVM IR types
|
A dictionary mapping field names to their LLVM IR types
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
TypeError: If a field has an unsupported type annotation
|
TypeError: If a field has an unsupported type annotation
|
||||||
"""
|
"""
|
||||||
@ -95,13 +95,13 @@ def parse_struct_fields(cls_node):
|
|||||||
def get_type_from_ann(annotation):
|
def get_type_from_ann(annotation):
|
||||||
"""
|
"""
|
||||||
Convert an AST annotation node to an LLVM IR type for struct fields.
|
Convert an AST annotation node to an LLVM IR type for struct fields.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
annotation: The AST annotation node (e.g., c_int64, str(32))
|
annotation: The AST annotation node (e.g., c_int64, str(32))
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The corresponding LLVM IR type
|
The corresponding LLVM IR type
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
TypeError: If the annotation type is not supported
|
TypeError: If the annotation type is not supported
|
||||||
"""
|
"""
|
||||||
@ -121,10 +121,10 @@ def get_type_from_ann(annotation):
|
|||||||
def calc_struct_size(field_types):
|
def calc_struct_size(field_types):
|
||||||
"""
|
"""
|
||||||
Calculate total size of the struct with alignment and padding.
|
Calculate total size of the struct with alignment and padding.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
field_types: List of LLVM IR types for each field
|
field_types: List of LLVM IR types for each field
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The total size of the struct in bytes
|
The total size of the struct in bytes
|
||||||
"""
|
"""
|
||||||
|
|||||||
@ -28,13 +28,13 @@ mapping = {
|
|||||||
def ctypes_to_ir(ctype: str):
|
def ctypes_to_ir(ctype: str):
|
||||||
"""
|
"""
|
||||||
Convert a ctypes type name to its corresponding LLVM IR type.
|
Convert a ctypes type name to its corresponding LLVM IR type.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
ctype: String name of the ctypes type (e.g., 'c_int64', 'c_void_p')
|
ctype: String name of the ctypes type (e.g., 'c_int64', 'c_void_p')
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The corresponding LLVM IR type
|
The corresponding LLVM IR type
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
NotImplementedError: If the ctype is not supported
|
NotImplementedError: If the ctype is not supported
|
||||||
"""
|
"""
|
||||||
@ -46,10 +46,10 @@ def ctypes_to_ir(ctype: str):
|
|||||||
def is_ctypes(ctype: str) -> bool:
|
def is_ctypes(ctype: str) -> bool:
|
||||||
"""
|
"""
|
||||||
Check if a given type name is a supported ctypes type.
|
Check if a given type name is a supported ctypes type.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
ctype: String name of the type to check
|
ctype: String name of the type to check
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
True if the type is a supported ctypes type, False otherwise
|
True if the type is a supported ctypes type, False otherwise
|
||||||
"""
|
"""
|
||||||
|
|||||||
@ -33,3 +33,5 @@ compile_to_ir("ringbuf.py", "ringbuf.ll")
|
|||||||
compile()
|
compile()
|
||||||
b = BPF()
|
b = BPF()
|
||||||
b.load_and_attach()
|
b.load_and_attach()
|
||||||
|
while True:
|
||||||
|
print("running")
|
||||||
|
|||||||
Reference in New Issue
Block a user