protoc-gen-go: oneof getters panic on typed-nil values.
What version of protobuf and what language are you using? Golang
google.golang.org/protobuf v1.26.0
$ protoc --version
libprotoc 3.17.3What did you do? Panic occurs when you set a typed nil on a oneof field
// test.proto
message Test {
oneof myOneof {
string str = 1;
}
}// main.go
var typedNil *pb.Test_myOneof
t := &pb.Test{MyOneof: typedNil}
fmt.Println(t.GetStr())What did you expect to see? Empty string
What did you see instead?
panic: runtime error: invalid memory address or nil pointer dereferencePossibly related: #478
Anything else we should know about your project / environment?
I tracked down the source of the panic. The generated getter for the oneof field does a nil check on the interface value, but not the Str value after casting it. Following code was generated with the above tool versions.
func (x *Test) GetStr() string {
if x, ok := x.GetMyOneof().(*Test_Str); ok {
return x.Str
}
return ""
}In the typed-nil case, the cast works and reports true, so the code attempts to access x.Str, but x is in fact nil. There should be an additional nil check on x.
I imagine this case is probably not intended to come about in practice, but it is certainly possible.
Source: golang/protobuf