[PATCH bpf-next v4 2/3] bpftool: Preserve unsigned enum values in data dumps
From: Hungyu Lin
Date: Fri Nov 06 2026 - 21:09:51 EST
btf_dumper_enum() loads ordinary enum data as signed and uses signed
numeric output. Unsigned values with the high bit set can therefore be
printed as negative numbers. Narrow unsigned values also fail to match
their enumerators: an eight-bit 0xff is loaded as -1, while its named
value is stored as 255.
btf_dumper_enum64() likewise uses signed numeric output for unmatched
values. For example, 0x8000000000000001 is printed as
-9223372036854775807 instead of 9223372036854775809.
Load ordinary enum data according to kflag and use btf_enum_value() for
name matching. Select the numeric writer according to kflag for both
enum kinds, casting the value to __s64 for signed output.
Fixes: ca7e6e45d108 ("bpftool: Print the enum's name instead of value")
Fixes: 58a53978fdf6 ("bpftool: Add btf enum64 support")
Suggested-by: Alexei Starovoitov <ast@xxxxxxxxxx>
Acked-by: Quentin Monnet <qmo@xxxxxxxxxx>
Signed-off-by: Hungyu Lin <dennylin0707@xxxxxxxxx>
---
Changes in v4:
- Keep the normalized value unsigned; cast explicitly for signed output.
- Remove the signed-width compatibility comparison and match-priority
logic, as requested by Andrii.
tools/bpf/bpftool/btf_dumper.c | 23 +++++++++++++++--------
1 file changed, 15 insertions(+), 8 deletions(-)
diff --git a/tools/bpf/bpftool/btf_dumper.c b/tools/bpf/bpftool/btf_dumper.c
index 3267163119dc..a7171622ce57 100644
--- a/tools/bpf/bpftool/btf_dumper.c
+++ b/tools/bpf/bpftool/btf_dumper.c
@@ -149,28 +149,29 @@ static int btf_dumper_enum(const struct btf_dumper *d,
const void *data)
{
const struct btf_enum *enums = btf_enum(t);
- __s64 value;
+ bool is_signed = btf_kflag(t);
+ __u64 value;
__u32 i;
switch (t->size) {
case 8:
- value = *(__s64 *)data;
+ value = *(__u64 *)data;
break;
case 4:
- value = *(__s32 *)data;
+ value = is_signed ? (__s64)*(__s32 *)data : *(__u32 *)data;
break;
case 2:
- value = *(__s16 *)data;
+ value = is_signed ? *(__s16 *)data : *(__u16 *)data;
break;
case 1:
- value = *(__s8 *)data;
+ value = is_signed ? *(__s8 *)data : *(__u8 *)data;
break;
default:
return -EINVAL;
}
for (i = 0; i < btf_vlen(t); i++) {
- if (value == enums[i].val) {
+ if (value == btf_enum_value(t, &enums[i])) {
jsonw_string(d->jw,
btf__name_by_offset(d->btf,
enums[i].name_off));
@@ -178,7 +179,10 @@ static int btf_dumper_enum(const struct btf_dumper *d,
}
}
- jsonw_int(d->jw, value);
+ if (is_signed)
+ jsonw_int(d->jw, (__s64)value);
+ else
+ jsonw_uint(d->jw, value);
return 0;
}
@@ -204,7 +208,10 @@ static int btf_dumper_enum64(const struct btf_dumper *d,
}
}
- jsonw_int(d->jw, value);
+ if (btf_kflag(t))
+ jsonw_int(d->jw, (__s64)value);
+ else
+ jsonw_uint(d->jw, value);
return 0;
}
--
2.43.0