diff --git a/pythonbpf/allocation_pass.py b/pythonbpf/allocation_pass.py index aaf2539..aff095a 100644 --- a/pythonbpf/allocation_pass.py +++ b/pythonbpf/allocation_pass.py @@ -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, IntTy, signedness +from pythonbpf.type_deducer import ctypes_to_ir, is_ctypes, IntTy, signedness from pythonbpf.expr.type_inference import infer_int_type from pythonbpf.maps import BPFMapType @@ -110,7 +110,9 @@ def _allocate_for_call(builder, var_name, rval, local_sym_tab, compilation_conte call_type = rval.func.id # C type constructors - if call_type in ("c_int32", "c_int64", "c_uint32", "c_uint64", "c_void_p"): + if is_ctypes(call_type) and isinstance(ctypes_to_ir(call_type), ir.IntType): + # Any integer ctypes constructor, c_uint16 included, declares a + # 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 diff --git a/tests/test_signedness_ir.py b/tests/test_signedness_ir.py index 2166ed8..5a4b31d 100644 --- a/tests/test_signedness_ir.py +++ b/tests/test_signedness_ir.py @@ -68,6 +68,12 @@ CASES = { [r"\bsub i64", r"trunc i64 .* to i32", r"zext i32 .* to i64"], [], ), + # c_uint16(0) declares a 16-bit slot, so a u32 ctx field stored into it + # is truncated to 16 bits (C: __u16 queue = ctx->rx_queue_index). + "vmlinux/ctx_field_narrow_store.py": ( + [r'%"queue" = alloca i16', r"trunc i64 .* to i16"], + [r'%"queue" = alloca i64'], + ), # A bool widens with zext and an integer narrows to it by != 0, never by # trunc; sext of an i1 would return -1 for True. "signedness/bool_int.py": (