Skip to content

Commit dc72a2f

Browse files
committed
cmd/compile: detect unsafe conversions from smaller to larger types
This CL extends the runtime instrumentation for (*T)(ptr) to also check that the first and last bytes of *(*T)(ptr) are part of the same heap object. Updates #22218. Updates #34959. Change-Id: I2c8063fe1b7fe6e6145e41c5654cb64dd1c9dd41 Reviewed-on: https://go-review.googlesource.com/c/go/+/201778 Run-TryBot: Matthew Dempsky <[email protected]> Reviewed-by: Keith Randall <[email protected]> Reviewed-by: Cuong Manh Le <[email protected]> TryBot-Result: Gobot Gobot <[email protected]>
1 parent 4edd78d commit dc72a2f

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

src/cmd/compile/internal/gc/walk.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -3910,7 +3910,7 @@ func isRuneCount(n *Node) bool {
39103910
}
39113911

39123912
func walkCheckPtrAlignment(n *Node, init *Nodes) *Node {
3913-
if n.Type.Elem().Alignment() == 1 {
3913+
if n.Type.Elem().Alignment() == 1 && n.Type.Elem().Size() == 1 {
39143914
return n
39153915
}
39163916

src/runtime/checkptr.go

+9-3
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,20 @@ package runtime
77
import "unsafe"
88

99
type ptrAlign struct {
10-
ptr unsafe.Pointer
11-
align uintptr
10+
ptr unsafe.Pointer
11+
elem *_type
1212
}
1313

1414
func checkptrAlignment(p unsafe.Pointer, elem *_type) {
15+
// Check that (*T)(p) is appropriately aligned.
1516
// TODO(mdempsky): What about fieldAlign?
1617
if uintptr(p)&(uintptr(elem.align)-1) != 0 {
17-
panic(ptrAlign{p, uintptr(elem.align)})
18+
panic(ptrAlign{p, elem})
19+
}
20+
21+
// Check that (*T)(p) doesn't straddle multiple heap objects.
22+
if elem.size != 1 && checkptrBase(p) != checkptrBase(add(p, elem.size-1)) {
23+
panic(ptrAlign{p, elem})
1824
}
1925
}
2026

0 commit comments

Comments
 (0)