golang/go

cmd/compile: minimally align variables in memory when -d=checkptr is used

Open

#35,128 opened on Oct 24, 2019

View on GitHub
 (3 comments) (2 reactions) (0 assignees)Go (19,008 forks)batch import
NeedsInvestigationcompiler/runtimehelp wanted

Repository metrics

Stars
 (133,883 stars)
PR merge metrics
 (No merged PRs in 30d)

Description

-d=checkptr should report a warning for:

var x [4]byte
p := (*uint32)(unsafe.Pointer(&x[0]))

In general, this is unsafe because x only requires 1-byte alignment, but *uint32 requires 4-byte alignment.

Currently, this isn't reliably reported, because efficiently allocating variables often results in over alignment. But when -d=checkptr is in use, cmd/compile and the runtime could burn a few bytes of memory to intentionally minimally align things in the heap and on the stack (e.g., 1-byte-alignment variables always on an odd address).

Relatedly, when the runtime allocates a chunk of memory for a heap variable allocation, it could align the variable as close to the end of the allocation (rather than at the beginning), so that we can more easily detect pointer arithmetic overflows (at the expense of pointer arithmetic underflows, which seem less common).

These both would have helped catch issues that I've noticed in CLs to address errors reported by -d=checkptr.

(Prior art: I think OpenBSD's malloc used to prefer aligning allocations towards the end of an mmap'ed page so that buffer overflows were more likely to trigger a segmentation fault. Not sure if it still does that. I don't see it mentioned specifically in the man page.)

Contributor guide