From 8efc81471e0fe679c453aa0e8c03d752721733bc Mon Sep 17 00:00:00 2001 From: Rob Shakir Date: Mon, 11 Dec 2023 16:22:46 -0800 Subject: [PATCH] Avoid panic when calling Elem on a nil map member. (#941) * (M) ygot/struct_validation_map(_test)?.go - if a map was received that had a nil value in it, this caused a panic to occur since `(reflect.Value).Elem()` does not handle these cases cleanly. Add a check whether the value is nil before calling Elem. --- ygot/struct_validation_map.go | 4 ++++ ygot/struct_validation_map_test.go | 9 +++++++++ 2 files changed, 13 insertions(+) diff --git a/ygot/struct_validation_map.go b/ygot/struct_validation_map.go index 1b655b24..edcd821e 100644 --- a/ygot/struct_validation_map.go +++ b/ygot/struct_validation_map.go @@ -864,6 +864,10 @@ func copyMapField(dstField, srcField reflect.Value, accessPath string, opts ...M errs.Separator = "\n" for _, k := range srcField.MapKeys() { v := srcField.MapIndex(k) + if v.IsNil() { + errs.Add(fmt.Errorf("map key %v, got nil value", k.Interface())) + continue + } d := reflect.New(v.Elem().Type()) if _, ok := dstKeys[k.Interface()]; ok { d = dstField.MapIndex(k) diff --git a/ygot/struct_validation_map_test.go b/ygot/struct_validation_map_test.go index 8a3d653b..613db64d 100644 --- a/ygot/struct_validation_map_test.go +++ b/ygot/struct_validation_map_test.go @@ -1617,6 +1617,15 @@ func TestCopyStruct(t *testing.T) { wantDst: ©Test{ StructMap: map[copyMapKey]*copyTest{}, }, + }, { + name: "string map with explicit nil value", + inSrc: ©Test{ + StringMap: map[string]*copyTest{ + "fish": nil, + }, + }, + inDst: ©Test{}, + wantErr: true, }} for _, tt := range tests {