Open
Description
When a map is marshaled where the value type is another map with custom MarshalJSON
, go-json panics:
type Map map[string]struct{}
type MapMap map[string]Map
func (m Map) MarshalJSON() ([]byte, error) {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
return json.Marshal(keys)
}
func TestMapType(t *testing.T) {
v := MapMap{
"test": Map{
"test": {},
},
}
b, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
assertEq(t, "unexpected result", `{"test": ["test"]}`, string(b))
}
Results in:
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x1 pc=0x9fa2a9]
goroutine 7 [running]:
testing.tRunner.func1.2({0xb7b320, 0xf20290})
/usr/lib/go/src/testing/testing.go:1734 +0x49e
testing.tRunner.func1()
/usr/lib/go/src/testing/testing.go:1737 +0x669
panic({0xb7b320?, 0xf20290?})
/usr/lib/go/src/runtime/panic.go:792 +0x136
github.com/goccy/go-json_test.Map.MarshalJSON(0x1)
/go-json/encode_test.go:2724 +0x49
github.com/goccy/go-json/internal/encoder.AppendMarshalJSON(0xc000119a00, 0xc0001159f0, {0xc000116400, 0x8, 0x400}, {0xbaaa40, 0x1})
Internally, the IsNilableTypeFlags
is set (because it's a map) and IndirectFlags
is set (because it's a value type in a map), causing vm.go:269 to try and dereference the map. However, since it's a map, this breaks and returns 1, causing the panic once MarshalJSON
is invoked.
Metadata
Metadata
Assignees
Labels
No labels