golang/go

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

开放

#35,128 创建于 2019年10月24日

 (3 条评论) (2 个反应) (0 位负责人)Go (19,008 个派生)batch import
NeedsInvestigationcompiler/runtimehelp wanted

仓库指标

星标
 (133,883 个星标)
PR 合并指标
 (30 天内没有已合并 PR)

描述

-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.)

贡献者指南