binary
binary copied to clipboard
Self-referencing data structure causes stack overflow by endless recursion
Consider the following program:
import (
"fmt"
"github.com/kelindar/binary"
)
type Thing struct {
N int
P *Thing
}
func main() {
x := Thing{N: 1}
bin, _ := binary.Marshal(x)
fmt.Printf("asdf %d\n", len(bin))
}
Running this causes a fatal error:
runtime: sp=0xc020300350 stack=[0xc020300000, 0xc040300000]
fatal error: stack overflow
runtime stack:
runtime.throw(0x50aa19, 0xe)
/usr/lib/golang/src/runtime/panic.go:1117 +0x72
runtime.newstack()
/usr/lib/golang/src/runtime/stack.go:1069 +0x7ed
runtime.morestack()
/usr/lib/golang/src/runtime/asm_amd64.s:458 +0x8f
goroutine 1 [running]:
reflect.resolveTypeOff(0x4e84e0, 0x8840, 0x40ca1b)
/usr/lib/golang/src/runtime/runtime1.go:503 +0x4c fp=0xc020300360 sp=0xc020300358 pc=0x462e4c
reflect.(*rtype).typeOff(...)
/usr/lib/golang/src/reflect/type.go:690
reflect.(*rtype).ptrTo(0x4e84e0, 0x4db001)
/usr/lib/golang/src/reflect/type.go:1384 +0x36c fp=0xc020300408 sp=0xc020300360 pc=0x48110c
reflect.PtrTo(...)
/usr/lib/golang/src/reflect/type.go:1379
github.com/kelindar/binary.scanCustomCodec(0x531f60, 0x4e84e0, 0xc00775c0f0, 0x0, 0x0)
/home/user/go/pkg/mod/github.com/kelindar/[email protected]/scanner.go:247 +0x5b fp=0xc020300530 sp=0xc020300408 pc=0x4da6fb
github.com/kelindar/binary.scanType(0x531f60, 0x4e84e0, 0x4db00f, 0x1, 0x0, 0x0)
/home/user/go/pkg/mod/github.com/kelindar/[email protected]/scanner.go:56 +0x50 fp=0xc020300680 sp=0xc020300530 pc=0x4d8dd0
github.com/kelindar/binary.scanType(0x531f60, 0x4f5120, 0x4f5120, 0x0, 0x0, 0x4f5180)
/home/user/go/pkg/mod/github.com/kelindar/[email protected]/scanner.go:137 +0x991 fp=0xc0203007d0 sp=0xc020300680 pc=0x4d9711
github.com/kelindar/binary.scanType(0x531f60, 0x4e3d80, 0x4db013, 0x1, 0x0, 0x0)
/home/user/go/pkg/mod/github.com/kelindar/[email protected]/scanner.go:66 +0x43c fp=0xc020300920 sp=0xc0203007d0 pc=0x4d91bc
github.com/kelindar/binary.scanType(0x531f60, 0x4f5120, 0x4f5120, 0x0, 0x0, 0x4f5180)
(with many more similar lines).
Apparently the *Thing pointer in the struct causes the problem. This means that in its current state this library cannot be used to serialize e.g. linked lists.