mirror of
https://github.com/varun-r-mallya/Python-BPF.git
synced 2026-12-06 01:48:35 +00:00
Core: Size and describe integers by their real width
Two places took an integer's width as 32 or 64 bits. Ten sites computed byte sizes as width // 8 (alignment, struct layout, globals), which is zero for a 1-bit type; they now share byte_size(), which rounds up to whole bytes. And debug info described every map key or value, and every struct field, that was not 32 bits wide as unsigned long long: a c_uint8 or c_uint16 map value was declared 8 bytes wide in BTF, so the kernel copied 8 bytes from a smaller slot. get_int_type() now gives the real width and sign everywhere, globals included. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@ -6,7 +6,7 @@ from .symbols import LocalSymbol
|
||||
from pythonbpf.helper import HelperHandlerRegistry
|
||||
from pythonbpf.vmlinux_parser.dependency_node import Field
|
||||
from .expr import VmlinuxHandlerRegistry
|
||||
from pythonbpf.type_deducer import ctypes_to_ir, is_ctypes, IntTy, signedness
|
||||
from pythonbpf.type_deducer import ctypes_to_ir, is_ctypes, IntTy, signedness, byte_size
|
||||
from pythonbpf.expr.type_inference import infer_int_type
|
||||
from pythonbpf.maps import BPFMapType
|
||||
|
||||
@ -115,7 +115,7 @@ def _allocate_for_call(builder, var_name, rval, local_sym_tab, compilation_conte
|
||||
# slot of that width; the value is converted into it at the store.
|
||||
ir_type = ctypes_to_ir(call_type)
|
||||
var = builder.alloca(ir_type, name=var_name)
|
||||
var.align = ir_type.width // 8
|
||||
var.align = byte_size(ir_type)
|
||||
local_sym_tab[var_name] = LocalSymbol(var, ir_type)
|
||||
logger.info(f"Pre-allocated {var_name} as {call_type}")
|
||||
|
||||
@ -472,7 +472,7 @@ def _allocate_for_attribute(
|
||||
tmp_name = f"{struct_var}_{field_name}_tmp"
|
||||
tmp_ir_type = ir.IntType(field_size_bits)
|
||||
tmp_var = builder.alloca(tmp_ir_type, name=tmp_name)
|
||||
tmp_var.align = tmp_ir_type.width // 8
|
||||
tmp_var.align = byte_size(tmp_ir_type)
|
||||
local_sym_tab[tmp_name] = LocalSymbol(tmp_var, tmp_ir_type)
|
||||
logger.info(
|
||||
f"Pre-allocated temp {tmp_name} (i{field_size_bits}) for vmlinux field read {vmlinux_struct_name}.{field_name}"
|
||||
@ -527,8 +527,8 @@ def _allocate_with_type(builder, var_name, ir_type):
|
||||
def _get_alignment(ir_type):
|
||||
"""Get appropriate alignment for IR type."""
|
||||
if isinstance(ir_type, ir.IntType):
|
||||
return ir_type.width // 8
|
||||
return byte_size(ir_type)
|
||||
elif isinstance(ir_type, ir.ArrayType) and isinstance(ir_type.element, ir.IntType):
|
||||
return ir_type.element.width // 8
|
||||
return byte_size(ir_type.element)
|
||||
else:
|
||||
return 8 # Default: pointer size
|
||||
|
||||
@ -49,6 +49,27 @@ class DebugInfoGenerator:
|
||||
)
|
||||
return self._type_cache[key]
|
||||
|
||||
def get_int_type(self, ty) -> Any:
|
||||
"""Debug type for an integer IR type, by width and sign (read from the
|
||||
IntTy descriptor, signed for a plain ir.IntType). A 1-bit type is C's
|
||||
_Bool, which occupies one byte. BTF, and so a map's key and value
|
||||
sizes, come from this, so the width must be the real one."""
|
||||
from pythonbpf.type_deducer import signedness
|
||||
|
||||
width, signed = ty.width, signedness(ty)
|
||||
if width == 1:
|
||||
return self.get_basic_type("_Bool", 8, dc.DW_ATE_boolean)
|
||||
base = {8: "char", 16: "short", 32: "int", 64: "long long"}.get(width)
|
||||
if base is None:
|
||||
raise ValueError(f"no debug type for a {width}-bit integer")
|
||||
if width == 8:
|
||||
encoding = dc.DW_ATE_signed_char if signed else dc.DW_ATE_unsigned_char
|
||||
else:
|
||||
encoding = dc.DW_ATE_signed if signed else dc.DW_ATE_unsigned
|
||||
return self.get_basic_type(
|
||||
base if signed else f"unsigned {base}", width, encoding
|
||||
)
|
||||
|
||||
def get_uint8_type(self) -> Any:
|
||||
"""Get debug info for signed 8-bit integer"""
|
||||
return self.get_basic_type("char", 8, dc.DW_ATE_unsigned)
|
||||
|
||||
@ -3,16 +3,13 @@ import ast
|
||||
|
||||
from logging import Logger
|
||||
import logging
|
||||
from .type_deducer import ctypes_to_ir, is_signed_ctype
|
||||
from .type_deducer import ctypes_to_ir, byte_size
|
||||
from .symbols import BpfGlobalSymbol
|
||||
from .debuginfo import DebugInfoGenerator
|
||||
from .expr import VmlinuxHandlerRegistry
|
||||
from .debuginfo import dwarf_constants as dc
|
||||
|
||||
logger: Logger = logging.getLogger(__name__)
|
||||
|
||||
_C_NAME_BY_WIDTH = {8: "char", 16: "short", 32: "int", 64: "long long"}
|
||||
|
||||
|
||||
def populate_global_symbol_table(tree, compilation_context):
|
||||
"""
|
||||
@ -78,7 +75,7 @@ def _emit_global(module: ir.Module, node, name):
|
||||
# (align 4 for i32, align 8 for i64). llc derives the BTF DATASEC layout
|
||||
# from these symbols, so the alignment should mirror the C reference in
|
||||
# tests/c-form/global_vars.bpf.c.
|
||||
gvar.align = ty.width // 8 if isinstance(ty, ir.IntType) else 8
|
||||
gvar.align = byte_size(ty) if isinstance(ty, ir.IntType) else 8
|
||||
gvar.linkage = "dso_local"
|
||||
gvar.global_constant = False
|
||||
return gvar
|
||||
@ -93,15 +90,7 @@ def _emit_global_debug_info(compilation_context, gvar, name, ctype_name):
|
||||
future skeleton can tell which variable lives at which offset.
|
||||
"""
|
||||
generator = DebugInfoGenerator(compilation_context.module)
|
||||
width = gvar.value_type.width
|
||||
signed = is_signed_ctype(ctype_name)
|
||||
base = _C_NAME_BY_WIDTH[width]
|
||||
if width == 8:
|
||||
encoding = dc.DW_ATE_signed_char if signed else dc.DW_ATE_unsigned_char
|
||||
else:
|
||||
encoding = dc.DW_ATE_signed if signed else dc.DW_ATE_unsigned
|
||||
cname = base if signed else f"unsigned {base}"
|
||||
di_type = generator.get_basic_type(cname, width, encoding)
|
||||
di_type = generator.get_int_type(ctypes_to_ir(ctype_name))
|
||||
dv = generator.create_global_var_debug_info(name, di_type, is_local=False)
|
||||
gvar.set_metadata("dbg", dv)
|
||||
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
from pythonbpf.type_deducer import ctypes_to_ir, is_ctypes
|
||||
import logging
|
||||
from llvmlite import ir
|
||||
from pythonbpf.debuginfo import DebugInfoGenerator
|
||||
@ -122,11 +123,12 @@ def _get_key_val_dbg_type(name, generator, structs_sym_tab):
|
||||
# Fallback to basic types
|
||||
logger.info(f"No struct named {name}, falling back to basic type")
|
||||
|
||||
# NOTE: Only handling int and long for now
|
||||
if name in ["c_int32", "c_uint32"]:
|
||||
return generator.get_uint32_type()
|
||||
# A ctypes integer: its real width and sign, so the map's key or value
|
||||
# size in BTF matches what the program stores (a c_uint8 value is 1 byte).
|
||||
if is_ctypes(name):
|
||||
return generator.get_int_type(ctypes_to_ir(name))
|
||||
|
||||
# Default fallback for now
|
||||
logger.warning(f"No debug type for map key/value {name}, defaulting to u64")
|
||||
return generator.get_uint64_type()
|
||||
|
||||
|
||||
@ -136,11 +138,7 @@ def _get_struct_debug_type(struct_obj, generator, structs_sym_tab):
|
||||
for fld in struct_obj.fields.keys():
|
||||
fld_type = struct_obj.field_type(fld)
|
||||
if isinstance(fld_type, ir.IntType):
|
||||
if fld_type.width == 32:
|
||||
fld_dbg_type = generator.get_uint32_type()
|
||||
else:
|
||||
# NOTE: Assuming 64-bit for all other int types
|
||||
fld_dbg_type = generator.get_uint64_type()
|
||||
fld_dbg_type = generator.get_int_type(fld_type)
|
||||
elif isinstance(fld_type, ir.ArrayType):
|
||||
# NOTE: Array types have u8 elements only for now
|
||||
# Debug info generation should fail for other types
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
from pythonbpf.type_deducer import byte_size
|
||||
from llvmlite import ir
|
||||
|
||||
|
||||
@ -24,9 +25,9 @@ class StructType:
|
||||
def field_size(self, field_name):
|
||||
fld = self.fields[field_name]
|
||||
if isinstance(fld, ir.ArrayType):
|
||||
return fld.count * (fld.element.width // 8)
|
||||
return fld.count * byte_size(fld.element)
|
||||
elif isinstance(fld, ir.IntType):
|
||||
return fld.width // 8
|
||||
return byte_size(fld)
|
||||
elif isinstance(fld, ir.PointerType):
|
||||
return 8
|
||||
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import ast
|
||||
import logging
|
||||
from llvmlite import ir
|
||||
from pythonbpf.type_deducer import ctypes_to_ir
|
||||
from pythonbpf.type_deducer import ctypes_to_ir, byte_size
|
||||
from .struct_type import StructType
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@ -79,11 +79,11 @@ def calc_struct_size(field_types):
|
||||
curr_offset = 0
|
||||
for ftype in field_types:
|
||||
if isinstance(ftype, ir.IntType):
|
||||
fsize = ftype.width // 8
|
||||
fsize = byte_size(ftype)
|
||||
alignment = fsize
|
||||
elif isinstance(ftype, ir.ArrayType):
|
||||
fsize = ftype.count * (ftype.element.width // 8)
|
||||
alignment = ftype.element.width // 8
|
||||
fsize = ftype.count * byte_size(ftype.element)
|
||||
alignment = byte_size(ftype.element)
|
||||
elif isinstance(ftype, ir.PointerType):
|
||||
# We won't encounter this rn, but for the future
|
||||
fsize = 8
|
||||
|
||||
@ -41,6 +41,12 @@ class IntTy(ir.IntType):
|
||||
return f"{'i' if self.signed else 'u'}{self.width}"
|
||||
|
||||
|
||||
def byte_size(ty) -> int:
|
||||
"""Bytes an integer type occupies in memory: its width rounded up to whole
|
||||
bytes, so a 1-bit bool still takes one byte, as C's _Bool does."""
|
||||
return (ty.width + 7) // 8
|
||||
|
||||
|
||||
def int_literal_type(value: int) -> IntTy:
|
||||
"""C's type for an integer constant: `int` if the value fits, else
|
||||
`long long`. Literals and enum constants alike; an enum constant is an
|
||||
|
||||
Reference in New Issue
Block a user