Skip to content

Bug: marshaling of map of map with custom MarshalJSON panics #543

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
secDre4mer opened this issue Apr 4, 2025 · 0 comments · May be fixed by #544
Open

Bug: marshaling of map of map with custom MarshalJSON panics #543

secDre4mer opened this issue Apr 4, 2025 · 0 comments · May be fixed by #544

Comments

@secDre4mer
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant