runtime: improve invalid pointer error message

By default, the runtime panics if it detects a pointer to an
unallocated span. At this point, this usually catches bad uses of
unsafe or cgo in user code (though it could also catch runtime bugs).
Unfortunately, the rather cryptic error misleads users, offers users
little help with debugging their own problem, and offers the Go
developers little help with root-causing.

Improve the error message in various ways. First, the wording is
improved to make it clearer what condition was detected and to suggest
that this may be the result of incorrect use of unsafe or cgo. Second,
we add a dump of the object containing the bad pointer so that there's
at least some hope of figuring out why a bad pointer was stored in the
Go heap.

Change-Id: I57b91b12bc3cb04476399d7706679e096ce594b9
Reviewed-on: https://go-review.googlesource.com/14763
Reviewed-by: Rick Hudson <rlh@golang.org>
This commit is contained in:
Austin Clements 2015-09-18 11:55:31 -04:00
parent 7360638da0
commit b7c55ba496
3 changed files with 64 additions and 13 deletions

View file

@ -587,3 +587,40 @@ func main() {
fmt.Println("done")
}
`
func TestInvalidptrCrash(t *testing.T) {
output := executeTest(t, invalidptrCrashSource, nil)
// Check that the bad pointer was detected.
want1 := "found bad pointer in Go heap"
if !strings.Contains(output, want1) {
t.Fatalf("failed to detect bad pointer; output does not contain %q:\n%s", want1, output)
}
// Check that we dumped the object containing the bad pointer.
want2 := "*(object+0) = 0x12345678"
if !strings.Contains(output, want2) {
t.Fatalf("failed to dump source object; output does not contain %q:\n%s", want2, output)
}
}
const invalidptrCrashSource = `
package main
import (
"runtime"
"unsafe"
)
var x = new(struct {
magic uintptr
y *byte
})
func main() {
runtime.GC()
x.magic = 0x12345678
x.y = &make([]byte, 64*1024)[0]
weasel := uintptr(unsafe.Pointer(x.y))
x.y = nil
runtime.GC()
x.y = (*byte)(unsafe.Pointer(weasel))
runtime.GC()
println("failed to detect bad pointer")
}
`