From 23be7099d3a1299353728b9bab56af11336b8fc8 Mon Sep 17 00:00:00 2001 From: Lorenz Bauer Date: Tue, 3 Oct 2023 11:09:57 +0100 Subject: [PATCH] btf: fix writing out signed enums The formatter currently doesn't do sign conversion when writing out enum values. This means that negative signed enum values end up with large unsigned values. Fix this by doing correct sign conversion. Signed-off-by: Lorenz Bauer --- btf/format.go | 8 +++++++- btf/format_test.go | 13 ++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/btf/format.go b/btf/format.go index e85220259..acb489cd0 100644 --- a/btf/format.go +++ b/btf/format.go @@ -77,7 +77,13 @@ func (gf *GoFormatter) writeTypeDecl(name string, typ Type) error { gf.w.WriteString("; const ( ") for _, ev := range e.Values { id := gf.enumIdentifier(name, ev.Name) - fmt.Fprintf(&gf.w, "%s %s = %d; ", id, name, ev.Value) + var value any + if e.Signed { + value = int64(ev.Value) + } else { + value = ev.Value + } + fmt.Fprintf(&gf.w, "%s %s = %d; ", id, name, value) } gf.w.WriteString(")") diff --git a/btf/format_test.go b/btf/format_test.go index 7ada84d50..c26e023df 100644 --- a/btf/format_test.go +++ b/btf/format_test.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "go/format" + "math" "strings" "testing" ) @@ -22,7 +23,17 @@ func TestGoTypeDeclaration(t *testing.T) { {&Typedef{Name: "frob", Type: &Int{Size: 8}}, "type t uint64"}, {&Int{Size: 16}, "type t [16]byte /* uint128 */"}, {&Enum{Values: []EnumValue{{"FOO", 32}}, Size: 4}, "type t uint32; const ( tFOO t = 32; )"}, - {&Enum{Values: []EnumValue{{"BAR", 1}}, Size: 1, Signed: true}, "type t int8; const ( tBAR t = 1; )"}, + { + &Enum{ + Values: []EnumValue{ + {"MINUS_ONE", math.MaxUint64}, + {"MINUS_TWO", math.MaxUint64 - 1}, + }, + Size: 1, + Signed: true, + }, + "type t int8; const ( tMINUS_ONE t = -1; tMINUS_TWO t = -2; )", + }, { &Struct{ Name: "enum literals",