golang/go

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

Ouverte

#35 128 ouverte le 24 oct. 2019

 (3 commentaires) (2 réactions) (0 personne assignée)Go (19 008 forks)batch import
NeedsInvestigationcompiler/runtimehelp wanted

Métriques du dépôt

Stars
 (133 883 étoiles)
Métriques de merge PR
 (Aucune PR mergée en 30 j)

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

Guide contributeur