runtime/coverage: use atomic access for counter reads

Read counters using atomic ops so as to avoid problems with the race
detector if a goroutine happens to still be executing at the end of a
test run when we're writing out counter data. In theory we could guard
the atomic use on the counter mode, but it's better just to do it in
all cases, leaves us with a simpler implementation.

Fixes #56006.

Change-Id: I81c2234b5a1c3b00cff6c77daf2c2315451b7f6c
Reviewed-on: https://go-review.googlesource.com/c/go/+/438256
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Bryan Mills <bcmills@google.com>
Reviewed-by: David Chase <drchase@google.com>
Run-TryBot: Than McIntosh <thanm@google.com>
This commit is contained in:
Than McIntosh 2022-10-03 18:40:59 -04:00
parent 8bd803fd4e
commit cddf792428
5 changed files with 95 additions and 15 deletions

View file

@ -8,10 +8,12 @@ import (
"fmt"
"internal/coverage"
"internal/goexperiment"
"internal/platform"
"internal/testenv"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
)
@ -402,3 +404,32 @@ func TestApisOnNocoverBinary(t *testing.T) {
t.Errorf("error output does not contain %q: %s", want, output)
}
}
func TestIssue56006EmitDataRaceCoverRunningGoroutine(t *testing.T) {
// This test requires "go test -race -cover", meaning that we need
// go build, go run, and "-race" support.
testenv.MustHaveGoRun(t)
if !platform.RaceDetectorSupported(runtime.GOOS, runtime.GOARCH) ||
!testenv.HasCGO() {
t.Skip("skipped due to lack of race detector support / CGO")
}
// This will run a program with -cover and -race where we have a
// goroutine still running (and updating counters) at the point where
// the test runtime is trying to write out counter data.
cmd := exec.Command(testenv.GoToolPath(t), "test", "-cover", "-race")
cmd.Dir = filepath.Join("testdata", "issue56006")
b, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("go test -cover -race failed: %v", err)
}
// Don't want to see any data races in output.
avoid := []string{"DATA RACE"}
for _, no := range avoid {
if strings.Contains(string(b), no) {
t.Logf("%s\n", string(b))
t.Fatalf("found %s in test output, not permitted", no)
}
}
}