|
| 1 | +import ctypes |
| 2 | +import logging |
| 3 | +from typing import Dict, Type |
| 4 | + |
| 5 | +from llvmlite import ir |
| 6 | + |
| 7 | +logger = logging.getLogger(__name__) |
| 8 | + |
| 9 | + |
| 10 | +def ir_type_to_ctypes(ir_type): |
| 11 | + """Convert LLVM IR type to ctypes type.""" |
| 12 | + if isinstance(ir_type, ir.IntType): |
| 13 | + width = ir_type.width |
| 14 | + type_map = { |
| 15 | + 8: ctypes.c_uint8, |
| 16 | + 16: ctypes.c_uint16, |
| 17 | + 32: ctypes.c_uint32, |
| 18 | + 64: ctypes.c_uint64, |
| 19 | + } |
| 20 | + if width not in type_map: |
| 21 | + raise ValueError(f"Unsupported integer width: {width}") |
| 22 | + return type_map[width] |
| 23 | + |
| 24 | + elif isinstance(ir_type, ir.ArrayType): |
| 25 | + count = ir_type.count |
| 26 | + element_type_ir = ir_type.element |
| 27 | + |
| 28 | + if isinstance(element_type_ir, ir.IntType) and element_type_ir.width == 8: |
| 29 | + # Use c_char for string fields (will have .decode()) |
| 30 | + return ctypes.c_char * count |
| 31 | + else: |
| 32 | + element_type = ir_type_to_ctypes(element_type_ir) |
| 33 | + return element_type * count |
| 34 | + elif isinstance(ir_type, ir.PointerType): |
| 35 | + return ctypes.c_void_p |
| 36 | + |
| 37 | + else: |
| 38 | + raise TypeError(f"Unsupported IR type: {ir_type}") |
| 39 | + |
| 40 | + |
| 41 | +def _make_repr(struct_name: str, fields: list): |
| 42 | + """Create a __repr__ function for a struct""" |
| 43 | + |
| 44 | + def __repr__(self): |
| 45 | + field_strs = [] |
| 46 | + for field_name, _ in fields: |
| 47 | + value = getattr(self, field_name) |
| 48 | + field_strs.append(f"{field_name}={value}") |
| 49 | + return f"<{struct_name} {' '.join(field_strs)}>" |
| 50 | + |
| 51 | + return __repr__ |
| 52 | + |
| 53 | + |
| 54 | +def convert_structs_to_ctypes(structs_sym_tab) -> Dict[str, Type[ctypes.Structure]]: |
| 55 | + """Convert PythonBPF's structs_sym_tab to ctypes.Structure classes.""" |
| 56 | + if not structs_sym_tab: |
| 57 | + return {} |
| 58 | + |
| 59 | + ctypes_structs = {} |
| 60 | + |
| 61 | + for struct_name, struct_type_obj in structs_sym_tab.items(): |
| 62 | + try: |
| 63 | + fields = [] |
| 64 | + for field_name, field_ir_type in struct_type_obj.fields.items(): |
| 65 | + field_ctypes = ir_type_to_ctypes(field_ir_type) |
| 66 | + fields.append((field_name, field_ctypes)) |
| 67 | + |
| 68 | + repr_func = _make_repr(struct_name, fields) |
| 69 | + |
| 70 | + struct_class = type( |
| 71 | + struct_name, |
| 72 | + (ctypes.Structure,), |
| 73 | + { |
| 74 | + "_fields_": fields, |
| 75 | + "__module__": "pylibbpf.ir_to_ctypes", |
| 76 | + "__doc__": f"Auto-generated ctypes structure for {struct_name}", |
| 77 | + "__repr__": repr_func, |
| 78 | + }, |
| 79 | + ) |
| 80 | + |
| 81 | + ctypes_structs[struct_name] = struct_class |
| 82 | + # Pretty print field info |
| 83 | + field_info = ", ".join(f"{name}: {typ.__name__}" for name, typ in fields) |
| 84 | + logger.debug(f" {struct_name}({field_info})") |
| 85 | + except Exception as e: |
| 86 | + logger.error(f"Failed to convert struct '{struct_name}': {e}") |
| 87 | + raise |
| 88 | + logger.info(f"Converted struct '{struct_name}' to ctypes") |
| 89 | + return ctypes_structs |
| 90 | + |
| 91 | + |
| 92 | +def is_pythonbpf_structs(structs) -> bool: |
| 93 | + """Check if structs dict is from PythonBPF.""" |
| 94 | + if not isinstance(structs, dict) or not structs: |
| 95 | + return False |
| 96 | + |
| 97 | + first_value = next(iter(structs.values())) |
| 98 | + return ( |
| 99 | + hasattr(first_value, "ir_type") |
| 100 | + and hasattr(first_value, "fields") |
| 101 | + and hasattr(first_value, "size") |
| 102 | + ) |
| 103 | + |
| 104 | + |
| 105 | +__all__ = ["convert_structs_to_ctypes", "is_pythonbpf_structs"] |
0 commit comments