Skip to content

Commit

Permalink
btf: fix writing out signed enums
Browse files Browse the repository at this point in the history
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 <lmb@isovalent.com>
  • Loading branch information
lmb committed Oct 10, 2023
1 parent 3a926eb commit 23be709
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
8 changes: 7 additions & 1 deletion btf/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(")")

Expand Down
13 changes: 12 additions & 1 deletion btf/format_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"go/format"
"math"
"strings"
"testing"
)
Expand All @@ -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",
Expand Down

0 comments on commit 23be709

Please sign in to comment.