]> Cypherpunks repositories - gostls13.git/commit
runtime: add valgrind instrumentation
authorRoland Shoemaker <bracewell@google.com>
Sat, 22 Mar 2025 00:58:55 +0000 (00:58 +0000)
committerRoland Shoemaker <bracewell@google.com>
Wed, 21 May 2025 17:08:08 +0000 (10:08 -0700)
commit40b19b56a94c4d53a3c1d98275df44049b2f5917
treef508107b828ff065480c87b2aa2f41c1eceabcc2
parent2a5ac1a993efc463efdce7996efd356dabf03a25
runtime: add valgrind instrumentation

Add build tag gated Valgrind annotations to the runtime which let it
understand how the runtime manages memory. This allows for Go binaries
to be run under Valgrind without emitting spurious errors.

Instead of adding the Valgrind headers to the tree, and using cgo to
call the various Valgrind client request macros, we just add an assembly
function which emits the necessary instructions to trigger client
requests.

In particular we add instrumentation of the memory allocator, using a
two-level mempool structure (as described in the Valgrind manual [0]).
We also add annotations which allow Valgrind to track which memory we
use for stacks, which seems necessary to let it properly function.

We describe the memory model to Valgrind as follows: we treat heap
arenas as a "pool" created with VALGRIND_CREATE_MEMPOOL_EXT (so that we
can use VALGRIND_MEMPOOL_METAPOOL and VALGRIND_MEMPOOL_AUTO_FREE).
Within the pool we treat spans as "superblocks", annotated with
VALGRIND_MEMPOOL_ALLOC. We then allocate individual objects within spans
with VALGRIND_MALLOCLIKE_BLOCK.

It should be noted that running binaries under Valgrind can be _quite
slow_, and certain operations, such as running the GC, can be _very
slow_. It is recommended to run programs with GOGC=off. Additionally,
async preemption should be turned off, since it'll cause strange
behavior (GODEBUG=asyncpreemptoff=1).

Running Valgrind with --leak-check=yes will result in some errors
resulting from some things not being marked fully free'd. These likely
need more annotations to rectify, but for now it is recommended to run
with --leak-check=off.

Updates #73602

[0] https://valgrind.org/docs/manual/mc-manual.html#mc-manual.mempools

Change-Id: I71b26c47d7084de71ef1e03947ef6b1cc6d38301
Reviewed-on: https://go-review.googlesource.com/c/go/+/674077
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
15 files changed:
src/os/pidfd_linux.go
src/runtime/arena.go
src/runtime/malloc.go
src/runtime/mgcmark.go
src/runtime/mgcsweep.go
src/runtime/mheap.go
src/runtime/proc.go
src/runtime/runtime2.go
src/runtime/sizeof_test.go
src/runtime/stack.go
src/runtime/valgrind.go [new file with mode: 0644]
src/runtime/valgrind0.go [new file with mode: 0644]
src/runtime/valgrind_amd64.s [new file with mode: 0644]
src/runtime/valgrind_arm64.s [new file with mode: 0644]
src/syscall/exec_linux.go