Files
python-bpf/tests/passing_tests/signedness/map_value_narrow.py
Varun R Mallya c11a25c0ab Core: Access narrow map values at their own width
A lookup local was always an i64*, whatever the map's value type, so a
c_uint32 value was read with an 8-byte load (the verifier rejects an
access past value_size) and its spare `v_tmp` slot, typed i32, could not
take the i64 a rebind stored into it. The local now points at the
value's own width for an integer value (a struct value keeps the generic
pointer; field access casts it), and the generic pointer the lookup
helper returns is cast to it on assignment.

The sites that read the local by its pointer type follow:
- A comparison reads it as get_typed_operand does, at its width and
  with the map's declared sign, so `u == 3` on a c_uint32 value is a
  zext and an unsigned compare where needed (on c_uint64 values it was a
  signed compare before).
- print() takes the format from the declared value type and widens by
  its sign: a c_uint8 value was about to print as a string (%s on i8*),
  and integers narrower than 32 bits now print as %d, promoted as C
  varargs are.
- A rebind converts the i64 result to the slot's width.

holds_map_int_value names the predicate those sites share.
2026-09-25 11:22:25 +05:30

57 lines
1.3 KiB
Python

# Map values narrower than 64 bits are read and written at their own width:
# the verifier rejects an 8-byte access to a 4-byte value. Each value is then
# widened per its declared sign -- zext for c_uint32 and c_uint8, sext for
# c_int32 -- in arithmetic, comparisons and printing alike, and a c_uint8
# value prints as a number, not as a string.
from pythonbpf import bpf, map, section, bpfglobal, compile
from pythonbpf.maps import HashMap
from ctypes import c_void_p, c_int64, c_uint32, c_int32, c_uint8
@bpf
@map
def u32s() -> HashMap:
return HashMap(key=c_uint32, value=c_uint32, max_entries=4)
@bpf
@map
def i32s() -> HashMap:
return HashMap(key=c_uint32, value=c_int32, max_entries=4)
@bpf
@map
def u8s() -> HashMap:
return HashMap(key=c_uint32, value=c_uint8, max_entries=4)
@bpf
@section("tracepoint/raw_syscalls/sys_enter")
def prog(ctx: c_void_p) -> c_int64:
k = c_uint32(0)
u = u32s.lookup(k)
i = i32s.lookup(k)
b = u8s.lookup(k)
if u:
if u == 3:
print(f"u {u}")
u32s.update(k, u + 1)
if i:
n = i - 1
print(f"i {i} n {n}")
if b:
print(f"b {b}")
b = b + 2
return b
return c_int64(0)
@bpf
@bpfglobal
def LICENSE() -> str:
return "GPL"
compile()