diff --git a/tests/passing_tests/signedness/bool_int.py b/tests/passing_tests/signedness/bool_int.py new file mode 100644 index 0000000..3103ec6 --- /dev/null +++ b/tests/passing_tests/signedness/bool_int.py @@ -0,0 +1,24 @@ +# A bool is a 1-bit integer to LLVM, and C's rules for it are not the integer +# ones: it widens to 0 or 1 (never sign-extends to -1), and an integer narrows +# to it by comparing with zero (2 is true), not by keeping the low bit. +from pythonbpf import bpf, section, bpfglobal, compile +from ctypes import c_void_p, c_int64 + + +@bpf +@section("tracepoint/raw_syscalls/sys_enter") +def prog(ctx: c_void_p) -> c_int64: + t = True + n = True + n = 2 # bool = 2 is true in C; truncation would make it false + s = t + 1 # int + bool promotes the bool to int 1: 2, not 0 + return c_int64(t + n + s) # 1 + 1 + 2 = 4, not -1 + 0 + 0 + + +@bpf +@bpfglobal +def LICENSE() -> str: + return "GPL" + + +compile() diff --git a/tests/test_signedness_ir.py b/tests/test_signedness_ir.py index f44eeed..b38834e 100644 --- a/tests/test_signedness_ir.py +++ b/tests/test_signedness_ir.py @@ -50,6 +50,12 @@ CASES = { [r"\budiv i64 .*, 4294967294"], [r"\bsdiv 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": ( + [r"zext i1 .* to i(32|64)", r"icmp ne i64 .*, 0"], + [r"sext i1 ", r"trunc i64 .* to i1"], + ), # An enum constant is a C `int`, so `XDP_PASS - k` with k a c_uint32 is a # u32 operation: the result is cut to 32 bits and zero-extended. Ranked # as i64 it would be a signed 64-bit subtraction with no trunc at all.