]> Cypherpunks.ru repositories - gostls13.git/commitdiff
[dev.boringcrypto] all: merge master into dev.boringcrypto
authorFilippo Valsorda <filippo@golang.org>
Wed, 8 Apr 2020 21:39:57 +0000 (17:39 -0400)
committerFilippo Valsorda <filippo@golang.org>
Wed, 8 Apr 2020 21:48:41 +0000 (17:48 -0400)
Change-Id: I2dcec316fd08d91db4183fb9d3b9afde65cc248f

14 files changed:
1  2 
src/cmd/go/go_test.go
src/cmd/go/internal/load/pkg.go
src/cmd/link/internal/ld/lib.go
src/crypto/ecdsa/ecdsa.go
src/crypto/rsa/pkcs1v15.go
src/crypto/rsa/pkcs1v15_test.go
src/crypto/rsa/pss.go
src/crypto/rsa/rsa.go
src/crypto/tls/auth.go
src/crypto/tls/auth_test.go
src/crypto/tls/common.go
src/crypto/tls/handshake_client.go
src/crypto/tls/handshake_server.go
src/go/build/deps_test.go

diff --combined src/cmd/go/go_test.go
index 78b4cf196218abdc947c43a81c893d5ff62b86fe,d446e457b5a14e86d972576e91eb0ce500da345c..2ecacc5564083cf0880e6567e9dba372e2c4f7b3
@@@ -9,6 -9,7 +9,7 @@@ import 
        "context"
        "debug/elf"
        "debug/macho"
+       "debug/pe"
        "flag"
        "fmt"
        "go/format"
@@@ -198,6 -199,7 +199,7 @@@ func TestMain(m *testing.M) 
                        return strings.TrimSpace(string(out))
                }
                testGOROOT = goEnv("GOROOT")
+               os.Setenv("TESTGO_GOROOT", testGOROOT)
  
                // The whole GOROOT/pkg tree was installed using the GOHOSTOS/GOHOSTARCH
                // toolchain (installed in GOROOT/pkg/tool/GOHOSTOS_GOHOSTARCH).
@@@ -317,7 -319,6 +319,6 @@@ var mtimeTick time.Duration = 1 * time.
  type testgoData struct {
        t              *testing.T
        temps          []string
-       wd             string
        env            []string
        tempdir        string
        ran            bool
@@@ -367,9 -368,6 +368,6 @@@ func (tg *testgoData) parallel() 
        if tg.ran {
                tg.t.Fatal("internal testsuite error: call to parallel after run")
        }
-       if tg.wd != "" {
-               tg.t.Fatal("internal testsuite error: call to parallel after cd")
-       }
        for _, e := range tg.env {
                if strings.HasPrefix(e, "GOROOT=") || strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
                        val := e[strings.Index(e, "=")+1:]
@@@ -392,24 -390,6 +390,6 @@@ func (tg *testgoData) pwd() string 
        return wd
  }
  
- // cd changes the current directory to the named directory. Note that
- // using this means that the test must not be run in parallel with any
- // other tests.
- func (tg *testgoData) cd(dir string) {
-       tg.t.Helper()
-       if tg.inParallel {
-               tg.t.Fatal("internal testsuite error: changing directory when running in parallel")
-       }
-       if tg.wd == "" {
-               tg.wd = tg.pwd()
-       }
-       abs, err := filepath.Abs(dir)
-       tg.must(os.Chdir(dir))
-       if err == nil {
-               tg.setenv("PWD", abs)
-       }
- }
  // sleep sleeps for one tick, where a tick is a conservative estimate
  // of how long it takes for a file modification to get a different
  // mtime.
@@@ -638,7 -618,7 +618,7 @@@ func (tg *testgoData) grepStderrNot(mat
  }
  
  // grepBothNot looks for a regular expression in the test run's
- // standard output or stand error and fails, logging msg, if it is
+ // standard output or standard error and fails, logging msg, if it is
  // found.
  func (tg *testgoData) grepBothNot(match, msg string) {
        tg.t.Helper()
@@@ -680,12 -660,6 +660,6 @@@ func (tg *testgoData) creatingTemp(pat
        if filepath.IsAbs(path) && !strings.HasPrefix(path, tg.tempdir) {
                tg.t.Fatalf("internal testsuite error: creatingTemp(%q) with absolute path not in temporary directory", path)
        }
-       // If we have changed the working directory, make sure we have
-       // an absolute path, because we are going to change directory
-       // back before we remove the temporary.
-       if tg.wd != "" && !filepath.IsAbs(path) {
-               path = filepath.Join(tg.pwd(), path)
-       }
        tg.must(robustio.RemoveAll(path))
        tg.temps = append(tg.temps, path)
  }
@@@ -785,21 -759,6 +759,6 @@@ func (tg *testgoData) wantExecutable(pa
        }
  }
  
- // wantArchive fails if path is not an archive.
- func (tg *testgoData) wantArchive(path string) {
-       tg.t.Helper()
-       f, err := os.Open(path)
-       if err != nil {
-               tg.t.Fatal(err)
-       }
-       buf := make([]byte, 100)
-       io.ReadFull(f, buf)
-       f.Close()
-       if !bytes.HasPrefix(buf, []byte("!<arch>\n")) {
-               tg.t.Fatalf("file %s exists but is not an archive", path)
-       }
- }
  // isStale reports whether pkg is stale, and why
  func (tg *testgoData) isStale(pkg string) (bool, string) {
        tg.t.Helper()
@@@ -854,16 -813,6 +813,6 @@@ var testWork = flag.Bool("testwork", fa
  // cleanup cleans up a test that runs testgo.
  func (tg *testgoData) cleanup() {
        tg.t.Helper()
-       if tg.wd != "" {
-               wd, _ := os.Getwd()
-               tg.t.Logf("ended in %s", wd)
-               if err := os.Chdir(tg.wd); err != nil {
-                       // We are unlikely to be able to continue.
-                       fmt.Fprintln(os.Stderr, "could not restore working directory, crashing:", err)
-                       os.Exit(2)
-               }
-       }
        if *testWork {
                tg.t.Logf("TESTWORK=%s\n", tg.path("."))
                return
@@@ -910,6 -859,7 +859,7 @@@ func TestNewReleaseRebuildsStalePackage
  
        tg := testgo(t)
        defer tg.cleanup()
+       tg.parallel()
  
        // Copy the runtime packages into a temporary GOROOT
        // so that we can change files.
                                        return err
                                }
                                tg.tempFile(dest, string(data))
-                               if err := os.Chmod(tg.path(dest), info.Mode()); err != nil {
+                               if err := os.Chmod(tg.path(dest), info.Mode()|0200); err != nil {
                                        return err
                                }
                                return nil
        tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with old release")
  }
  
- func testLocalRun(tg *testgoData, exepath, local, match string) {
-       tg.t.Helper()
-       out, err := exec.Command(exepath).Output()
-       if err != nil {
-               tg.t.Fatalf("error running %v: %v", exepath, err)
-       }
-       if !regexp.MustCompile(match).Match(out) {
-               tg.t.Log(string(out))
-               tg.t.Errorf("testdata/%s/easy.go did not generate expected output", local)
-       }
- }
- func testLocalEasy(tg *testgoData, local string) {
-       tg.t.Helper()
-       exepath := "./easy" + exeSuffix
-       tg.creatingTemp(exepath)
-       tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easy.go"))
-       testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
- }
- func testLocalEasySub(tg *testgoData, local string) {
-       tg.t.Helper()
-       exepath := "./easysub" + exeSuffix
-       tg.creatingTemp(exepath)
-       tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easysub", "main.go"))
-       testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
- }
- func testLocalHard(tg *testgoData, local string) {
-       tg.t.Helper()
-       exepath := "./hard" + exeSuffix
-       tg.creatingTemp(exepath)
-       tg.run("build", "-o", exepath, filepath.Join("testdata", local, "hard.go"))
-       testLocalRun(tg, exepath, local, `(?m)^sub\.Hello`)
- }
- func testLocalInstall(tg *testgoData, local string) {
-       tg.t.Helper()
-       tg.runFail("install", filepath.Join("testdata", local, "easy.go"))
- }
- func TestLocalImportsEasy(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       testLocalEasy(tg, "local")
- }
- func TestLocalImportsEasySub(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       testLocalEasySub(tg, "local")
- }
- func TestLocalImportsHard(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       testLocalHard(tg, "local")
- }
- func TestLocalImportsGoInstallShouldFail(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       testLocalInstall(tg, "local")
- }
- const badDirName = `#$%:, &()*;<=>?\^{}`
- func copyBad(tg *testgoData) {
-       tg.t.Helper()
-       if runtime.GOOS == "windows" {
-               tg.t.Skipf("skipping test because %q is an invalid directory name", badDirName)
-       }
-       tg.must(filepath.Walk("testdata/local",
-               func(path string, info os.FileInfo, err error) error {
-                       if err != nil {
-                               return err
-                       }
-                       if info.IsDir() {
-                               return nil
-                       }
-                       var data []byte
-                       data, err = ioutil.ReadFile(path)
-                       if err != nil {
-                               return err
-                       }
-                       newpath := strings.Replace(path, "local", badDirName, 1)
-                       tg.tempFile(newpath, string(data))
-                       return nil
-               }))
-       tg.cd(tg.path("."))
- }
- func TestBadImportsEasy(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       // TODO: tg.parallel()
-       copyBad(tg)
-       testLocalEasy(tg, badDirName)
- }
- func TestBadImportsEasySub(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       copyBad(tg)
-       testLocalEasySub(tg, badDirName)
- }
- func TestBadImportsHard(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       copyBad(tg)
-       testLocalHard(tg, badDirName)
- }
- func TestBadImportsGoInstallShouldFail(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       copyBad(tg)
-       testLocalInstall(tg, badDirName)
- }
- func TestInternalPackagesInGOROOTAreRespected(t *testing.T) {
-       skipIfGccgo(t, "gccgo does not have GOROOT")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.runFail("build", "-v", "./testdata/testinternal")
-       tg.grepBoth(`testinternal(\/|\\)p\.go\:3\:8\: use of internal package net/http/internal not allowed`, "wrong error message for testdata/testinternal")
- }
- func TestInternalPackagesOutsideGOROOTAreRespected(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.runFail("build", "-v", "./testdata/testinternal2")
-       tg.grepBoth(`testinternal2(\/|\\)p\.go\:3\:8\: use of internal package .*internal/w not allowed`, "wrote error message for testdata/testinternal2")
- }
- func TestRunInternal(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       dir := filepath.Join(tg.pwd(), "testdata")
-       tg.setenv("GOPATH", dir)
-       tg.run("run", filepath.Join(dir, "src/run/good.go"))
-       tg.runFail("run", filepath.Join(dir, "src/run/bad.go"))
-       tg.grepStderr(`testdata(\/|\\)src(\/|\\)run(\/|\\)bad\.go\:3\:8\: use of internal package run/subdir/internal/private not allowed`, "unexpected error for run/bad.go")
- }
- func TestRunPkg(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       dir := filepath.Join(tg.pwd(), "testdata")
-       tg.setenv("GOPATH", dir)
-       tg.run("run", "hello")
-       tg.grepStderr("hello, world", "did not find hello, world")
-       tg.cd(filepath.Join(dir, "src/hello"))
-       tg.run("run", ".")
-       tg.grepStderr("hello, world", "did not find hello, world")
- }
- func testMove(t *testing.T, vcs, url, base, config string) {
-       testenv.MustHaveExternalNetwork(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.tempDir("src")
-       tg.must(os.Mkdir(tg.path(".hg"), 0700))
-       tg.must(ioutil.WriteFile(filepath.Join(tg.path(".hg"), "hgrc"), nil, 0600))
-       tg.setenv("GOPATH", tg.path("."))
-       tg.run("get", "-d", url)
-       tg.run("get", "-d", "-u", url)
-       switch vcs {
-       case "svn":
-               // SVN doesn't believe in text files so we can't just edit the config.
-               // Check out a different repo into the wrong place.
-               tg.must(robustio.RemoveAll(tg.path("src/code.google.com/p/rsc-svn")))
-               tg.run("get", "-d", "-u", "code.google.com/p/rsc-svn2/trunk")
-               tg.must(os.Rename(tg.path("src/code.google.com/p/rsc-svn2"), tg.path("src/code.google.com/p/rsc-svn")))
-       default:
-               path := tg.path(filepath.Join("src", config))
-               data, err := ioutil.ReadFile(path)
-               tg.must(err)
-               data = bytes.ReplaceAll(data, []byte(base), []byte(base+"XXX"))
-               tg.must(ioutil.WriteFile(path, data, 0644))
-       }
-       if vcs == "git" {
-               // git will ask for a username and password when we
-               // run go get -d -f -u. An empty username and
-               // password will work. Prevent asking by setting
-               // GIT_ASKPASS.
-               tg.creatingTemp("sink" + exeSuffix)
-               tg.tempFile("src/sink/sink.go", `package main; func main() {}`)
-               tg.run("build", "-o", "sink"+exeSuffix, "sink")
-               tg.setenv("GIT_ASKPASS", filepath.Join(tg.pwd(), "sink"+exeSuffix))
-       }
-       tg.runFail("get", "-d", "-u", url)
-       tg.grepStderr("is a custom import path for", "go get -d -u "+url+" failed for wrong reason")
-       tg.runFail("get", "-d", "-f", "-u", url)
-       tg.grepStderr("validating server certificate|[nN]ot [fF]ound", "go get -d -f -u "+url+" failed for wrong reason")
- }
- func TestInternalPackageErrorsAreHandled(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("list", "./testdata/testinternal3")
- }
- func TestInternalCache(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/testinternal4"))
-       tg.runFail("build", "p")
-       tg.grepStderr("internal", "did not fail to build p")
- }
- func TestMoveGit(t *testing.T) {
-       testenv.MustHaveExecPath(t, "git")
-       testMove(t, "git", "rsc.io/pdf", "pdf", "rsc.io/pdf/.git/config")
- }
- func TestMoveHG(t *testing.T) {
-       testenv.MustHaveExecPath(t, "hg")
-       testMove(t, "hg", "vcs-test.golang.org/go/custom-hg-hello", "custom-hg-hello", "vcs-test.golang.org/go/custom-hg-hello/.hg/hgrc")
- }
- // TODO(rsc): Set up a test case on SourceForge (?) for svn.
- // func testMoveSVN(t *testing.T) {
- //    testMove(t, "svn", "code.google.com/p/rsc-svn/trunk", "-", "-")
- // }
- func TestImportCommandMatch(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
-       tg.run("build", "./testdata/importcom/works.go")
- }
- func TestImportCommentMismatch(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
-       tg.runFail("build", "./testdata/importcom/wrongplace.go")
-       tg.grepStderr(`wrongplace expects import "my/x"`, "go build did not mention incorrect import")
- }
- func TestImportCommentSyntaxError(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
-       tg.runFail("build", "./testdata/importcom/bad.go")
-       tg.grepStderr("cannot parse import comment", "go build did not mention syntax error")
- }
- func TestImportCommentConflict(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
-       tg.runFail("build", "./testdata/importcom/conflict.go")
-       tg.grepStderr("found import comments", "go build did not mention comment conflict")
- }
- func TestImportCycle(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcycle"))
-       tg.runFail("build", "selfimport")
-       count := tg.grepCountBoth("import cycle not allowed")
-       if count == 0 {
-               t.Fatal("go build did not mention cyclical import")
-       }
-       if count > 1 {
-               t.Fatal("go build mentioned import cycle more than once")
-       }
-       // Don't hang forever.
-       tg.run("list", "-e", "-json", "selfimport")
- }
  // cmd/go: custom import path checking should not apply to Go packages without import comment.
  func TestIssue10952(t *testing.T) {
        testenv.MustHaveExternalNetwork(t)
@@@ -1375,6 -1045,7 +1045,7 @@@ func TestGetGitDefaultBranch(t *testing
  func TestAccidentalGitCheckout(t *testing.T) {
        testenv.MustHaveExternalNetwork(t)
        testenv.MustHaveExecPath(t, "git")
+       testenv.MustHaveExecPath(t, "svn")
  
        tg := testgo(t)
        defer tg.cleanup()
        }
  }
  
- func TestErrorMessageForSyntaxErrorInTestGoFileSaysFAIL(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.runFail("test", "syntaxerror")
-       tg.grepStderr("x_test.go:", "did not diagnose error")
-       tg.grepStdout("FAIL", "go test did not say FAIL")
- }
- func TestWildcardsDoNotLookInUselessDirectories(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.runFail("list", "...")
-       tg.grepBoth("badpkg", "go list ... failure does not mention badpkg")
-       tg.run("list", "m...")
- }
- func TestRelativeImportsGoTest(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("test", "./testdata/testimport")
- }
- func TestRelativeImportsGoTestDashI(t *testing.T) {
+ func TestPackageMainTestCompilerFlags(t *testing.T) {
        tg := testgo(t)
        defer tg.cleanup()
-       // don't let test -i overwrite runtime
-       tg.wantNotStale("runtime", "", "must be non-stale before test -i")
-       tg.run("test", "-i", "./testdata/testimport")
+       tg.parallel()
+       tg.makeTempdir()
+       tg.setenv("GOPATH", tg.path("."))
+       tg.tempFile("src/p1/p1.go", "package main\n")
+       tg.tempFile("src/p1/p1_test.go", "package main\nimport \"testing\"\nfunc Test(t *testing.T){}\n")
+       tg.run("test", "-c", "-n", "p1")
+       tg.grepBothNot(`([\\/]compile|gccgo).* (-p main|-fgo-pkgpath=main).*p1\.go`, "should not have run compile -p main p1.go")
+       tg.grepStderr(`([\\/]compile|gccgo).* (-p p1|-fgo-pkgpath=p1).*p1\.go`, "should have run compile -p p1 p1.go")
  }
  
- func TestRelativeImportsInCommandLinePackage(t *testing.T) {
+ // Issue 4104.
+ func TestGoTestWithPackageListedMultipleTimes(t *testing.T) {
+       tooSlow(t)
        tg := testgo(t)
        defer tg.cleanup()
-       // TODO: tg.parallel()
-       files, err := filepath.Glob("./testdata/testimport/*.go")
-       tg.must(err)
-       tg.run(append([]string{"test"}, files...)...)
+       tg.parallel()
+       tg.run("test", "errors", "errors", "errors", "errors", "errors")
+       if strings.Contains(strings.TrimSpace(tg.getStdout()), "\n") {
+               t.Error("go test errors errors errors errors errors tested the same package multiple times")
+       }
  }
  
- func TestVersionControlErrorMessageIncludesCorrectDirectory(t *testing.T) {
+ func TestGoListHasAConsistentOrder(t *testing.T) {
+       tooSlow(t)
        tg := testgo(t)
        defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/shadow/root1"))
-       tg.runFail("get", "-u", "foo")
-       // TODO(iant): We should not have to use strconv.Quote here.
-       // The code in vcs.go should be changed so that it is not required.
-       quoted := strconv.Quote(filepath.Join("testdata", "shadow", "root1", "src", "foo"))
-       quoted = quoted[1 : len(quoted)-1]
-       tg.grepStderr(regexp.QuoteMeta(quoted), "go get -u error does not mention shadow/root1/src/foo")
+       tg.parallel()
+       tg.run("list", "std")
+       first := tg.getStdout()
+       tg.run("list", "std")
+       if first != tg.getStdout() {
+               t.Error("go list std ordering is inconsistent")
+       }
  }
  
- func TestInstallFailsWithNoBuildableFiles(t *testing.T) {
+ func TestGoListStdDoesNotIncludeCommands(t *testing.T) {
+       tooSlow(t)
        tg := testgo(t)
        defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.setenv("CGO_ENABLED", "0")
-       tg.runFail("install", "cgotest")
-       tg.grepStderr("build constraints exclude all Go files", "go install cgotest did not report 'build constraints exclude all Go files'")
+       tg.parallel()
+       tg.run("list", "std")
+       tg.grepStdoutNot("cmd/", "go list std shows commands")
  }
  
- // Issue 21895
- func TestMSanAndRaceRequireCgo(t *testing.T) {
-       if !canMSan && !canRace {
-               t.Skip("skipping because both msan and the race detector are not supported")
-       }
+ func TestGoListCmdOnlyShowsCommands(t *testing.T) {
+       skipIfGccgo(t, "gccgo does not have GOROOT")
+       tooSlow(t)
        tg := testgo(t)
        defer tg.cleanup()
-       tg.tempFile("triv.go", `package main; func main() {}`)
-       tg.setenv("CGO_ENABLED", "0")
-       if canRace {
-               tg.runFail("install", "-race", "triv.go")
-               tg.grepStderr("-race requires cgo", "did not correctly report that -race requires cgo")
-               tg.grepStderrNot("-msan", "reported that -msan instead of -race requires cgo")
-       }
-       if canMSan {
-               tg.runFail("install", "-msan", "triv.go")
-               tg.grepStderr("-msan requires cgo", "did not correctly report that -msan requires cgo")
-               tg.grepStderrNot("-race", "reported that -race instead of -msan requires cgo")
+       tg.parallel()
+       tg.run("list", "cmd")
+       out := strings.TrimSpace(tg.getStdout())
+       for _, line := range strings.Split(out, "\n") {
+               if !strings.Contains(line, "cmd/") {
+                       t.Error("go list cmd shows non-commands")
+                       break
+               }
        }
  }
  
- func TestRelativeGOBINFail(t *testing.T) {
+ func TestGoListDeps(t *testing.T) {
        tg := testgo(t)
        defer tg.cleanup()
-       tg.tempFile("triv.go", `package main; func main() {}`)
-       tg.setenv("GOBIN", ".")
-       tg.cd(tg.path("."))
-       tg.runFail("install")
-       tg.grepStderr("cannot install, GOBIN must be an absolute path", "go install must fail if $GOBIN is a relative path")
- }
+       tg.parallel()
+       tg.tempDir("src/p1/p2/p3/p4")
+       tg.setenv("GOPATH", tg.path("."))
+       tg.tempFile("src/p1/p.go", "package p1\nimport _ \"p1/p2\"\n")
+       tg.tempFile("src/p1/p2/p.go", "package p2\nimport _ \"p1/p2/p3\"\n")
+       tg.tempFile("src/p1/p2/p3/p.go", "package p3\nimport _ \"p1/p2/p3/p4\"\n")
+       tg.tempFile("src/p1/p2/p3/p4/p.go", "package p4\n")
+       tg.run("list", "-f", "{{.Deps}}", "p1")
+       tg.grepStdout("p1/p2/p3/p4", "Deps(p1) does not mention p4")
  
- // Test that without $GOBIN set, binaries get installed
- // into the GOPATH bin directory.
- func TestInstallIntoGOPATH(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("install", "go-cmd-test")
-       tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
- }
+       tg.run("list", "-deps", "p1")
+       tg.grepStdout("p1/p2/p3/p4", "-deps p1 does not mention p4")
  
- // Issue 12407
- func TestBuildOutputToDevNull(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       fi1, err1 := os.Lstat(os.DevNull)
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("build", "-o", os.DevNull, "go-cmd-test")
-       fi2, err2 := os.Lstat(os.DevNull)
-       if err1 == nil {
-               if err2 != nil {
-                       t.Errorf("second stat of /dev/null failed: %v", err2)
-               } else if !os.SameFile(fi1, fi2) {
-                       t.Errorf("/dev/null changed: now %v was %v", fi1, fi2)
+       if runtime.Compiler != "gccgo" {
+               // Check the list is in dependency order.
+               tg.run("list", "-deps", "math")
+               want := "internal/cpu\nunsafe\nmath/bits\nmath\n"
+               out := tg.stdout.String()
+               if !strings.Contains(out, "internal/cpu") {
+                       // Some systems don't use internal/cpu.
+                       want = "unsafe\nmath/bits\nmath\n"
+               }
+               if tg.stdout.String() != want {
+                       t.Fatalf("list -deps math: wrong order\nhave %q\nwant %q", tg.stdout.String(), want)
                }
        }
  }
  
- // Issue 28549.
- func TestTestOutputToDevNull(t *testing.T) {
+ func TestGoListTest(t *testing.T) {
+       skipIfGccgo(t, "gccgo does not have standard packages")
        tg := testgo(t)
        defer tg.cleanup()
-       fi1, err1 := os.Lstat(os.DevNull)
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("."))
-       tg.tempFile("src/p/p.go", "package p\n")
-       tg.tempFile("src/p/p_test.go", "package p\nimport \"testing\"\nfunc TestX(t *testing.T) {}\n")
-       tg.run("test", "-o", os.DevNull, "-c", "p")
-       tg.mustNotExist("p.test")
-       fi2, err2 := os.Lstat(os.DevNull)
-       if err1 == nil {
-               if err2 != nil {
-                       t.Errorf("second stat of /dev/null failed: %v", err2)
-               } else if !os.SameFile(fi1, fi2) {
-                       t.Errorf("/dev/null changed: now %v was %v", fi1, fi2)
-               }
-       }
- }
- func TestPackageMainTestImportsArchiveNotBinary(t *testing.T) {
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       gobin := filepath.Join(tg.pwd(), "testdata", "bin")
-       tg.creatingTemp(gobin)
-       tg.setenv("GOBIN", gobin)
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.must(os.Chtimes("./testdata/src/main_test/m.go", time.Now(), time.Now()))
-       tg.sleep()
-       tg.run("test", "main_test")
-       tg.run("install", "main_test")
-       tg.wantNotStale("main_test", "", "after go install, main listed as stale")
-       tg.run("test", "main_test")
- }
- func TestPackageMainTestCompilerFlags(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("."))
-       tg.tempFile("src/p1/p1.go", "package main\n")
-       tg.tempFile("src/p1/p1_test.go", "package main\nimport \"testing\"\nfunc Test(t *testing.T){}\n")
-       tg.run("test", "-c", "-n", "p1")
-       tg.grepBothNot(`([\\/]compile|gccgo).* (-p main|-fgo-pkgpath=main).*p1\.go`, "should not have run compile -p main p1.go")
-       tg.grepStderr(`([\\/]compile|gccgo).* (-p p1|-fgo-pkgpath=p1).*p1\.go`, "should have run compile -p p1 p1.go")
- }
- // Issue 12690
- func TestPackageNotStaleWithTrailingSlash(t *testing.T) {
-       skipIfGccgo(t, "gccgo does not have GOROOT")
-       tg := testgo(t)
-       defer tg.cleanup()
-       // Make sure the packages below are not stale.
-       tg.wantNotStale("runtime", "", "must be non-stale before test runs")
-       tg.wantNotStale("os", "", "must be non-stale before test runs")
-       tg.wantNotStale("io", "", "must be non-stale before test runs")
-       goroot := runtime.GOROOT()
-       tg.setenv("GOROOT", goroot+"/")
-       tg.wantNotStale("runtime", "", "with trailing slash in GOROOT, runtime listed as stale")
-       tg.wantNotStale("os", "", "with trailing slash in GOROOT, os listed as stale")
-       tg.wantNotStale("io", "", "with trailing slash in GOROOT, io listed as stale")
- }
- // With $GOBIN set, binaries get installed to $GOBIN.
- func TestInstallIntoGOBIN(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
-       tg.creatingTemp(gobin)
-       tg.setenv("GOBIN", gobin)
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("install", "go-cmd-test")
-       tg.wantExecutable("testdata/bin1/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin1/go-cmd-test")
- }
- // Issue 11065
- func TestInstallToCurrentDirectoryCreatesExecutable(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       pkg := filepath.Join(tg.pwd(), "testdata", "src", "go-cmd-test")
-       tg.creatingTemp(filepath.Join(pkg, "go-cmd-test"+exeSuffix))
-       tg.setenv("GOBIN", pkg)
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.cd(pkg)
-       tg.run("install")
-       tg.wantExecutable("go-cmd-test"+exeSuffix, "go install did not write to current directory")
- }
- // Without $GOBIN set, installing a program outside $GOPATH should fail
- // (there is nowhere to install it).
- func TestInstallWithoutDestinationFails(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.runFail("install", "testdata/src/go-cmd-test/helloworld.go")
-       tg.grepStderr("no install location for .go files listed on command line", "wrong error")
- }
- // With $GOBIN set, should install there.
- func TestInstallToGOBINCommandLinePackage(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
-       tg.creatingTemp(gobin)
-       tg.setenv("GOBIN", gobin)
-       tg.run("install", "testdata/src/go-cmd-test/helloworld.go")
-       tg.wantExecutable("testdata/bin1/helloworld"+exeSuffix, "go install testdata/src/go-cmd-test/helloworld.go did not write testdata/bin1/helloworld")
- }
- func TestGoGetNonPkg(t *testing.T) {
-       testenv.MustHaveExternalNetwork(t)
-       testenv.MustHaveExecPath(t, "git")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.tempDir("gobin")
-       tg.setenv("GOPATH", tg.path("."))
-       tg.setenv("GOBIN", tg.path("gobin"))
-       tg.runFail("get", "-d", "golang.org/x/tools")
-       tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
-       tg.runFail("get", "-d", "-u", "golang.org/x/tools")
-       tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
-       tg.runFail("get", "-d", "golang.org/x/tools")
-       tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
- }
- func TestGoGetTestOnlyPkg(t *testing.T) {
-       testenv.MustHaveExternalNetwork(t)
-       testenv.MustHaveExecPath(t, "git")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.tempDir("gopath")
-       tg.setenv("GOPATH", tg.path("gopath"))
-       tg.run("get", "golang.org/x/tour/content...")
-       tg.run("get", "-t", "golang.org/x/tour/content...")
- }
- func TestInstalls(t *testing.T) {
-       if testing.Short() {
-               t.Skip("don't install into GOROOT in short mode")
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.tempDir("gobin")
-       tg.setenv("GOPATH", tg.path("."))
-       goroot := runtime.GOROOT()
-       tg.setenv("GOROOT", goroot)
-       // cmd/fix installs into tool
-       tg.run("env", "GOOS")
-       goos := strings.TrimSpace(tg.getStdout())
-       tg.setenv("GOOS", goos)
-       tg.run("env", "GOARCH")
-       goarch := strings.TrimSpace(tg.getStdout())
-       tg.setenv("GOARCH", goarch)
-       fixbin := filepath.Join(goroot, "pkg", "tool", goos+"_"+goarch, "fix") + exeSuffix
-       tg.must(robustio.RemoveAll(fixbin))
-       tg.run("install", "cmd/fix")
-       tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool")
-       tg.must(os.Remove(fixbin))
-       tg.setenv("GOBIN", tg.path("gobin"))
-       tg.run("install", "cmd/fix")
-       tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool with $GOBIN set")
-       tg.unsetenv("GOBIN")
-       // gopath program installs into GOBIN
-       tg.tempFile("src/progname/p.go", `package main; func main() {}`)
-       tg.setenv("GOBIN", tg.path("gobin"))
-       tg.run("install", "progname")
-       tg.unsetenv("GOBIN")
-       tg.wantExecutable(tg.path("gobin/progname")+exeSuffix, "did not install progname to $GOBIN/progname")
-       // gopath program installs into GOPATH/bin
-       tg.run("install", "progname")
-       tg.wantExecutable(tg.path("bin/progname")+exeSuffix, "did not install progname to $GOPATH/bin/progname")
- }
- func TestRejectRelativeDotPathInGOPATHCommandLinePackage(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", ".")
-       tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
-       tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
- }
- func TestRejectRelativePathsInGOPATH(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       sep := string(filepath.ListSeparator)
-       tg.setenv("GOPATH", sep+filepath.Join(tg.pwd(), "testdata")+sep+".")
-       tg.runFail("build", "go-cmd-test")
-       tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
- }
- func TestRejectRelativePathsInGOPATHCommandLinePackage(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", "testdata")
-       tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
-       tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
- }
- // Issue 21928.
- func TestRejectBlankPathsInGOPATH(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       sep := string(filepath.ListSeparator)
-       tg.setenv("GOPATH", " "+sep+filepath.Join(tg.pwd(), "testdata"))
-       tg.runFail("build", "go-cmd-test")
-       tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
- }
- // Issue 21928.
- func TestIgnoreEmptyPathsInGOPATH(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
-       sep := string(filepath.ListSeparator)
-       tg.setenv("GOPATH", ""+sep+filepath.Join(tg.pwd(), "testdata"))
-       tg.run("install", "go-cmd-test")
-       tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
- }
- // Issue 4104.
- func TestGoTestWithPackageListedMultipleTimes(t *testing.T) {
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.run("test", "errors", "errors", "errors", "errors", "errors")
-       if strings.Contains(strings.TrimSpace(tg.getStdout()), "\n") {
-               t.Error("go test errors errors errors errors errors tested the same package multiple times")
-       }
- }
- func TestGoListHasAConsistentOrder(t *testing.T) {
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.run("list", "std")
-       first := tg.getStdout()
-       tg.run("list", "std")
-       if first != tg.getStdout() {
-               t.Error("go list std ordering is inconsistent")
-       }
- }
- func TestGoListStdDoesNotIncludeCommands(t *testing.T) {
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.run("list", "std")
-       tg.grepStdoutNot("cmd/", "go list std shows commands")
- }
- func TestGoListCmdOnlyShowsCommands(t *testing.T) {
-       skipIfGccgo(t, "gccgo does not have GOROOT")
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.run("list", "cmd")
-       out := strings.TrimSpace(tg.getStdout())
-       for _, line := range strings.Split(out, "\n") {
-               if !strings.Contains(line, "cmd/") {
-                       t.Error("go list cmd shows non-commands")
-                       break
-               }
-       }
- }
- func TestGoListDedupsPackages(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       // TODO: tg.parallel()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("list", "xtestonly", "./testdata/src/xtestonly/...")
-       got := strings.TrimSpace(tg.getStdout())
-       const want = "xtestonly"
-       if got != want {
-               t.Errorf("got %q; want %q", got, want)
-       }
- }
- func TestGoListDeps(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.tempDir("src/p1/p2/p3/p4")
-       tg.setenv("GOPATH", tg.path("."))
-       tg.tempFile("src/p1/p.go", "package p1\nimport _ \"p1/p2\"\n")
-       tg.tempFile("src/p1/p2/p.go", "package p2\nimport _ \"p1/p2/p3\"\n")
-       tg.tempFile("src/p1/p2/p3/p.go", "package p3\nimport _ \"p1/p2/p3/p4\"\n")
-       tg.tempFile("src/p1/p2/p3/p4/p.go", "package p4\n")
-       tg.run("list", "-f", "{{.Deps}}", "p1")
-       tg.grepStdout("p1/p2/p3/p4", "Deps(p1) does not mention p4")
-       tg.run("list", "-deps", "p1")
-       tg.grepStdout("p1/p2/p3/p4", "-deps p1 does not mention p4")
-       if runtime.Compiler != "gccgo" {
-               // Check the list is in dependency order.
-               tg.run("list", "-deps", "math")
-               want := "internal/cpu\nunsafe\nmath/bits\nmath\n"
-               out := tg.stdout.String()
-               if !strings.Contains(out, "internal/cpu") {
-                       // Some systems don't use internal/cpu.
-                       want = "unsafe\nmath/bits\nmath\n"
-               }
-               if tg.stdout.String() != want {
-                       t.Fatalf("list -deps math: wrong order\nhave %q\nwant %q", tg.stdout.String(), want)
-               }
-       }
- }
- func TestGoListTest(t *testing.T) {
-       skipIfGccgo(t, "gccgo does not have standard packages")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
+       tg.parallel()
        tg.makeTempdir()
        tg.setenv("GOCACHE", tg.tempdir)
  
@@@ -2047,6 -1360,7 +1360,7 @@@ func TestDefaultGOPATHGet(t *testing.T
  
        tg := testgo(t)
        defer tg.cleanup()
+       tg.parallel()
        tg.setenv("GOPATH", "")
        tg.tempDir("home")
        tg.setenv(homeEnvName(), tg.path("home"))
  func TestDefaultGOPATHPrintedSearchList(t *testing.T) {
        tg := testgo(t)
        defer tg.cleanup()
+       tg.parallel()
        tg.setenv("GOPATH", "")
        tg.tempDir("home")
        tg.setenv(homeEnvName(), tg.path("home"))
        tg.grepStderr(regexp.QuoteMeta(tg.path("home/go/src/github.com/golang/example/hello"))+`.*from \$GOPATH`, "expected default GOPATH")
  }
  
- // Issue 4186. go get cannot be used to download packages to $GOROOT.
- // Test that without GOPATH set, go get should fail.
- func TestGoGetIntoGOROOT(t *testing.T) {
-       testenv.MustHaveExternalNetwork(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.tempDir("src")
-       // Fails because GOROOT=GOPATH
-       tg.setenv("GOPATH", tg.path("."))
-       tg.setenv("GOROOT", tg.path("."))
-       tg.runFail("get", "-d", "github.com/golang/example/hello")
-       tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
-       tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
-       // Fails because GOROOT=GOPATH after cleaning.
-       tg.setenv("GOPATH", tg.path(".")+"/")
-       tg.setenv("GOROOT", tg.path("."))
-       tg.runFail("get", "-d", "github.com/golang/example/hello")
-       tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
-       tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
-       tg.setenv("GOPATH", tg.path("."))
-       tg.setenv("GOROOT", tg.path(".")+"/")
-       tg.runFail("get", "-d", "github.com/golang/example/hello")
-       tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
-       tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
-       // Fails because GOROOT=$HOME/go so default GOPATH unset.
-       tg.tempDir("home/go")
-       tg.setenv(homeEnvName(), tg.path("home"))
-       tg.setenv("GOPATH", "")
-       tg.setenv("GOROOT", tg.path("home/go"))
-       tg.runFail("get", "-d", "github.com/golang/example/hello")
-       tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
-       tg.setenv(homeEnvName(), tg.path("home")+"/")
-       tg.setenv("GOPATH", "")
-       tg.setenv("GOROOT", tg.path("home/go"))
-       tg.runFail("get", "-d", "github.com/golang/example/hello")
-       tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
-       tg.setenv(homeEnvName(), tg.path("home"))
-       tg.setenv("GOPATH", "")
-       tg.setenv("GOROOT", tg.path("home/go")+"/")
-       tg.runFail("get", "-d", "github.com/golang/example/hello")
-       tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
- }
  func TestLdflagsArgumentsWithSpacesIssue3941(t *testing.T) {
        skipIfGccgo(t, "gccgo does not support -ldflags -X")
        tooSlow(t)
        tg.grepStderr("^hello world", `ldflags -X "main.extern=hello world"' failed`)
  }
  
- func TestGoTestCpuprofileLeavesBinaryBehind(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no standard packages")
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       // TODO: tg.parallel()
-       tg.makeTempdir()
-       tg.cd(tg.path("."))
-       tg.run("test", "-cpuprofile", "errors.prof", "errors")
-       tg.wantExecutable("errors.test"+exeSuffix, "go test -cpuprofile did not create errors.test")
- }
- func TestGoTestCpuprofileDashOControlsBinaryLocation(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no standard packages")
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       // TODO: tg.parallel()
-       tg.makeTempdir()
-       tg.cd(tg.path("."))
-       tg.run("test", "-cpuprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
-       tg.wantExecutable("myerrors.test"+exeSuffix, "go test -cpuprofile -o myerrors.test did not create myerrors.test")
- }
- func TestGoTestMutexprofileLeavesBinaryBehind(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no standard packages")
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       // TODO: tg.parallel()
-       tg.makeTempdir()
-       tg.cd(tg.path("."))
-       tg.run("test", "-mutexprofile", "errors.prof", "errors")
-       tg.wantExecutable("errors.test"+exeSuffix, "go test -mutexprofile did not create errors.test")
- }
- func TestGoTestMutexprofileDashOControlsBinaryLocation(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no standard packages")
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       // TODO: tg.parallel()
-       tg.makeTempdir()
-       tg.cd(tg.path("."))
-       tg.run("test", "-mutexprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
-       tg.wantExecutable("myerrors.test"+exeSuffix, "go test -mutexprofile -o myerrors.test did not create myerrors.test")
- }
- func TestGoBuildNonMain(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       // TODO: tg.parallel()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.runFail("build", "-buildmode=exe", "-o", "not_main"+exeSuffix, "not_main")
-       tg.grepStderr("-buildmode=exe requires exactly one main package", "go build with -o and -buildmode=exe should on a non-main package should throw an error")
-       tg.mustNotExist("not_main" + exeSuffix)
- }
  func TestGoTestDashCDashOControlsBinaryLocation(t *testing.T) {
        skipIfGccgo(t, "gccgo has no standard packages")
        tooSlow(t)
@@@ -2241,88 -1447,6 +1447,6 @@@ func TestGoTestDashIDashOWritesBinary(
        tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
  }
  
- // Issue 4568.
- func TestSymlinksList(t *testing.T) {
-       testenv.MustHaveSymlink(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       // TODO: tg.parallel()
-       tg.tempDir("src")
-       tg.must(os.Symlink(tg.path("."), tg.path("src/dir1")))
-       tg.tempFile("src/dir1/p.go", "package p")
-       tg.setenv("GOPATH", tg.path("."))
-       tg.cd(tg.path("src"))
-       tg.run("list", "-f", "{{.Root}}", "dir1")
-       if strings.TrimSpace(tg.getStdout()) != tg.path(".") {
-               t.Error("confused by symlinks")
-       }
- }
- // Issue 14054.
- func TestSymlinksVendor(t *testing.T) {
-       testenv.MustHaveSymlink(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       // TODO: tg.parallel()
-       tg.tempDir("gopath/src/dir1/vendor/v")
-       tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `v`\nfunc main(){}")
-       tg.tempFile("gopath/src/dir1/vendor/v/v.go", "package v")
-       tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
-       tg.setenv("GOPATH", tg.path("gopath"))
-       tg.cd(tg.path("symdir1"))
-       tg.run("list", "-f", "{{.Root}}", ".")
-       if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
-               t.Error("list confused by symlinks")
-       }
-       // All of these should succeed, not die in vendor-handling code.
-       tg.run("run", "p.go")
-       tg.run("build")
-       tg.run("install")
- }
- // Issue 15201.
- func TestSymlinksVendor15201(t *testing.T) {
-       testenv.MustHaveSymlink(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.tempDir("gopath/src/x/y/_vendor/src/x")
-       tg.must(os.Symlink("../../..", tg.path("gopath/src/x/y/_vendor/src/x/y")))
-       tg.tempFile("gopath/src/x/y/w/w.go", "package w\nimport \"x/y/z\"\n")
-       tg.must(os.Symlink("../_vendor/src", tg.path("gopath/src/x/y/w/vendor")))
-       tg.tempFile("gopath/src/x/y/z/z.go", "package z\n")
-       tg.setenv("GOPATH", tg.path("gopath/src/x/y/_vendor")+string(filepath.ListSeparator)+tg.path("gopath"))
-       tg.cd(tg.path("gopath/src"))
-       tg.run("list", "./...")
- }
- func TestSymlinksInternal(t *testing.T) {
-       testenv.MustHaveSymlink(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.tempDir("gopath/src/dir1/internal/v")
-       tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `dir1/internal/v`\nfunc main(){}")
-       tg.tempFile("gopath/src/dir1/internal/v/v.go", "package v")
-       tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
-       tg.setenv("GOPATH", tg.path("gopath"))
-       tg.cd(tg.path("symdir1"))
-       tg.run("list", "-f", "{{.Root}}", ".")
-       if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
-               t.Error("list confused by symlinks")
-       }
-       // All of these should succeed, not die in internal-handling code.
-       tg.run("run", "p.go")
-       tg.run("build")
-       tg.run("install")
- }
  // Issue 4515.
  func TestInstallWithTags(t *testing.T) {
        tooSlow(t)
@@@ -2422,528 -1546,77 +1546,77 @@@ func TestSymlinkWarning(t *testing.T) 
        tg.grepStderr("ignoring symlink", "list should have reported symlink")
  }
  
- // Issue 8181.
- func TestGoGetDashTIssue8181(t *testing.T) {
-       testenv.MustHaveExternalNetwork(t)
-       testenv.MustHaveExecPath(t, "git")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("."))
-       tg.run("get", "-v", "-t", "github.com/rsc/go-get-issue-8181/a", "github.com/rsc/go-get-issue-8181/b")
-       tg.run("list", "...")
-       tg.grepStdout("x/build/gerrit", "missing expected x/build/gerrit")
- }
- func TestIssue11307(t *testing.T) {
-       // go get -u was not working except in checkout directory
-       testenv.MustHaveExternalNetwork(t)
-       testenv.MustHaveExecPath(t, "git")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("."))
-       tg.run("get", "github.com/rsc/go-get-issue-11307")
-       tg.run("get", "-u", "github.com/rsc/go-get-issue-11307") // was failing
- }
- func TestShadowingLogic(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no standard packages")
-       tg := testgo(t)
-       defer tg.cleanup()
-       pwd := tg.pwd()
-       sep := string(filepath.ListSeparator)
-       tg.setenv("GOPATH", filepath.Join(pwd, "testdata", "shadow", "root1")+sep+filepath.Join(pwd, "testdata", "shadow", "root2"))
-       // The math in root1 is not "math" because the standard math is.
-       tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/math")
-       pwdForwardSlash := strings.ReplaceAll(pwd, string(os.PathSeparator), "/")
-       if !strings.HasPrefix(pwdForwardSlash, "/") {
-               pwdForwardSlash = "/" + pwdForwardSlash
-       }
-       // The output will have makeImportValid applies, but we only
-       // bother to deal with characters we might reasonably see.
-       for _, r := range " :" {
-               pwdForwardSlash = strings.ReplaceAll(pwdForwardSlash, string(r), "_")
-       }
-       want := "(_" + pwdForwardSlash + "/testdata/shadow/root1/src/math) (" + filepath.Join(runtime.GOROOT(), "src", "math") + ")"
-       if strings.TrimSpace(tg.getStdout()) != want {
-               t.Error("shadowed math is not shadowed; looking for", want)
-       }
-       // The foo in root1 is "foo".
-       tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/foo")
-       if strings.TrimSpace(tg.getStdout()) != "(foo) ()" {
-               t.Error("unshadowed foo is shadowed")
-       }
-       // The foo in root2 is not "foo" because the foo in root1 got there first.
-       tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root2/src/foo")
-       want = "(_" + pwdForwardSlash + "/testdata/shadow/root2/src/foo) (" + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo") + ")"
-       if strings.TrimSpace(tg.getStdout()) != want {
-               t.Error("shadowed foo is not shadowed; looking for", want)
-       }
-       // The error for go install should mention the conflicting directory.
-       tg.runFail("install", "./testdata/shadow/root2/src/foo")
-       want = "go install: no install location for " + filepath.Join(pwd, "testdata", "shadow", "root2", "src", "foo") + ": hidden by " + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo")
-       if strings.TrimSpace(tg.getStderr()) != want {
-               t.Error("wrong shadowed install error; looking for", want)
-       }
- }
- // Only succeeds if source order is preserved.
- func TestSourceFileNameOrderPreserved(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("test", "testdata/example1_test.go", "testdata/example2_test.go")
- }
- // Check that coverage analysis works at all.
- // Don't worry about the exact numbers but require not 0.0%.
- func checkCoverage(tg *testgoData, data string) {
-       tg.t.Helper()
-       if regexp.MustCompile(`[^0-9]0\.0%`).MatchString(data) {
-               tg.t.Error("some coverage results are 0.0%")
+ func TestCgoShowsFullPathNames(t *testing.T) {
+       if !canCgo {
+               t.Skip("skipping because cgo not enabled")
        }
- }
- func TestCoverageRuns(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no cover tool")
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("test", "-short", "-coverpkg=strings", "strings", "regexp")
-       data := tg.getStdout() + tg.getStderr()
-       tg.run("test", "-short", "-cover", "strings", "math", "regexp")
-       data += tg.getStdout() + tg.getStderr()
-       checkCoverage(tg, data)
- }
  
- func TestCoverageDotImport(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no cover tool")
-       tooSlow(t)
        tg := testgo(t)
        defer tg.cleanup()
        tg.parallel()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("test", "-coverpkg=coverdot1,coverdot2", "coverdot2")
-       data := tg.getStdout() + tg.getStderr()
-       checkCoverage(tg, data)
- }
- // Check that coverage analysis uses set mode.
- // Also check that coverage profiles merge correctly.
- func TestCoverageUsesSetMode(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no cover tool")
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.creatingTemp("testdata/cover.out")
-       tg.run("test", "-short", "-cover", "encoding/binary", "errors", "-coverprofile=testdata/cover.out")
-       data := tg.getStdout() + tg.getStderr()
-       if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
-               t.Error(err)
-       } else {
-               if !bytes.Contains(out, []byte("mode: set")) {
-                       t.Error("missing mode: set")
-               }
-               if !bytes.Contains(out, []byte("errors.go")) {
-                       t.Error("missing errors.go")
-               }
-               if !bytes.Contains(out, []byte("binary.go")) {
-                       t.Error("missing binary.go")
-               }
-               if bytes.Count(out, []byte("mode: set")) != 1 {
-                       t.Error("too many mode: set")
-               }
-       }
-       checkCoverage(tg, data)
+       tg.tempFile("src/x/y/dirname/foo.go", `
+               package foo
+               import "C"
+               func f() {`)
+       tg.setenv("GOPATH", tg.path("."))
+       tg.runFail("build", "x/y/dirname")
+       tg.grepBoth("x/y/dirname", "error did not use full path")
  }
  
- func TestCoverageUsesAtomicModeForRace(t *testing.T) {
+ func TestCgoHandlesWlORIGIN(t *testing.T) {
        tooSlow(t)
-       if !canRace {
-               t.Skip("skipping because race detector not supported")
-       }
-       skipIfGccgo(t, "gccgo has no cover tool")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.creatingTemp("testdata/cover.out")
-       tg.run("test", "-short", "-race", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out")
-       data := tg.getStdout() + tg.getStderr()
-       if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
-               t.Error(err)
-       } else {
-               if !bytes.Contains(out, []byte("mode: atomic")) {
-                       t.Error("missing mode: atomic")
-               }
+       if !canCgo {
+               t.Skip("skipping because cgo not enabled")
        }
-       checkCoverage(tg, data)
- }
- func TestCoverageSyncAtomicImport(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no cover tool")
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("test", "-short", "-cover", "-covermode=atomic", "-coverpkg=coverdep/p1", "coverdep")
- }
- func TestCoverageDepLoop(t *testing.T) {
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       // coverdep2/p1's xtest imports coverdep2/p2 which imports coverdep2/p1.
-       // Make sure that coverage on coverdep2/p2 recompiles coverdep2/p2.
-       tg.run("test", "-short", "-cover", "coverdep2/p1")
-       tg.grepStdout("coverage: 100.0% of statements", "expected 100.0% coverage")
- }
  
- func TestCoverageNoStatements(t *testing.T) {
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("test", "-cover", "./testdata/testcover/pkg4")
-       tg.grepStdout("[no statements]", "expected [no statements] for pkg4")
- }
- func TestCoverageImportMainLoop(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no cover tool")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.runFail("test", "importmain/test")
-       tg.grepStderr("not an importable package", "did not detect import main")
-       tg.runFail("test", "-cover", "importmain/test")
-       tg.grepStderr("not an importable package", "did not detect import main")
- }
- func TestCoveragePattern(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no cover tool")
-       tooSlow(t)
        tg := testgo(t)
        defer tg.cleanup()
        tg.parallel()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       // If coverpkg=sleepy... expands by package loading
-       // (as opposed to pattern matching on deps)
-       // then it will try to load sleepybad, which does not compile,
-       // and the test command will fail.
-       tg.run("test", "-coverprofile="+tg.path("cover.out"), "-coverpkg=sleepy...", "-run=^$", "sleepy1")
+       tg.tempFile("src/origin/origin.go", `package origin
+               // #cgo !darwin LDFLAGS: -Wl,-rpath,$ORIGIN
+               // void f(void) {}
+               import "C"
+               func f() { C.f() }`)
+       tg.setenv("GOPATH", tg.path("."))
+       tg.run("build", "origin")
  }
  
- func TestCoverageErrorLine(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no cover tool")
+ func TestCgoPkgConfig(t *testing.T) {
        tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.setenv("GOTMPDIR", tg.tempdir)
-       tg.runFail("test", "coverbad")
-       tg.grepStderr(`coverbad[\\/]p\.go:4`, "did not find coverbad/p.go:4")
-       if canCgo {
-               tg.grepStderr(`coverbad[\\/]p1\.go:6`, "did not find coverbad/p1.go:6")
-       }
-       tg.grepStderrNot(regexp.QuoteMeta(tg.tempdir), "found temporary directory in error")
-       stderr := tg.getStderr()
-       tg.runFail("test", "-cover", "coverbad")
-       stderr2 := tg.getStderr()
-       // It's OK that stderr2 drops the character position in the error,
-       // because of the //line directive (see golang.org/issue/22662).
-       stderr = strings.ReplaceAll(stderr, "p.go:4:2:", "p.go:4:")
-       if stderr != stderr2 {
-               t.Logf("test -cover changed error messages:\nbefore:\n%s\n\nafter:\n%s", stderr, stderr2)
-               t.Skip("golang.org/issue/22660")
-               t.FailNow()
+       if !canCgo {
+               t.Skip("skipping because cgo not enabled")
        }
- }
- func TestTestBuildFailureOutput(t *testing.T) {
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       // Doesn't build, -x output should not claim to run test.
-       tg.runFail("test", "-x", "coverbad")
-       tg.grepStderrNot(`[\\/]coverbad\.test( |$)`, "claimed to run test")
- }
- func TestCoverageFunc(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no cover tool")
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("test", "-outputdir="+tg.tempdir, "-coverprofile=cover.out", "coverasm")
-       tg.run("tool", "cover", "-func="+tg.path("cover.out"))
-       tg.grepStdout(`\tg\t*100.0%`, "did not find g 100% covered")
-       tg.grepStdoutNot(`\tf\t*[0-9]`, "reported coverage for assembly function f")
- }
- // Issue 24588.
- func TestCoverageDashC(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no cover tool")
-       tooSlow(t)
        tg := testgo(t)
        defer tg.cleanup()
        tg.parallel()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("test", "-c", "-o", tg.path("coverdep"), "-coverprofile="+tg.path("no/such/dir/cover.out"), "coverdep")
-       tg.wantExecutable(tg.path("coverdep"), "go -test -c -coverprofile did not create executable")
- }
  
- func TestPluginNonMain(t *testing.T) {
-       wd, err := os.Getwd()
-       if err != nil {
-               t.Fatal(err)
-       }
-       pkg := filepath.Join(wd, "testdata", "testdep", "p2")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.runFail("build", "-buildmode=plugin", pkg)
- }
- func TestTestEmpty(t *testing.T) {
-       if !canRace {
-               t.Skip("no race detector")
-       }
-       wd, _ := os.Getwd()
-       testdata := filepath.Join(wd, "testdata")
-       for _, dir := range []string{"pkg", "test", "xtest", "pkgtest", "pkgxtest", "pkgtestxtest", "testxtest"} {
-               t.Run(dir, func(t *testing.T) {
-                       tg := testgo(t)
-                       defer tg.cleanup()
-                       tg.setenv("GOPATH", testdata)
-                       tg.cd(filepath.Join(testdata, "src/empty/"+dir))
-                       tg.run("test", "-cover", "-coverpkg=.", "-race")
-               })
-               if testing.Short() {
-                       break
-               }
-       }
- }
- func TestNoGoError(t *testing.T) {
-       wd, _ := os.Getwd()
-       testdata := filepath.Join(wd, "testdata")
-       for _, dir := range []string{"empty/test", "empty/xtest", "empty/testxtest", "exclude", "exclude/ignore", "exclude/empty"} {
-               t.Run(dir, func(t *testing.T) {
-                       tg := testgo(t)
-                       defer tg.cleanup()
-                       tg.setenv("GOPATH", testdata)
-                       tg.cd(filepath.Join(testdata, "src"))
-                       tg.runFail("build", "./"+dir)
-                       var want string
-                       if strings.Contains(dir, "test") {
-                               want = "no non-test Go files in "
-                       } else if dir == "exclude" {
-                               want = "build constraints exclude all Go files in "
-                       } else {
-                               want = "no Go files in "
-                       }
-                       tg.grepStderr(want, "wrong reason for failure")
-               })
-       }
- }
- func TestTestRaceInstall(t *testing.T) {
-       if !canRace {
-               t.Skip("no race detector")
-       }
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.tempDir("pkg")
-       pkgdir := tg.path("pkg")
-       tg.run("install", "-race", "-pkgdir="+pkgdir, "std")
-       tg.run("test", "-race", "-pkgdir="+pkgdir, "-i", "-v", "empty/pkg")
-       if tg.getStderr() != "" {
-               t.Error("go test -i -race: rebuilds cached packages")
-       }
- }
- func TestBuildDryRunWithCgo(t *testing.T) {
-       if !canCgo {
-               t.Skip("skipping because cgo not enabled")
+       tg.run("env", "PKG_CONFIG")
+       pkgConfig := strings.TrimSpace(tg.getStdout())
+       testenv.MustHaveExecPath(t, pkgConfig)
+       if out, err := exec.Command(pkgConfig, "--atleast-pkgconfig-version", "0.24").CombinedOutput(); err != nil {
+               t.Skipf("%s --atleast-pkgconfig-version 0.24: %v\n%s", pkgConfig, err, out)
        }
  
-       tg := testgo(t)
-       defer tg.cleanup()
+       // OpenBSD's pkg-config is strict about whitespace and only
+       // supports backslash-escaped whitespace. It does not support
+       // quotes, which the normal freedesktop.org pkg-config does
+       // support. See https://man.openbsd.org/pkg-config.1
+       tg.tempFile("foo.pc", `
+ Name: foo
+ Description: The foo library
+ Version: 1.0.0
+ Cflags: -Dhello=10 -Dworld=+32 -DDEFINED_FROM_PKG_CONFIG=hello\ world
+ `)
        tg.tempFile("foo.go", `package main
  
  /*
- #include <limits.h>
+ #cgo pkg-config: foo
+ int value() {
+       return DEFINED_FROM_PKG_CONFIG;
+ }
  */
  import "C"
- func main() {
-         println(C.INT_MAX)
- }`)
-       tg.run("build", "-n", tg.path("foo.go"))
-       tg.grepStderrNot(`os.Stat .* no such file or directory`, "unexpected stat of archive file")
- }
- func TestCoverageWithCgo(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no cover tool")
-       tooSlow(t)
-       if !canCgo {
-               t.Skip("skipping because cgo not enabled")
-       }
-       for _, dir := range []string{"cgocover", "cgocover2", "cgocover3", "cgocover4"} {
-               t.Run(dir, func(t *testing.T) {
-                       tg := testgo(t)
-                       tg.parallel()
-                       defer tg.cleanup()
-                       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-                       tg.run("test", "-short", "-cover", dir)
-                       data := tg.getStdout() + tg.getStderr()
-                       checkCoverage(tg, data)
-               })
-       }
- }
- func TestCgoAsmError(t *testing.T) {
-       if !canCgo {
-               t.Skip("skipping because cgo not enabled")
-       }
-       tg := testgo(t)
-       tg.parallel()
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.runFail("build", "cgoasm")
-       tg.grepBoth("package using cgo has Go assembly file", "did not detect Go assembly file")
- }
- func TestCgoDependsOnSyscall(t *testing.T) {
-       if testing.Short() {
-               t.Skip("skipping test that removes $GOROOT/pkg/*_race in short mode")
-       }
-       if !canCgo {
-               t.Skip("skipping because cgo not enabled")
-       }
-       if !canRace {
-               t.Skip("skipping because race detector not supported")
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       files, err := filepath.Glob(filepath.Join(runtime.GOROOT(), "pkg", "*_race"))
-       tg.must(err)
-       for _, file := range files {
-               tg.check(robustio.RemoveAll(file))
-       }
-       tg.tempFile("src/foo/foo.go", `
-               package foo
-               //#include <stdio.h>
-               import "C"`)
-       tg.setenv("GOPATH", tg.path("."))
-       tg.run("build", "-race", "foo")
- }
- func TestCgoShowsFullPathNames(t *testing.T) {
-       if !canCgo {
-               t.Skip("skipping because cgo not enabled")
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.tempFile("src/x/y/dirname/foo.go", `
-               package foo
-               import "C"
-               func f() {`)
-       tg.setenv("GOPATH", tg.path("."))
-       tg.runFail("build", "x/y/dirname")
-       tg.grepBoth("x/y/dirname", "error did not use full path")
- }
- func TestCgoHandlesWlORIGIN(t *testing.T) {
-       tooSlow(t)
-       if !canCgo {
-               t.Skip("skipping because cgo not enabled")
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.tempFile("src/origin/origin.go", `package origin
-               // #cgo !darwin LDFLAGS: -Wl,-rpath,$ORIGIN
-               // void f(void) {}
-               import "C"
-               func f() { C.f() }`)
-       tg.setenv("GOPATH", tg.path("."))
-       tg.run("build", "origin")
- }
- func TestCgoPkgConfig(t *testing.T) {
-       tooSlow(t)
-       if !canCgo {
-               t.Skip("skipping because cgo not enabled")
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.run("env", "PKG_CONFIG")
-       pkgConfig := strings.TrimSpace(tg.getStdout())
-       testenv.MustHaveExecPath(t, pkgConfig)
-       if out, err := exec.Command(pkgConfig, "--atleast-pkgconfig-version", "0.24").CombinedOutput(); err != nil {
-               t.Skipf("%s --atleast-pkgconfig-version 0.24: %v\n%s", pkgConfig, err, out)
-       }
-       // OpenBSD's pkg-config is strict about whitespace and only
-       // supports backslash-escaped whitespace. It does not support
-       // quotes, which the normal freedesktop.org pkg-config does
-       // support. See https://man.openbsd.org/pkg-config.1
-       tg.tempFile("foo.pc", `
- Name: foo
- Description: The foo library
- Version: 1.0.0
- Cflags: -Dhello=10 -Dworld=+32 -DDEFINED_FROM_PKG_CONFIG=hello\ world
- `)
-       tg.tempFile("foo.go", `package main
- /*
- #cgo pkg-config: foo
- int value() {
-       return DEFINED_FROM_PKG_CONFIG;
- }
- */
- import "C"
- import "os"
+ import "os"
  
  func main() {
        if C.value() != 42 {
        tg.run("run", tg.path("foo.go"))
  }
  
- // "go test -c -test.bench=XXX errors" should not hang.
- // "go test -c" should also produce reproducible binaries.
- // "go test -c" should also appear to write a new binary every time,
- // even if it's really just updating the mtime on an existing up-to-date binary.
- func TestIssue6480(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no standard packages")
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       // TODO: tg.parallel()
-       tg.makeTempdir()
-       tg.cd(tg.path("."))
-       tg.run("test", "-c", "-test.bench=XXX", "errors")
-       tg.run("test", "-c", "-o", "errors2.test", "errors")
-       data1, err := ioutil.ReadFile("errors.test" + exeSuffix)
-       tg.must(err)
-       data2, err := ioutil.ReadFile("errors2.test") // no exeSuffix because -o above doesn't have it
-       tg.must(err)
-       if !bytes.Equal(data1, data2) {
-               t.Fatalf("go test -c errors produced different binaries when run twice")
-       }
-       start := time.Now()
-       tg.run("test", "-x", "-c", "-test.bench=XXX", "errors")
-       tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly relinked up-to-date test binary")
-       info, err := os.Stat("errors.test" + exeSuffix)
-       if err != nil {
-               t.Fatal(err)
-       }
-       start = truncateLike(start, info.ModTime())
-       if info.ModTime().Before(start) {
-               t.Fatalf("mtime of errors.test predates test -c command (%v < %v)", info.ModTime(), start)
-       }
-       start = time.Now()
-       tg.run("test", "-x", "-c", "-o", "errors2.test", "errors")
-       tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly relinked up-to-date test binary")
-       info, err = os.Stat("errors2.test")
-       if err != nil {
-               t.Fatal(err)
-       }
-       start = truncateLike(start, info.ModTime())
-       if info.ModTime().Before(start) {
-               t.Fatalf("mtime of errors2.test predates test -c command (%v < %v)", info.ModTime(), start)
-       }
- }
- // truncateLike returns the result of truncating t to the apparent precision of p.
- func truncateLike(t, p time.Time) time.Time {
-       nano := p.UnixNano()
-       d := 1 * time.Nanosecond
-       for nano%int64(d) == 0 && d < 1*time.Second {
-               d *= 10
-       }
-       for nano%int64(d) == 0 && d < 2*time.Second {
-               d *= 2
-       }
-       return t.Truncate(d)
- }
- // cmd/cgo: undefined reference when linking a C-library using gccgo
- func TestIssue7573(t *testing.T) {
-       if !canCgo {
-               t.Skip("skipping because cgo not enabled")
-       }
-       testenv.MustHaveExecPath(t, "gccgo")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.tempFile("src/cgoref/cgoref.go", `
- package main
- // #cgo LDFLAGS: -L alibpath -lalib
- // void f(void) {}
- import "C"
- func main() { C.f() }`)
-       tg.setenv("GOPATH", tg.path("."))
-       tg.run("build", "-n", "-compiler", "gccgo", "cgoref")
-       tg.grepStderr(`gccgo.*\-L [^ ]*alibpath \-lalib`, `no Go-inline "#cgo LDFLAGS:" ("-L alibpath -lalib") passed to gccgo linking stage`)
- }
  func TestListTemplateContextFunction(t *testing.T) {
        t.Parallel()
        for _, tt := range []struct {
                {"UseAllFiles", ""},
                {"Compiler", ""},
                {"BuildTags", ""},
-               {"ReleaseTags", ""},
-               {"InstallSuffix", ""},
-       } {
-               tt := tt
-               t.Run(tt.v, func(t *testing.T) {
-                       tg := testgo(t)
-                       tg.parallel()
-                       defer tg.cleanup()
-                       tmpl := "{{context." + tt.v + "}}"
-                       tg.run("list", "-f", tmpl)
-                       if tt.want == "" {
-                               return
-                       }
-                       if got := strings.TrimSpace(tg.getStdout()); got != tt.want {
-                               t.Errorf("go list -f %q: got %q; want %q", tmpl, got, tt.want)
-                       }
-               })
-       }
- }
- // cmd/go: "go test" should fail if package does not build
- func TestIssue7108(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.runFail("test", "notest")
- }
- // cmd/go: go test -a foo does not rebuild regexp.
- func TestIssue6844(t *testing.T) {
-       if testing.Short() {
-               t.Skip("don't rebuild the standard library in short mode")
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.creatingTemp("deps.test" + exeSuffix)
-       tg.run("test", "-x", "-a", "-c", "testdata/dep_test.go")
-       tg.grepStderr("regexp", "go test -x -a -c testdata/dep-test.go did not rebuild regexp")
- }
- func TestBuildDashIInstallsDependencies(t *testing.T) {
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.tempFile("src/x/y/foo/foo.go", `package foo
-               func F() {}`)
-       tg.tempFile("src/x/y/bar/bar.go", `package bar
-               import "x/y/foo"
-               func F() { foo.F() }`)
-       tg.setenv("GOPATH", tg.path("."))
-       // don't let build -i overwrite runtime
-       tg.wantNotStale("runtime", "", "must be non-stale before build -i")
-       checkbar := func(desc string) {
-               tg.run("build", "-v", "-i", "x/y/bar")
-               tg.grepBoth("x/y/foo", "first build -i "+desc+" did not build x/y/foo")
-               tg.run("build", "-v", "-i", "x/y/bar")
-               tg.grepBothNot("x/y/foo", "second build -i "+desc+" built x/y/foo")
-       }
-       checkbar("pkg")
-       tg.creatingTemp("bar" + exeSuffix)
-       tg.sleep()
-       tg.tempFile("src/x/y/foo/foo.go", `package foo
-               func F() { F() }`)
-       tg.tempFile("src/x/y/bar/bar.go", `package main
-               import "x/y/foo"
-               func main() { foo.F() }`)
-       checkbar("cmd")
- }
- func TestGoBuildTestOnly(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("."))
-       tg.tempFile("src/testonly/t_test.go", `package testonly`)
-       tg.tempFile("src/testonly2/t.go", `package testonly2`)
-       tg.cd(tg.path("src"))
-       // Named explicitly, test-only packages should be reported as unbuildable/uninstallable,
-       // even if there is a wildcard also matching.
-       tg.runFail("build", "testonly", "testonly...")
-       tg.grepStderr("no non-test Go files in", "go build ./xtestonly produced unexpected error")
-       tg.runFail("install", "./testonly")
-       tg.grepStderr("no non-test Go files in", "go install ./testonly produced unexpected error")
-       // Named through a wildcards, the test-only packages should be silently ignored.
-       tg.run("build", "testonly...")
-       tg.run("install", "./testonly...")
- }
- func TestGoTestDetectsTestOnlyImportCycles(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.runFail("test", "-c", "testcycle/p3")
-       tg.grepStderr("import cycle not allowed in test", "go test testcycle/p3 produced unexpected error")
-       tg.runFail("test", "-c", "testcycle/q1")
-       tg.grepStderr("import cycle not allowed in test", "go test testcycle/q1 produced unexpected error")
- }
- func TestGoTestFooTestWorks(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("test", "testdata/standalone_test.go")
- }
- func TestGoTestTestMainSeesTestingFlags(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("test", "testdata/standalone_testmain_flag_test.go")
- }
- // Issue 22388
- func TestGoTestMainWithWrongSignature(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.runFail("test", "testdata/standalone_main_wrong_test.go")
-       tg.grepStderr(`wrong signature for TestMain, must be: func TestMain\(m \*testing.M\)`, "detected wrong error message")
- }
- func TestGoTestMainAsNormalTest(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("test", "testdata/standalone_main_normal_test.go")
-       tg.grepBoth(okPattern, "go test did not say ok")
- }
- func TestGoTestMainTwice(t *testing.T) {
-       if testing.Short() {
-               t.Skip("Skipping in short mode")
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOCACHE", tg.tempdir)
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("test", "-v", "multimain")
-       if strings.Count(tg.getStdout(), "notwithstanding") != 2 {
-               t.Fatal("tests did not run twice")
-       }
- }
- func TestGoTestFlagsAfterPackage(t *testing.T) {
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("test", "testdata/flag_test.go", "-v", "-args", "-v=7") // Two distinct -v flags.
-       tg.run("test", "-v", "testdata/flag_test.go", "-args", "-v=7") // Two distinct -v flags.
- }
- func TestGoTestXtestonlyWorks(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("clean", "-i", "xtestonly")
-       tg.run("test", "xtestonly")
- }
- func TestGoTestBuildsAnXtestContainingOnlyNonRunnableExamples(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("test", "-v", "./testdata/norunexample")
-       tg.grepStdout("File with non-runnable example was built.", "file with non-runnable example was not built")
- }
- func TestGoGenerateHandlesSimpleCommand(t *testing.T) {
-       if runtime.GOOS == "windows" {
-               t.Skip("skipping because windows has no echo command")
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("generate", "./testdata/generate/test1.go")
-       tg.grepStdout("Success", "go generate ./testdata/generate/test1.go generated wrong output")
- }
- func TestGoGenerateHandlesCommandAlias(t *testing.T) {
-       if runtime.GOOS == "windows" {
-               t.Skip("skipping because windows has no echo command")
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("generate", "./testdata/generate/test2.go")
-       tg.grepStdout("Now is the time for all good men", "go generate ./testdata/generate/test2.go generated wrong output")
- }
- func TestGoGenerateVariableSubstitution(t *testing.T) {
-       if runtime.GOOS == "windows" {
-               t.Skip("skipping because windows has no echo command")
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("generate", "./testdata/generate/test3.go")
-       tg.grepStdout(runtime.GOARCH+" test3.go:7 pabc xyzp/test3.go/123", "go generate ./testdata/generate/test3.go generated wrong output")
- }
- func TestGoGenerateRunFlag(t *testing.T) {
-       if runtime.GOOS == "windows" {
-               t.Skip("skipping because windows has no echo command")
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("generate", "-run", "y.s", "./testdata/generate/test4.go")
-       tg.grepStdout("yes", "go generate -run yes ./testdata/generate/test4.go did not select yes")
-       tg.grepStdoutNot("no", "go generate -run yes ./testdata/generate/test4.go selected no")
- }
- func TestGoGenerateEnv(t *testing.T) {
-       switch runtime.GOOS {
-       case "plan9", "windows":
-               t.Skipf("skipping because %s does not have the env command", runtime.GOOS)
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.tempFile("env.go", "package main\n\n//go:generate env")
-       tg.run("generate", tg.path("env.go"))
-       for _, v := range []string{"GOARCH", "GOOS", "GOFILE", "GOLINE", "GOPACKAGE", "DOLLAR"} {
-               tg.grepStdout("^"+v+"=", "go generate environment missing "+v)
-       }
- }
- func TestGoGenerateXTestPkgName(t *testing.T) {
-       if runtime.GOOS == "windows" {
-               t.Skip("skipping because windows has no echo command")
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.tempFile("env_test.go", "package main_test\n\n//go:generate echo $GOPACKAGE")
-       tg.run("generate", tg.path("env_test.go"))
-       want := "main_test"
-       if got := strings.TrimSpace(tg.getStdout()); got != want {
-               t.Errorf("go generate in XTest file got package name %q; want %q", got, want)
-       }
- }
- func TestGoGenerateBadImports(t *testing.T) {
-       if runtime.GOOS == "windows" {
-               t.Skip("skipping because windows has no echo command")
-       }
-       // This package has an invalid import causing an import cycle,
-       // but go generate is supposed to still run.
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("generate", "gencycle")
-       tg.grepStdout("hello world", "go generate gencycle did not run generator")
- }
- func TestGoGetCustomDomainWildcard(t *testing.T) {
-       testenv.MustHaveExternalNetwork(t)
-       testenv.MustHaveExecPath(t, "git")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("."))
-       tg.run("get", "-u", "rsc.io/pdf/...")
-       tg.wantExecutable(tg.path("bin/pdfpasswd"+exeSuffix), "did not build rsc/io/pdf/pdfpasswd")
- }
- func TestGoGetInternalWildcard(t *testing.T) {
-       testenv.MustHaveExternalNetwork(t)
-       testenv.MustHaveExecPath(t, "git")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("."))
-       // used to fail with errors about internal packages
-       tg.run("get", "github.com/rsc/go-get-issue-11960/...")
- }
- func TestGoVetWithExternalTests(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.runFail("vet", "vetpkg")
-       tg.grepBoth("Printf", "go vet vetpkg did not find missing argument for Printf")
- }
- func TestGoVetWithTags(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.runFail("vet", "-tags", "tagtest", "vetpkg")
-       tg.grepBoth(`c\.go.*Printf`, "go vet vetpkg did not run scan tagged file")
- }
- func TestGoVetWithFlagsOn(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.runFail("vet", "-printf", "vetpkg")
-       tg.grepBoth("Printf", "go vet -printf vetpkg did not find missing argument for Printf")
- }
- func TestGoVetWithFlagsOff(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("vet", "-printf=false", "vetpkg")
- }
- // Issue 23395.
- func TestGoVetWithOnlyTestFiles(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.tempFile("src/p/p_test.go", "package p; import \"testing\"; func TestMe(*testing.T) {}")
-       tg.setenv("GOPATH", tg.path("."))
-       tg.run("vet", "p")
- }
- // Issue 24193.
- func TestVetWithOnlyCgoFiles(t *testing.T) {
-       if !canCgo {
-               t.Skip("skipping because cgo not enabled")
-       }
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.tempFile("src/p/p.go", "package p; import \"C\"; func F() {}")
-       tg.setenv("GOPATH", tg.path("."))
-       tg.run("vet", "p")
- }
- // Issue 9767, 19769.
- func TestGoGetDotSlashDownload(t *testing.T) {
-       testenv.MustHaveExternalNetwork(t)
-       testenv.MustHaveExecPath(t, "git")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.tempDir("src/rsc.io")
-       tg.setenv("GOPATH", tg.path("."))
-       tg.cd(tg.path("src/rsc.io"))
-       tg.run("get", "./pprof_mac_fix")
- }
- // Test that you cannot import a main package.
- // See golang.org/issue/4210 and golang.org/issue/17475.
- func TestImportMain(t *testing.T) {
-       tooSlow(t)
-       tg := testgo(t)
-       tg.parallel()
-       defer tg.cleanup()
-       // Importing package main from that package main's test should work.
-       tg.tempFile("src/x/main.go", `package main
-               var X int
-               func main() {}`)
-       tg.tempFile("src/x/main_test.go", `package main_test
-               import xmain "x"
-               import "testing"
-               var _ = xmain.X
-               func TestFoo(t *testing.T) {}
-       `)
-       tg.setenv("GOPATH", tg.path("."))
-       tg.creatingTemp("x" + exeSuffix)
-       tg.run("build", "x")
-       tg.run("test", "x")
-       // Importing package main from another package should fail.
-       tg.tempFile("src/p1/p.go", `package p1
-               import xmain "x"
-               var _ = xmain.X
-       `)
-       tg.runFail("build", "p1")
-       tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
-       // ... even in that package's test.
-       tg.tempFile("src/p2/p.go", `package p2
-       `)
-       tg.tempFile("src/p2/p_test.go", `package p2
-               import xmain "x"
-               import "testing"
-               var _ = xmain.X
-               func TestFoo(t *testing.T) {}
-       `)
-       tg.run("build", "p2")
-       tg.runFail("test", "p2")
-       tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
-       // ... even if that package's test is an xtest.
-       tg.tempFile("src/p3/p.go", `package p
-       `)
-       tg.tempFile("src/p3/p_test.go", `package p_test
-               import xmain "x"
-               import "testing"
-               var _ = xmain.X
-               func TestFoo(t *testing.T) {}
-       `)
-       tg.run("build", "p3")
-       tg.runFail("test", "p3")
-       tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
-       // ... even if that package is a package main
-       tg.tempFile("src/p4/p.go", `package main
-       func main() {}
-       `)
-       tg.tempFile("src/p4/p_test.go", `package main
-               import xmain "x"
-               import "testing"
-               var _ = xmain.X
-               func TestFoo(t *testing.T) {}
-       `)
-       tg.creatingTemp("p4" + exeSuffix)
-       tg.run("build", "p4")
-       tg.runFail("test", "p4")
-       tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
-       // ... even if that package is a package main using an xtest.
-       tg.tempFile("src/p5/p.go", `package main
-       func main() {}
-       `)
-       tg.tempFile("src/p5/p_test.go", `package main_test
-               import xmain "x"
-               import "testing"
-               var _ = xmain.X
-               func TestFoo(t *testing.T) {}
-       `)
-       tg.creatingTemp("p5" + exeSuffix)
-       tg.run("build", "p5")
-       tg.runFail("test", "p5")
-       tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
+               {"ReleaseTags", ""},
+               {"InstallSuffix", ""},
+       } {
+               tt := tt
+               t.Run(tt.v, func(t *testing.T) {
+                       tg := testgo(t)
+                       tg.parallel()
+                       defer tg.cleanup()
+                       tmpl := "{{context." + tt.v + "}}"
+                       tg.run("list", "-f", tmpl)
+                       if tt.want == "" {
+                               return
+                       }
+                       if got := strings.TrimSpace(tg.getStdout()); got != tt.want {
+                               t.Errorf("go list -f %q: got %q; want %q", tmpl, got, tt.want)
+                       }
+               })
+       }
  }
  
  // Test that you cannot use a local import in a package
@@@ -3655,132 -1817,6 +1817,6 @@@ func TestImportLocal(t *testing.T) 
        tg.grepStderr("cannot import current directory", "did not diagnose import current directory")
  }
  
- func TestGoGetInsecure(t *testing.T) {
-       test := func(t *testing.T, modules bool) {
-               testenv.MustHaveExternalNetwork(t)
-               testenv.MustHaveExecPath(t, "git")
-               tg := testgo(t)
-               defer tg.cleanup()
-               tg.makeTempdir()
-               tg.failSSH()
-               if modules {
-                       tg.setenv("GOPATH", tg.path("gp"))
-                       tg.tempFile("go.mod", "module m")
-                       tg.cd(tg.path("."))
-                       tg.setenv("GO111MODULE", "on")
-                       tg.setenv("GOPROXY", "")
-               } else {
-                       tg.setenv("GOPATH", tg.path("."))
-                       tg.setenv("GO111MODULE", "off")
-               }
-               const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
-               // Try go get -d of HTTP-only repo (should fail).
-               tg.runFail("get", "-d", repo)
-               // Try again with -insecure (should succeed).
-               tg.run("get", "-d", "-insecure", repo)
-               // Try updating without -insecure (should fail).
-               tg.runFail("get", "-d", "-u", "-f", repo)
-               if modules {
-                       tg.run("list", "-m", "...")
-                       tg.grepStdout("insecure.go-get-issue", "should find insecure module")
-               }
-       }
-       t.Run("gopath", func(t *testing.T) { test(t, false) })
-       t.Run("modules", func(t *testing.T) { test(t, true) })
- }
- func TestGoGetUpdateInsecure(t *testing.T) {
-       testenv.MustHaveExternalNetwork(t)
-       testenv.MustHaveExecPath(t, "git")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("."))
-       const repo = "github.com/golang/example"
-       // Clone the repo via HTTP manually.
-       cmd := exec.Command("git", "clone", "-q", "http://"+repo, tg.path("src/"+repo))
-       if out, err := cmd.CombinedOutput(); err != nil {
-               t.Fatalf("cloning %v repo: %v\n%s", repo, err, out)
-       }
-       // Update without -insecure should fail.
-       // Update with -insecure should succeed.
-       // We need -f to ignore import comments.
-       const pkg = repo + "/hello"
-       tg.runFail("get", "-d", "-u", "-f", pkg)
-       tg.run("get", "-d", "-u", "-f", "-insecure", pkg)
- }
- func TestGoGetUpdateUnknownProtocol(t *testing.T) {
-       testenv.MustHaveExternalNetwork(t)
-       testenv.MustHaveExecPath(t, "git")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("."))
-       const repo = "github.com/golang/example"
-       // Clone the repo via HTTPS manually.
-       repoDir := tg.path("src/" + repo)
-       cmd := exec.Command("git", "clone", "-q", "https://"+repo, repoDir)
-       if out, err := cmd.CombinedOutput(); err != nil {
-               t.Fatalf("cloning %v repo: %v\n%s", repo, err, out)
-       }
-       // Configure the repo to use a protocol unknown to cmd/go
-       // that still actually works.
-       cmd = exec.Command("git", "remote", "set-url", "origin", "xyz://"+repo)
-       cmd.Dir = repoDir
-       if out, err := cmd.CombinedOutput(); err != nil {
-               t.Fatalf("git remote set-url: %v\n%s", err, out)
-       }
-       cmd = exec.Command("git", "config", "--local", "url.https://github.com/.insteadOf", "xyz://github.com/")
-       cmd.Dir = repoDir
-       if out, err := cmd.CombinedOutput(); err != nil {
-               t.Fatalf("git config: %v\n%s", err, out)
-       }
-       // We need -f to ignore import comments.
-       tg.run("get", "-d", "-u", "-f", repo+"/hello")
- }
- func TestGoGetInsecureCustomDomain(t *testing.T) {
-       testenv.MustHaveExternalNetwork(t)
-       testenv.MustHaveExecPath(t, "git")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("."))
-       const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
-       tg.runFail("get", "-d", repo)
-       tg.run("get", "-d", "-insecure", repo)
- }
- func TestGoRunDirs(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.cd("testdata/rundir")
-       tg.runFail("run", "x.go", "sub/sub.go")
-       tg.grepStderr("named files must all be in one directory; have ./ and sub/", "wrong output")
-       tg.runFail("run", "sub/sub.go", "x.go")
-       tg.grepStderr("named files must all be in one directory; have sub/ and ./", "wrong output")
- }
  func TestGoInstallPkgdir(t *testing.T) {
        skipIfGccgo(t, "gccgo has no standard packages")
        tooSlow(t)
        tg.run("install", "-pkgdir", pkg, "sync")
        tg.mustExist(filepath.Join(pkg, "sync.a"))
        tg.mustNotExist(filepath.Join(pkg, "sync/atomic.a"))
-       tg.run("install", "-i", "-pkgdir", pkg, "sync")
-       tg.mustExist(filepath.Join(pkg, "sync.a"))
-       tg.mustExist(filepath.Join(pkg, "sync/atomic.a"))
- }
- func TestGoTestRaceInstallCgo(t *testing.T) {
-       if !canRace {
-               t.Skip("skipping because race detector not supported")
-       }
-       // golang.org/issue/10500.
-       // This used to install a race-enabled cgo.
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("tool", "-n", "cgo")
-       cgo := strings.TrimSpace(tg.stdout.String())
-       old, err := os.Stat(cgo)
-       tg.must(err)
-       tg.run("test", "-race", "-i", "runtime/race")
-       new, err := os.Stat(cgo)
-       tg.must(err)
-       if !new.ModTime().Equal(old.ModTime()) {
-               t.Fatalf("go test -i runtime/race reinstalled cmd/cgo")
-       }
- }
- func TestGoTestRaceFailures(t *testing.T) {
-       tooSlow(t)
-       if !canRace {
-               t.Skip("skipping because race detector not supported")
-       }
-       tg := testgo(t)
-       tg.parallel()
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("test", "testrace")
-       tg.runFail("test", "-race", "testrace")
-       tg.grepStdout("FAIL: TestRace", "TestRace did not fail")
-       tg.grepBothNot("PASS", "something passed")
-       tg.runFail("test", "-race", "testrace", "-run", "XXX", "-bench", ".")
-       tg.grepStdout("FAIL: BenchmarkRace", "BenchmarkRace did not fail")
-       tg.grepBothNot("PASS", "something passed")
- }
- func TestGoTestImportErrorStack(t *testing.T) {
-       const out = `package testdep/p1 (test)
-       imports testdep/p2
-       imports testdep/p3: build constraints exclude all Go files `
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.runFail("test", "testdep/p1")
-       if !strings.Contains(tg.stderr.String(), out) {
-               t.Fatalf("did not give full import stack:\n\n%s", tg.stderr.String())
-       }
- }
- func TestGoGetUpdate(t *testing.T) {
-       // golang.org/issue/9224.
-       // The recursive updating was trying to walk to
-       // former dependencies, not current ones.
-       testenv.MustHaveExternalNetwork(t)
-       testenv.MustHaveExecPath(t, "git")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("."))
-       rewind := func() {
-               tg.run("get", "github.com/rsc/go-get-issue-9224-cmd")
-               cmd := exec.Command("git", "reset", "--hard", "HEAD~")
-               cmd.Dir = tg.path("src/github.com/rsc/go-get-issue-9224-lib")
-               out, err := cmd.CombinedOutput()
-               if err != nil {
-                       t.Fatalf("git: %v\n%s", err, out)
-               }
-       }
-       rewind()
-       tg.run("get", "-u", "github.com/rsc/go-get-issue-9224-cmd")
-       // Again with -d -u.
-       rewind()
-       tg.run("get", "-d", "-u", "github.com/rsc/go-get-issue-9224-cmd")
- }
- // Issue #20512.
- func TestGoGetRace(t *testing.T) {
-       testenv.MustHaveExternalNetwork(t)
-       testenv.MustHaveExecPath(t, "git")
-       if !canRace {
-               t.Skip("skipping because race detector not supported")
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("."))
-       tg.run("get", "-race", "github.com/rsc/go-get-issue-9224-cmd")
- }
- func TestGoGetDomainRoot(t *testing.T) {
-       // golang.org/issue/9357.
-       // go get foo.io (not foo.io/subdir) was not working consistently.
-       testenv.MustHaveExternalNetwork(t)
-       testenv.MustHaveExecPath(t, "git")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("."))
-       // go-get-issue-9357.appspot.com is running
-       // the code at github.com/rsc/go-get-issue-9357,
-       // a trivial Go on App Engine app that serves a
-       // <meta> tag for the domain root.
-       tg.run("get", "-d", "go-get-issue-9357.appspot.com")
-       tg.run("get", "go-get-issue-9357.appspot.com")
-       tg.run("get", "-u", "go-get-issue-9357.appspot.com")
-       tg.must(robustio.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
-       tg.run("get", "go-get-issue-9357.appspot.com")
-       tg.must(robustio.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
-       tg.run("get", "-u", "go-get-issue-9357.appspot.com")
- }
- func TestGoInstallShadowedGOPATH(t *testing.T) {
-       // golang.org/issue/3652.
-       // go get foo.io (not foo.io/subdir) was not working consistently.
-       testenv.MustHaveExternalNetwork(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("gopath1")+string(filepath.ListSeparator)+tg.path("gopath2"))
-       tg.tempDir("gopath1/src/test")
-       tg.tempDir("gopath2/src/test")
-       tg.tempFile("gopath2/src/test/main.go", "package main\nfunc main(){}\n")
-       tg.cd(tg.path("gopath2/src/test"))
-       tg.runFail("install")
-       tg.grepStderr("no install location for.*gopath2.src.test: hidden by .*gopath1.src.test", "missing error")
- }
- func TestGoBuildGOPATHOrder(t *testing.T) {
-       // golang.org/issue/14176#issuecomment-179895769
-       // golang.org/issue/14192
-       // -I arguments to compiler could end up not in GOPATH order,
-       // leading to unexpected import resolution in the compiler.
-       // This is still not a complete fix (see golang.org/issue/14271 and next test)
-       // but it is clearly OK and enough to fix both of the two reported
-       // instances of the underlying problem. It will have to do for now.
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("p1")+string(filepath.ListSeparator)+tg.path("p2"))
-       tg.tempFile("p1/src/foo/foo.go", "package foo\n")
-       tg.tempFile("p2/src/baz/baz.go", "package baz\n")
-       tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
-       tg.tempFile("p1/src/bar/bar.go", `
-               package bar
-               import _ "baz"
-               import _ "foo"
-       `)
-       tg.run("install", "-x", "bar")
- }
- func TestGoBuildGOPATHOrderBroken(t *testing.T) {
-       // This test is known not to work.
-       // See golang.org/issue/14271.
-       t.Skip("golang.org/issue/14271")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.tempFile("p1/src/foo/foo.go", "package foo\n")
-       tg.tempFile("p2/src/baz/baz.go", "package baz\n")
-       tg.tempFile("p1/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/baz.a", "bad\n")
-       tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
-       tg.tempFile("p1/src/bar/bar.go", `
-               package bar
-               import _ "baz"
-               import _ "foo"
-       `)
-       colon := string(filepath.ListSeparator)
-       tg.setenv("GOPATH", tg.path("p1")+colon+tg.path("p2"))
-       tg.run("install", "-x", "bar")
-       tg.setenv("GOPATH", tg.path("p2")+colon+tg.path("p1"))
-       tg.run("install", "-x", "bar")
- }
- func TestIssue11709(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.tempFile("run.go", `
-               package main
-               import "os"
-               func main() {
-                       if os.Getenv("TERM") != "" {
-                               os.Exit(1)
-                       }
-               }`)
-       tg.unsetenv("TERM")
-       tg.run("run", tg.path("run.go"))
- }
- func TestIssue12096(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.tempFile("test_test.go", `
-               package main
-               import ("os"; "testing")
-               func TestEnv(t *testing.T) {
-                       if os.Getenv("TERM") != "" {
-                               t.Fatal("TERM is set")
-                       }
-               }`)
-       tg.unsetenv("TERM")
-       tg.run("test", tg.path("test_test.go"))
- }
- func TestGoBuildOutput(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no standard packages")
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.cd(tg.path("."))
-       nonExeSuffix := ".exe"
-       if exeSuffix == ".exe" {
-               nonExeSuffix = ""
-       }
-       tg.tempFile("x.go", "package main\nfunc main(){}\n")
-       tg.run("build", "x.go")
-       tg.wantExecutable("x"+exeSuffix, "go build x.go did not write x"+exeSuffix)
-       tg.must(os.Remove(tg.path("x" + exeSuffix)))
-       tg.mustNotExist("x" + nonExeSuffix)
-       tg.run("build", "-o", "myprog", "x.go")
-       tg.mustNotExist("x")
-       tg.mustNotExist("x.exe")
-       tg.wantExecutable("myprog", "go build -o myprog x.go did not write myprog")
-       tg.mustNotExist("myprog.exe")
-       tg.tempFile("p.go", "package p\n")
-       tg.run("build", "p.go")
-       tg.mustNotExist("p")
-       tg.mustNotExist("p.a")
-       tg.mustNotExist("p.o")
-       tg.mustNotExist("p.exe")
-       tg.run("build", "-o", "p.a", "p.go")
-       tg.wantArchive("p.a")
-       tg.run("build", "cmd/gofmt")
-       tg.wantExecutable("gofmt"+exeSuffix, "go build cmd/gofmt did not write gofmt"+exeSuffix)
-       tg.must(os.Remove(tg.path("gofmt" + exeSuffix)))
-       tg.mustNotExist("gofmt" + nonExeSuffix)
-       tg.run("build", "-o", "mygofmt", "cmd/gofmt")
-       tg.wantExecutable("mygofmt", "go build -o mygofmt cmd/gofmt did not write mygofmt")
-       tg.mustNotExist("mygofmt.exe")
-       tg.mustNotExist("gofmt")
-       tg.mustNotExist("gofmt.exe")
-       tg.run("build", "sync/atomic")
-       tg.mustNotExist("atomic")
-       tg.mustNotExist("atomic.exe")
-       tg.run("build", "-o", "myatomic.a", "sync/atomic")
-       tg.wantArchive("myatomic.a")
-       tg.mustNotExist("atomic")
-       tg.mustNotExist("atomic.a")
-       tg.mustNotExist("atomic.exe")
-       tg.runFail("build", "-o", "whatever", "cmd/gofmt", "sync/atomic")
-       tg.grepStderr("multiple packages", "did not reject -o with multiple packages")
- }
- func TestGoBuildARM(t *testing.T) {
-       if testing.Short() {
-               t.Skip("skipping cross-compile in short mode")
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.cd(tg.path("."))
-       tg.setenv("GOARCH", "arm")
-       tg.setenv("GOOS", "linux")
-       tg.setenv("GOARM", "5")
-       tg.tempFile("hello.go", `package main
-               func main() {}`)
-       tg.run("build", "hello.go")
-       tg.grepStderrNot("unable to find math.a", "did not build math.a correctly")
- }
- // For issue 14337.
- func TestParallelTest(t *testing.T) {
-       tooSlow(t)
-       tg := testgo(t)
-       tg.parallel()
-       defer tg.cleanup()
-       tg.makeTempdir()
-       const testSrc = `package package_test
-               import (
-                       "testing"
-               )
-               func TestTest(t *testing.T) {
-               }`
-       tg.tempFile("src/p1/p1_test.go", strings.Replace(testSrc, "package_test", "p1_test", 1))
-       tg.tempFile("src/p2/p2_test.go", strings.Replace(testSrc, "package_test", "p2_test", 1))
-       tg.tempFile("src/p3/p3_test.go", strings.Replace(testSrc, "package_test", "p3_test", 1))
-       tg.tempFile("src/p4/p4_test.go", strings.Replace(testSrc, "package_test", "p4_test", 1))
-       tg.setenv("GOPATH", tg.path("."))
-       tg.run("test", "-p=4", "p1", "p2", "p3", "p4")
- }
- func TestCgoConsistentResults(t *testing.T) {
-       tooSlow(t)
-       if !canCgo {
-               t.Skip("skipping because cgo not enabled")
-       }
-       switch runtime.GOOS {
-       case "solaris", "illumos":
-               testenv.SkipFlaky(t, 13247)
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       exe1 := tg.path("cgotest1" + exeSuffix)
-       exe2 := tg.path("cgotest2" + exeSuffix)
-       tg.run("build", "-o", exe1, "cgotest")
-       tg.run("build", "-x", "-o", exe2, "cgotest")
-       b1, err := ioutil.ReadFile(exe1)
-       tg.must(err)
-       b2, err := ioutil.ReadFile(exe2)
-       tg.must(err)
-       if !tg.doGrepMatch(`-fdebug-prefix-map=\$WORK`, &tg.stderr) {
-               t.Skip("skipping because C compiler does not support -fdebug-prefix-map")
-       }
-       if !bytes.Equal(b1, b2) {
-               t.Error("building cgotest twice did not produce the same output")
-       }
- }
- // Issue 14444: go get -u .../ duplicate loads errors
- func TestGoGetUpdateAllDoesNotTryToLoadDuplicates(t *testing.T) {
-       testenv.MustHaveExternalNetwork(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("."))
-       tg.run("get", "-u", ".../")
-       tg.grepStderrNot("duplicate loads of", "did not remove old packages from cache")
+       tg.run("install", "-i", "-pkgdir", pkg, "sync")
+       tg.mustExist(filepath.Join(pkg, "sync.a"))
+       tg.mustExist(filepath.Join(pkg, "sync/atomic.a"))
  }
  
- // Issue 17119 more duplicate load errors
- func TestIssue17119(t *testing.T) {
-       testenv.MustHaveExternalNetwork(t)
+ // For issue 14337.
+ func TestParallelTest(t *testing.T) {
+       tooSlow(t)
        tg := testgo(t)
-       defer tg.cleanup()
        tg.parallel()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.runFail("build", "dupload")
-       tg.grepBothNot("duplicate load|internal error", "internal error")
- }
- func TestFatalInBenchmarkCauseNonZeroExitStatus(t *testing.T) {
-       tg := testgo(t)
        defer tg.cleanup()
-       // TODO: tg.parallel()
-       tg.runFail("test", "-run", "^$", "-bench", ".", "./testdata/src/benchfatal")
-       tg.grepBothNot("^ok", "test passed unexpectedly")
-       tg.grepBoth("FAIL.*benchfatal", "test did not run everything")
+       tg.makeTempdir()
+       const testSrc = `package package_test
+               import (
+                       "testing"
+               )
+               func TestTest(t *testing.T) {
+               }`
+       tg.tempFile("src/p1/p1_test.go", strings.Replace(testSrc, "package_test", "p1_test", 1))
+       tg.tempFile("src/p2/p2_test.go", strings.Replace(testSrc, "package_test", "p2_test", 1))
+       tg.tempFile("src/p3/p3_test.go", strings.Replace(testSrc, "package_test", "p3_test", 1))
+       tg.tempFile("src/p4/p4_test.go", strings.Replace(testSrc, "package_test", "p4_test", 1))
+       tg.setenv("GOPATH", tg.path("."))
+       tg.run("test", "-p=4", "p1", "p2", "p3", "p4")
  }
  
  func TestBinaryOnlyPackages(t *testing.T) {
        tg.grepStdout("p2: false", "p2 listed as BinaryOnly")
  }
  
 -// Issue 16050.
 -func TestAlwaysLinkSysoFiles(t *testing.T) {
 +// Issue 16050 and 21884.
 +func TestLinkSysoFiles(t *testing.T) {
 +      if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" {
 +              t.Skip("not linux/amd64")
 +      }
 +
        tg := testgo(t)
        defer tg.cleanup()
        tg.parallel()
        tg.setenv("CGO_ENABLED", "0")
        tg.run("list", "-f", "{{.SysoFiles}}", "syso")
        tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=0")
 +
 +      tg.setenv("CGO_ENABLED", "1")
 +      tg.run("list", "-msan", "-f", "{{.SysoFiles}}", "syso")
 +      tg.grepStdoutNot("a.syso", "unexpected syso file with -msan")
  }
  
  // Issue 16120.
@@@ -4303,36 -1951,6 +1959,6 @@@ func TestGenerateUsesBuildContext(t *te
        tg.grepStdout("darwin 386", "unexpected GOOS/GOARCH combination")
  }
  
- // Issue 14450: go get -u .../ tried to import not downloaded package
- func TestGoGetUpdateWithWildcard(t *testing.T) {
-       testenv.MustHaveExternalNetwork(t)
-       testenv.MustHaveExecPath(t, "git")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("."))
-       const aPkgImportPath = "github.com/tmwh/go-get-issue-14450/a"
-       tg.run("get", aPkgImportPath)
-       tg.runFail("get", "-u", ".../")
-       tg.grepStderr("cannot find package.*d-dependency/e", "should have detected e missing")
-       // Even though get -u failed, the source for others should be downloaded.
-       var expectedPkgPaths = []string{
-               "src/github.com/tmwh/go-get-issue-14450/b",
-               "src/github.com/tmwh/go-get-issue-14450-b-dependency/c",
-               "src/github.com/tmwh/go-get-issue-14450-b-dependency/d",
-       }
-       for _, importPath := range expectedPkgPaths {
-               _, err := os.Stat(tg.path(importPath))
-               tg.must(err)
-       }
-       const notExpectedPkgPath = "src/github.com/tmwh/go-get-issue-14450-c-dependency/e"
-       tg.mustNotExist(tg.path(notExpectedPkgPath))
- }
  func TestGoEnv(t *testing.T) {
        tg := testgo(t)
        tg.parallel()
@@@ -4364,175 -1982,6 +1990,6 @@@ const 
        okPattern        = `(?m)^ok`
  )
  
- func TestMatchesNoTests(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       // TODO: tg.parallel()
-       tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_test.go")
-       tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
- }
- func TestMatchesNoTestsDoesNotOverrideBuildFailure(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.runFail("test", "-run", "ThisWillNotMatch", "syntaxerror")
-       tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
-       tg.grepBoth("FAIL", "go test did not say FAIL")
- }
- func TestMatchesNoBenchmarksIsOK(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       // TODO: tg.parallel()
-       tg.run("test", "-run", "^$", "-bench", "ThisWillNotMatch", "testdata/standalone_benchmark_test.go")
-       tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
-       tg.grepBoth(okPattern, "go test did not say ok")
- }
- func TestMatchesOnlyExampleIsOK(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       // TODO: tg.parallel()
-       tg.run("test", "-run", "Example", "testdata/example1_test.go")
-       tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
-       tg.grepBoth(okPattern, "go test did not say ok")
- }
- func TestMatchesOnlyBenchmarkIsOK(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       // TODO: tg.parallel()
-       tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
-       tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
-       tg.grepBoth(okPattern, "go test did not say ok")
- }
- func TestBenchmarkLabels(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       // TODO: tg.parallel()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("test", "-run", "^$", "-bench", ".", "bench")
-       tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
-       tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
-       tg.grepStdout(`(?m)^pkg: bench`, "go test did not say pkg: bench")
-       tg.grepBothNot(`(?s)pkg:.*pkg:`, "go test said pkg multiple times")
- }
- func TestBenchmarkLabelsOutsideGOPATH(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       // TODO: tg.parallel()
-       tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
-       tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
-       tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
-       tg.grepBothNot(`(?m)^pkg:`, "go test did say pkg:")
- }
- func TestMatchesOnlyTestIsOK(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       // TODO: tg.parallel()
-       tg.run("test", "-run", "Test", "testdata/standalone_test.go")
-       tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
-       tg.grepBoth(okPattern, "go test did not say ok")
- }
- func TestMatchesNoTestsWithSubtests(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_sub_test.go")
-       tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
- }
- func TestMatchesNoSubtestsMatch(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("test", "-run", "Test/ThisWillNotMatch", "testdata/standalone_sub_test.go")
-       tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
- }
- func TestMatchesNoSubtestsDoesNotOverrideFailure(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.runFail("test", "-run", "TestThatFails/ThisWillNotMatch", "testdata/standalone_fail_sub_test.go")
-       tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
-       tg.grepBoth("FAIL", "go test did not say FAIL")
- }
- func TestMatchesOnlySubtestIsOK(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("test", "-run", "Test/Sub", "testdata/standalone_sub_test.go")
-       tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
-       tg.grepBoth(okPattern, "go test did not say ok")
- }
- func TestMatchesNoSubtestsParallel(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("test", "-run", "Test/Sub/ThisWillNotMatch", "testdata/standalone_parallel_sub_test.go")
-       tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
- }
- func TestMatchesOnlySubtestParallelIsOK(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("test", "-run", "Test/Sub/Nested", "testdata/standalone_parallel_sub_test.go")
-       tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
-       tg.grepBoth(okPattern, "go test did not say ok")
- }
- // Issue 18845
- func TestBenchTimeout(t *testing.T) {
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("test", "-bench", ".", "-timeout", "750ms", "testdata/timeoutbench_test.go")
- }
- // Issue 19394
- func TestWriteProfilesOnTimeout(t *testing.T) {
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.tempDir("profiling")
-       tg.tempFile("profiling/timeouttest_test.go", `package timeouttest_test
- import "testing"
- import "time"
- func TestSleep(t *testing.T) { time.Sleep(time.Second) }`)
-       tg.cd(tg.path("profiling"))
-       tg.runFail(
-               "test",
-               "-cpuprofile", tg.path("profiling/cpu.pprof"), "-memprofile", tg.path("profiling/mem.pprof"),
-               "-timeout", "1ms")
-       tg.mustHaveContent(tg.path("profiling/cpu.pprof"))
-       tg.mustHaveContent(tg.path("profiling/mem.pprof"))
- }
- func TestLinkXImportPathEscape(t *testing.T) {
-       // golang.org/issue/16710
-       skipIfGccgo(t, "gccgo does not support -ldflags -X")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       exe := tg.path("linkx" + exeSuffix)
-       tg.creatingTemp(exe)
-       tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked", "my.pkg/main")
-       out, err := exec.Command(exe).CombinedOutput()
-       if err != nil {
-               tg.t.Fatal(err)
-       }
-       if string(out) != "linkXworked\n" {
-               tg.t.Log(string(out))
-               tg.t.Fatal(`incorrect output: expected "linkXworked\n"`)
-       }
- }
  // Issue 18044.
  func TestLdBindNow(t *testing.T) {
        tg := testgo(t)
@@@ -4559,29 -2008,6 +2016,6 @@@ GLOBL Â·constants<>(SB),8,$
        tg.run("build", "p")
  }
  
- // Issue 18778.
- func TestDotDotDotOutsideGOPATH(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.tempFile("pkgs/a.go", `package x`)
-       tg.tempFile("pkgs/a_test.go", `package x_test
- import "testing"
- func TestX(t *testing.T) {}`)
-       tg.tempFile("pkgs/a/a.go", `package a`)
-       tg.tempFile("pkgs/a/a_test.go", `package a_test
- import "testing"
- func TestA(t *testing.T) {}`)
-       tg.cd(tg.path("pkgs"))
-       tg.run("build", "./...")
-       tg.run("test", "./...")
-       tg.run("list", "./...")
-       tg.grepStdout("pkgs$", "expected package not listed")
-       tg.grepStdout("pkgs/a", "expected package not listed")
- }
  // Issue 18975.
  func TestFFLAGS(t *testing.T) {
        if !canCgo {
@@@ -4654,17 -2080,6 +2088,6 @@@ func main() 
        tg.run("build", "-o", exe, "p")
  }
  
- func TestBuildTagsNoComma(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no standard packages")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", tg.path("go"))
-       tg.run("build", "-tags", "tag1 tag2", "math")
-       tg.runFail("build", "-tags", "tag1,tag2 tag3", "math")
-       tg.grepBoth("space-separated list contains comma", "-tags with a comma-separated list didn't error")
- }
  func copyFile(src, dst string, perm os.FileMode) error {
        sf, err := os.Open(src)
        if err != nil {
        return err2
  }
  
- // TestExecutableGOROOT verifies that the cmd/go binary itself uses
- // os.Executable (when available) to locate GOROOT.
- func TestExecutableGOROOT(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no GOROOT")
-       // Note: Must not call tg methods inside subtests: tg is attached to outer t.
-       tg := testgo(t)
-       tg.unsetenv("GOROOT")
-       defer tg.cleanup()
-       check := func(t *testing.T, exe, want string) {
-               cmd := exec.Command(exe, "env", "GOROOT")
-               cmd.Env = tg.env
-               out, err := cmd.CombinedOutput()
-               if err != nil {
-                       t.Fatalf("%s env GOROOT: %v, %s", exe, err, out)
-               }
-               goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
-               if err != nil {
-                       t.Fatal(err)
-               }
-               want, err = filepath.EvalSymlinks(want)
-               if err != nil {
-                       t.Fatal(err)
-               }
-               if !strings.EqualFold(goroot, want) {
-                       t.Errorf("go env GOROOT:\nhave %s\nwant %s", goroot, want)
-               } else {
-                       t.Logf("go env GOROOT: %s", goroot)
-               }
-       }
-       tg.makeTempdir()
-       tg.tempDir("new/bin")
-       newGoTool := tg.path("new/bin/go" + exeSuffix)
-       tg.must(copyFile(tg.goTool(), newGoTool, 0775))
-       newRoot := tg.path("new")
-       t.Run("RelocatedExe", func(t *testing.T) {
-               // Should fall back to default location in binary,
-               // which is the GOROOT we used when building testgo.exe.
-               check(t, newGoTool, testGOROOT)
-       })
-       // If the binary is sitting in a bin dir next to ../pkg/tool, that counts as a GOROOT,
-       // so it should find the new tree.
-       tg.tempDir("new/pkg/tool")
-       t.Run("RelocatedTree", func(t *testing.T) {
-               check(t, newGoTool, newRoot)
-       })
-       tg.tempDir("other/bin")
-       symGoTool := tg.path("other/bin/go" + exeSuffix)
-       // Symlink into go tree should still find go tree.
-       t.Run("SymlinkedExe", func(t *testing.T) {
-               testenv.MustHaveSymlink(t)
-               if err := os.Symlink(newGoTool, symGoTool); err != nil {
-                       t.Fatal(err)
-               }
-               check(t, symGoTool, newRoot)
-       })
-       tg.must(robustio.RemoveAll(tg.path("new/pkg")))
-       // Binaries built in the new tree should report the
-       // new tree when they call runtime.GOROOT.
-       t.Run("RuntimeGoroot", func(t *testing.T) {
-               // Build a working GOROOT the easy way, with symlinks.
-               testenv.MustHaveSymlink(t)
-               if err := os.Symlink(filepath.Join(testGOROOT, "src"), tg.path("new/src")); err != nil {
-                       t.Fatal(err)
-               }
-               if err := os.Symlink(filepath.Join(testGOROOT, "pkg"), tg.path("new/pkg")); err != nil {
-                       t.Fatal(err)
-               }
-               cmd := exec.Command(newGoTool, "run", "testdata/print_goroot.go")
-               cmd.Env = tg.env
-               cmd.Stderr = os.Stderr
-               out, err := cmd.Output()
-               if err != nil {
-                       t.Fatalf("%s run testdata/print_goroot.go: %v, %s", newGoTool, err, out)
-               }
-               goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
-               if err != nil {
-                       t.Fatal(err)
-               }
-               want, err := filepath.EvalSymlinks(tg.path("new"))
-               if err != nil {
-                       t.Fatal(err)
-               }
-               if !strings.EqualFold(goroot, want) {
-                       t.Errorf("go run testdata/print_goroot.go:\nhave %s\nwant %s", goroot, want)
-               } else {
-                       t.Logf("go run testdata/print_goroot.go: %s", goroot)
-               }
-       })
- }
  func TestNeedVersion(t *testing.T) {
        skipIfGccgo(t, "gccgo does not use cmd/compile")
        tg := testgo(t)
        tg.grepStderr("compile", "does not match go tool version")
  }
  
- // Test that user can override default code generation flags.
- func TestUserOverrideFlags(t *testing.T) {
-       skipIfGccgo(t, "gccgo does not use -gcflags")
-       if !canCgo {
-               t.Skip("skipping because cgo not enabled")
-       }
-       if runtime.GOOS != "linux" {
-               // We are testing platform-independent code, so it's
-               // OK to skip cases that work differently.
-               t.Skipf("skipping on %s because test only works if c-archive implies -shared", runtime.GOOS)
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       // Don't call tg.parallel, as creating override.h and override.a may
-       // confuse other tests.
-       tg.tempFile("override.go", `package main
- import "C"
- //export GoFunc
- func GoFunc() {}
- func main() {}`)
-       tg.creatingTemp("override.a")
-       tg.creatingTemp("override.h")
-       tg.run("build", "-x", "-buildmode=c-archive", "-gcflags=all=-shared=false", tg.path("override.go"))
-       tg.grepStderr("compile .*-shared .*-shared=false", "user can not override code generation flag")
- }
- func TestCgoFlagContainsSpace(t *testing.T) {
-       tooSlow(t)
-       if !canCgo {
-               t.Skip("skipping because cgo not enabled")
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.makeTempdir()
-       tg.cd(tg.path("."))
-       tg.tempFile("main.go", `package main
-               // #cgo CFLAGS: -I"c flags"
-               // #cgo LDFLAGS: -L"ld flags"
-               import "C"
-               func main() {}
-       `)
-       tg.run("run", "-x", "main.go")
-       tg.grepStderr(`"-I[^"]+c flags"`, "did not find quoted c flags")
-       tg.grepStderrNot(`"-I[^"]+c flags".*"-I[^"]+c flags"`, "found too many quoted c flags")
-       tg.grepStderr(`"-L[^"]+ld flags"`, "did not find quoted ld flags")
-       tg.grepStderrNot(`"-L[^"]+c flags".*"-L[^"]+c flags"`, "found too many quoted ld flags")
- }
- // Issue #20435.
- func TestGoTestRaceCoverModeFailures(t *testing.T) {
-       tooSlow(t)
-       if !canRace {
-               t.Skip("skipping because race detector not supported")
-       }
-       tg := testgo(t)
-       tg.parallel()
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("test", "testrace")
-       tg.runFail("test", "-race", "-covermode=set", "testrace")
-       tg.grepStderr(`-covermode must be "atomic", not "set", when -race is enabled`, "-race -covermode=set was allowed")
-       tg.grepBothNot("PASS", "something passed")
- }
- // Issue 9737: verify that GOARM and GO386 affect the computed build ID.
- func TestBuildIDContainsArchModeEnv(t *testing.T) {
-       if testing.Short() {
-               t.Skip("skipping in short mode")
-       }
-       var tg *testgoData
-       testWith := func(before, after func()) func(*testing.T) {
-               return func(t *testing.T) {
-                       tg = testgo(t)
-                       defer tg.cleanup()
-                       tg.tempFile("src/mycmd/x.go", `package main
- func main() {}`)
-                       tg.setenv("GOPATH", tg.path("."))
-                       tg.cd(tg.path("src/mycmd"))
-                       tg.setenv("GOOS", "linux")
-                       before()
-                       tg.run("install", "mycmd")
-                       after()
-                       tg.wantStale("mycmd", "stale dependency", "should be stale after environment variable change")
-               }
-       }
-       t.Run("386", testWith(func() {
-               tg.setenv("GOARCH", "386")
-               tg.setenv("GO386", "387")
-       }, func() {
-               tg.setenv("GO386", "sse2")
-       }))
-       t.Run("arm", testWith(func() {
-               tg.setenv("GOARCH", "arm")
-               tg.setenv("GOARM", "5")
-       }, func() {
-               tg.setenv("GOARM", "7")
-       }))
- }
- func TestTestRegexps(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("test", "-cpu=1", "-run=X/Y", "-bench=X/Y", "-count=2", "-v", "testregexp")
-       var lines []string
-       for _, line := range strings.SplitAfter(tg.getStdout(), "\n") {
-               if strings.Contains(line, "=== RUN") || strings.Contains(line, "--- BENCH") || strings.Contains(line, "LOG") {
-                       lines = append(lines, line)
-               }
-       }
-       // Important parts:
-       //      TestX is run, twice
-       //      TestX/Y is run, twice
-       //      TestXX is run, twice
-       //      TestZ is not run
-       //      BenchmarkX is run but only with N=1, once
-       //      BenchmarkXX is run but only with N=1, once
-       //      BenchmarkX/Y is run in full, twice
-       want := `=== RUN   TestX
-     TestX: x_test.go:6: LOG: X running
- === RUN   TestX/Y
-     TestX/Y: x_test.go:8: LOG: Y running
- === RUN   TestXX
-     TestXX: z_test.go:10: LOG: XX running
- === RUN   TestX
-     TestX: x_test.go:6: LOG: X running
- === RUN   TestX/Y
-     TestX/Y: x_test.go:8: LOG: Y running
- === RUN   TestXX
-     TestXX: z_test.go:10: LOG: XX running
-     BenchmarkX: x_test.go:13: LOG: X running N=1
-     BenchmarkX/Y: x_test.go:15: LOG: Y running N=1
-     BenchmarkX/Y: x_test.go:15: LOG: Y running N=100
-     BenchmarkX/Y: x_test.go:15: LOG: Y running N=10000
-     BenchmarkX/Y: x_test.go:15: LOG: Y running N=1000000
-     BenchmarkX/Y: x_test.go:15: LOG: Y running N=100000000
-     BenchmarkX/Y: x_test.go:15: LOG: Y running N=1000000000
-     BenchmarkX/Y: x_test.go:15: LOG: Y running N=1
-     BenchmarkX/Y: x_test.go:15: LOG: Y running N=100
-     BenchmarkX/Y: x_test.go:15: LOG: Y running N=10000
-     BenchmarkX/Y: x_test.go:15: LOG: Y running N=1000000
-     BenchmarkX/Y: x_test.go:15: LOG: Y running N=100000000
-     BenchmarkX/Y: x_test.go:15: LOG: Y running N=1000000000
-     BenchmarkXX: z_test.go:18: LOG: XX running N=1
- `
-       have := strings.Join(lines, "")
-       if have != want {
-               t.Errorf("reduced output:<<<\n%s>>> want:<<<\n%s>>>", have, want)
-       }
- }
- func TestListTests(t *testing.T) {
-       tooSlow(t)
-       var tg *testgoData
-       testWith := func(listName, expected string) func(*testing.T) {
-               return func(t *testing.T) {
-                       tg = testgo(t)
-                       defer tg.cleanup()
-                       tg.run("test", "./testdata/src/testlist/...", fmt.Sprintf("-list=%s", listName))
-                       tg.grepStdout(expected, fmt.Sprintf("-test.list=%s returned %q, expected %s", listName, tg.getStdout(), expected))
-               }
-       }
-       t.Run("Test", testWith("Test", "TestSimple"))
-       t.Run("Bench", testWith("Benchmark", "BenchmarkSimple"))
-       t.Run("Example1", testWith("Example", "ExampleSimple"))
-       t.Run("Example2", testWith("Example", "ExampleWithEmptyOutput"))
- }
  func TestBuildmodePIE(t *testing.T) {
        if testing.Short() && testenv.Builder() == "" {
                t.Skipf("skipping in -short mode on non-builder")
        switch platform {
        case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64le", "linux/s390x",
                "android/amd64", "android/arm", "android/arm64", "android/386",
-               "freebsd/amd64":
+               "freebsd/amd64",
+               "windows/386", "windows/amd64", "windows/arm":
        case "darwin/amd64":
        default:
                t.Skipf("skipping test because buildmode=pie is not supported on %s", platform)
        }
+       t.Run("non-cgo", func(t *testing.T) {
+               testBuildmodePIE(t, false)
+       })
+       if canCgo {
+               switch runtime.GOOS {
+               case "darwin", "freebsd", "linux", "windows":
+                       t.Run("cgo", func(t *testing.T) {
+                               testBuildmodePIE(t, true)
+                       })
+               }
+       }
+ }
  
+ func testBuildmodePIE(t *testing.T, useCgo bool) {
        tg := testgo(t)
        defer tg.cleanup()
+       tg.parallel()
  
-       tg.tempFile("main.go", `package main; func main() { print("hello") }`)
+       var s string
+       if useCgo {
+               s = `import "C";`
+       }
+       tg.tempFile("main.go", fmt.Sprintf(`package main;%s func main() { print("hello") }`, s))
        src := tg.path("main.go")
-       obj := tg.path("main")
+       obj := tg.path("main.exe")
        tg.run("build", "-buildmode=pie", "-o", obj, src)
  
        switch runtime.GOOS {
                if f.Flags&macho.FlagPIE == 0 {
                        t.Error("PIE must have PIE flag, but not")
                }
+       case "windows":
+               f, err := pe.Open(obj)
+               if err != nil {
+                       t.Fatal(err)
+               }
+               defer f.Close()
+               if f.Section(".reloc") == nil {
+                       t.Error(".reloc section is not present")
+               }
+               if (f.FileHeader.Characteristics & pe.IMAGE_FILE_RELOCS_STRIPPED) != 0 {
+                       t.Error("IMAGE_FILE_RELOCS_STRIPPED flag is set")
+               }
+               var dc uint16
+               switch oh := f.OptionalHeader.(type) {
+               case *pe.OptionalHeader32:
+                       dc = oh.DllCharacteristics
+               case *pe.OptionalHeader64:
+                       dc = oh.DllCharacteristics
+                       if (dc & pe.IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA) == 0 {
+                               t.Error("IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA flag is not set")
+                       }
+               default:
+                       t.Fatalf("unexpected optional header type of %T", f.OptionalHeader)
+               }
+               if (dc & pe.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE) == 0 {
+                       t.Error("IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE flag is not set")
+               }
        default:
                panic("unreachable")
        }
        }
  }
  
- func TestExecBuildX(t *testing.T) {
-       tooSlow(t)
-       if !canCgo {
-               t.Skip("skipping because cgo not enabled")
-       }
-       testenv.MustHaveExecPath(t, "/usr/bin/env")
-       testenv.MustHaveExecPath(t, "bash")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.tempDir("cache")
-       tg.setenv("GOCACHE", tg.path("cache"))
-       // Before building our test main.go, ensure that an up-to-date copy of
-       // runtime/cgo is present in the cache. If it isn't, the 'go build' step below
-       // will fail with "can't open import". See golang.org/issue/29004.
-       tg.run("build", "runtime/cgo")
-       tg.tempFile("main.go", `package main; import "C"; func main() { print("hello") }`)
-       src := tg.path("main.go")
-       obj := tg.path("main")
-       tg.run("build", "-x", "-o", obj, src)
-       sh := tg.path("test.sh")
-       cmds := tg.getStderr()
-       err := ioutil.WriteFile(sh, []byte("set -e\n"+cmds), 0666)
-       if err != nil {
-               t.Fatal(err)
-       }
-       out, err := exec.Command(obj).CombinedOutput()
-       if err != nil {
-               t.Fatal(err)
-       }
-       if string(out) != "hello" {
-               t.Fatalf("got %q; want %q", out, "hello")
-       }
-       err = os.Remove(obj)
-       if err != nil {
-               t.Fatal(err)
-       }
-       out, err = exec.Command("/usr/bin/env", "bash", "-x", sh).CombinedOutput()
-       if err != nil {
-               t.Fatalf("/bin/sh %s: %v\n%s", sh, err, out)
-       }
-       t.Logf("shell output:\n%s", out)
-       out, err = exec.Command(obj).CombinedOutput()
-       if err != nil {
-               t.Fatal(err)
-       }
-       if string(out) != "hello" {
-               t.Fatalf("got %q; want %q", out, "hello")
-       }
-       matches := regexp.MustCompile(`^WORK=(.*)\n`).FindStringSubmatch(cmds)
-       if len(matches) == 0 {
-               t.Fatal("no WORK directory")
-       }
-       tg.must(robustio.RemoveAll(matches[1]))
- }
- func TestParallelNumber(t *testing.T) {
-       tooSlow(t)
-       for _, n := range [...]string{"-1", "0"} {
-               t.Run(n, func(t *testing.T) {
-                       tg := testgo(t)
-                       defer tg.cleanup()
-                       tg.runFail("test", "-parallel", n, "testdata/standalone_parallel_sub_test.go")
-                       tg.grepBoth("-parallel can only be given", "go test -parallel with N<1 did not error")
-               })
-       }
- }
- func TestWrongGOOSErrorBeforeLoadError(t *testing.T) {
-       skipIfGccgo(t, "gccgo assumes cross-compilation is always possible")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.setenv("GOOS", "windwos")
-       tg.runFail("build", "exclude")
-       tg.grepStderr("unsupported GOOS/GOARCH pair", "GOOS=windwos go build exclude did not report 'unsupported GOOS/GOARCH pair'")
- }
  func TestUpxCompression(t *testing.T) {
        if runtime.GOOS != "linux" ||
                (runtime.GOARCH != "amd64" && runtime.GOARCH != "386") {
  
        tg := testgo(t)
        defer tg.cleanup()
+       tg.parallel()
  
        tg.tempFile("main.go", `package main; import "fmt"; func main() { fmt.Print("hello upx") }`)
        src := tg.path("main.go")
@@@ -5222,38 -2314,6 +2322,6 @@@ func TestCacheCoverage(t *testing.T) 
        tg.run("test", "-cover", "-short", "math", "strings")
  }
  
- func TestCacheVet(t *testing.T) {
-       skipIfGccgo(t, "gccgo has no standard packages")
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
-               t.Skip("GODEBUG gocacheverify")
-       }
-       if testing.Short() {
-               // In short mode, reuse cache.
-               // Test failures may be masked if the cache has just the right entries already
-               // (not a concern during all.bash, which runs in a clean cache).
-               if cfg.Getenv("GOCACHE") == "off" {
-                       tooSlow(t)
-               }
-       } else {
-               tg.makeTempdir()
-               tg.setenv("GOCACHE", tg.path("cache"))
-       }
-       // Check that second vet reuses cgo-derived inputs.
-       // The first command could be build instead of vet,
-       // except that if the cache is empty and there's a net.a
-       // in GOROOT/pkg, the build will not bother to regenerate
-       // and cache the cgo outputs, whereas vet always will.
-       tg.run("vet", "os/user")
-       tg.run("vet", "-x", "os/user")
-       tg.grepStderrNot(`^(clang|gcc)`, "should not have run compiler")
-       tg.grepStderrNot(`[\\/]cgo `, "should not have run cgo")
- }
  func TestIssue22588(t *testing.T) {
        // Don't get confused by stderr coming from tools.
        tg := testgo(t)
@@@ -5340,30 -2400,6 +2408,6 @@@ func TestTestCache(t *testing.T) 
        tg.setenv("GOPATH", tg.tempdir)
        tg.setenv("GOCACHE", tg.path("cache"))
  
-       if runtime.Compiler != "gccgo" {
-               // timeout here should not affect result being cached
-               // or being retrieved later.
-               tg.run("test", "-x", "-timeout=10s", "errors")
-               tg.grepStderr(`[\\/]compile|gccgo`, "did not run compiler")
-               tg.grepStderr(`[\\/]link|gccgo`, "did not run linker")
-               tg.grepStderr(`errors\.test`, "did not run test")
-               tg.run("test", "-x", "errors")
-               tg.grepStdout(`ok  \terrors\t\(cached\)`, "did not report cached result")
-               tg.grepStderrNot(`[\\/]compile|gccgo`, "incorrectly ran compiler")
-               tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly ran linker")
-               tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
-               tg.grepStderrNot("DO NOT USE", "poisoned action status leaked")
-               // Even very low timeouts do not disqualify cached entries.
-               tg.run("test", "-timeout=1ns", "-x", "errors")
-               tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
-               tg.run("clean", "-testcache")
-               tg.run("test", "-x", "errors")
-               tg.grepStderr(`errors\.test`, "did not run test")
-       }
        // The -p=1 in the commands below just makes the -x output easier to read.
  
        t.Log("\n\nINITIAL\n\n")
        }
  }
  
- func TestTestCacheInputs(t *testing.T) {
-       tooSlow(t)
-       if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
-               t.Skip("GODEBUG gocacheverify")
-       }
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.makeTempdir()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.setenv("GOCACHE", tg.path("cache"))
-       defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"))
-       defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"))
-       tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("x"), 0644))
-       old := time.Now().Add(-1 * time.Minute)
-       tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old, old))
-       info, err := os.Stat(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"))
-       if err != nil {
-               t.Fatal(err)
-       }
-       t.Logf("file.txt: old=%v, info.ModTime=%v", old, info.ModTime()) // help debug when Chtimes lies about succeeding
-       tg.setenv("TESTKEY", "x")
-       tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), []byte("#!/bin/sh\nexit 0\n"), 0755))
-       tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), old, old))
-       tg.run("test", "testcache")
-       tg.run("test", "testcache")
-       tg.grepStdout(`\(cached\)`, "did not cache")
-       tg.setenv("TESTKEY", "y")
-       tg.run("test", "testcache")
-       tg.grepStdoutNot(`\(cached\)`, "did not notice env var change")
-       tg.run("test", "testcache")
-       tg.grepStdout(`\(cached\)`, "did not cache")
-       tg.run("test", "testcache", "-run=FileSize")
-       tg.run("test", "testcache", "-run=FileSize")
-       tg.grepStdout(`\(cached\)`, "did not cache")
-       tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("xxx"), 0644))
-       tg.run("test", "testcache", "-run=FileSize")
-       tg.grepStdoutNot(`\(cached\)`, "did not notice file size change")
-       tg.run("test", "testcache", "-run=FileSize")
-       tg.grepStdout(`\(cached\)`, "did not cache")
-       tg.run("test", "testcache", "-run=Chdir")
-       tg.run("test", "testcache", "-run=Chdir")
-       tg.grepStdout(`\(cached\)`, "did not cache")
-       tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("xxxxx"), 0644))
-       tg.run("test", "testcache", "-run=Chdir")
-       tg.grepStdoutNot(`\(cached\)`, "did not notice file size change")
-       tg.run("test", "testcache", "-run=Chdir")
-       tg.grepStdout(`\(cached\)`, "did not cache")
-       tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old, old))
-       tg.run("test", "testcache", "-run=FileContent")
-       tg.run("test", "testcache", "-run=FileContent")
-       tg.grepStdout(`\(cached\)`, "did not cache")
-       tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("yyy"), 0644))
-       old2 := old.Add(10 * time.Second)
-       tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old2, old2))
-       tg.run("test", "testcache", "-run=FileContent")
-       tg.grepStdoutNot(`\(cached\)`, "did not notice file content change")
-       tg.run("test", "testcache", "-run=FileContent")
-       tg.grepStdout(`\(cached\)`, "did not cache")
-       tg.run("test", "testcache", "-run=DirList")
-       tg.run("test", "testcache", "-run=DirList")
-       tg.grepStdout(`\(cached\)`, "did not cache")
-       tg.must(os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt")))
-       tg.run("test", "testcache", "-run=DirList")
-       tg.grepStdoutNot(`\(cached\)`, "did not notice directory change")
-       tg.run("test", "testcache", "-run=DirList")
-       tg.grepStdout(`\(cached\)`, "did not cache")
-       tg.tempFile("file.txt", "")
-       tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/testcachetmp_test.go"), []byte(`package testcache
-               import (
-                       "os"
-                       "testing"
-               )
-               func TestExternalFile(t *testing.T) {
-                       os.Open(`+fmt.Sprintf("%q", tg.path("file.txt"))+`)
-                       _, err := os.Stat(`+fmt.Sprintf("%q", tg.path("file.txt"))+`)
-                       if err != nil {
-                               t.Fatal(err)
-                       }
-               }
-       `), 0666))
-       defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/testcachetmp_test.go"))
-       tg.run("test", "testcache", "-run=ExternalFile")
-       tg.run("test", "testcache", "-run=ExternalFile")
-       tg.grepStdout(`\(cached\)`, "did not cache")
-       tg.must(os.Remove(filepath.Join(tg.tempdir, "file.txt")))
-       tg.run("test", "testcache", "-run=ExternalFile")
-       tg.grepStdout(`\(cached\)`, "did not cache")
-       switch runtime.GOOS {
-       case "plan9", "windows":
-               // no shell scripts
-       default:
-               tg.run("test", "testcache", "-run=Exec")
-               tg.run("test", "testcache", "-run=Exec")
-               tg.grepStdout(`\(cached\)`, "did not cache")
-               tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), old2, old2))
-               tg.run("test", "testcache", "-run=Exec")
-               tg.grepStdoutNot(`\(cached\)`, "did not notice script change")
-               tg.run("test", "testcache", "-run=Exec")
-               tg.grepStdout(`\(cached\)`, "did not cache")
-       }
- }
- func TestTestVet(t *testing.T) {
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.tempFile("p1_test.go", `
-               package p
-               import "testing"
-               func Test(t *testing.T) {
-                       t.Logf("%d") // oops
-               }
-       `)
-       tg.runFail("test", tg.path("p1_test.go"))
-       tg.grepStderr(`Logf format %d`, "did not diagnose bad Logf")
-       tg.run("test", "-vet=off", tg.path("p1_test.go"))
-       tg.grepStdout(`^ok`, "did not print test summary")
-       tg.tempFile("p1.go", `
-               package p
-               import "fmt"
-               func F() {
-                       fmt.Printf("%d") // oops
-               }
-       `)
-       tg.runFail("test", tg.path("p1.go"))
-       tg.grepStderr(`Printf format %d`, "did not diagnose bad Printf")
-       tg.run("test", "-x", "-vet=shift", tg.path("p1.go"))
-       tg.grepStderr(`[\\/]vet.*-shift`, "did not run vet with -shift")
-       tg.grepStdout(`\[no test files\]`, "did not print test summary")
-       tg.run("test", "-vet=off", tg.path("p1.go"))
-       tg.grepStdout(`\[no test files\]`, "did not print test summary")
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("test", "vetcycle") // must not fail; #22890
-       tg.runFail("test", "vetfail/...")
-       tg.grepStderr(`Printf format %d`, "did not diagnose bad Printf")
-       tg.grepStdout(`ok\s+vetfail/p2`, "did not run vetfail/p2")
-       // Use -a so that we need to recompute the vet-specific export data for
-       // vetfail/p1.
-       tg.run("test", "-a", "vetfail/p2")
-       tg.grepStderrNot(`invalid.*constraint`, "did diagnose bad build constraint in vetxonly mode")
- }
  func TestTestSkipVetAfterFailedBuild(t *testing.T) {
        tg := testgo(t)
        defer tg.cleanup()
@@@ -5701,100 -2574,6 +2582,6 @@@ func TestInstallDeps(t *testing.T) 
        tg.mustExist(p1)
  }
  
- func TestGoTestMinusN(t *testing.T) {
-       // Intent here is to verify that 'go test -n' works without crashing.
-       // This reuses flag_test.go, but really any test would do.
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.run("test", "testdata/flag_test.go", "-n", "-args", "-v=7")
- }
- func TestGoTestJSON(t *testing.T) {
-       skipIfGccgo(t, "gccgo does not have standard packages")
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.makeTempdir()
-       tg.setenv("GOCACHE", tg.tempdir)
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       // It would be nice to test that the output is interlaced
-       // but it seems to be impossible to do that in a short test
-       // that isn't also flaky. Just check that we get JSON output.
-       tg.run("test", "-json", "-short", "-v", "errors", "empty/pkg", "skipper")
-       tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
-       tg.grepStdout(`"Action":"run"`, "did not see JSON output")
-       tg.grepStdout(`"Action":"output","Package":"empty/pkg","Output":".*no test files`, "did not see no test files print")
-       tg.grepStdout(`"Action":"skip","Package":"empty/pkg"`, "did not see skip")
-       tg.grepStdout(`"Action":"output","Package":"skipper","Test":"Test","Output":"--- SKIP:`, "did not see SKIP output")
-       tg.grepStdout(`"Action":"skip","Package":"skipper","Test":"Test"`, "did not see skip result for Test")
-       tg.run("test", "-json", "-short", "-v", "errors")
-       tg.grepStdout(`"Action":"output","Package":"errors","Output":".*\(cached\)`, "did not see no cached output")
-       tg.run("test", "-json", "-bench=NONE", "-short", "-v", "errors")
-       tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
-       tg.grepStdout(`"Action":"run"`, "did not see JSON output")
-       tg.run("test", "-o", tg.path("errors.test.exe"), "-c", "errors")
-       tg.run("tool", "test2json", "-p", "errors", tg.path("errors.test.exe"), "-test.v", "-test.short")
-       tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
-       tg.grepStdout(`"Action":"run"`, "did not see JSON output")
-       tg.grepStdout(`\{"Action":"pass","Package":"errors"\}`, "did not see final pass")
- }
- func TestFailFast(t *testing.T) {
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tests := []struct {
-               run      string
-               failfast bool
-               nfail    int
-       }{
-               {"TestFailingA", true, 1},
-               {"TestFailing[AB]", true, 1},
-               {"TestFailing[AB]", false, 2},
-               // mix with non-failing tests:
-               {"TestA|TestFailing[AB]", true, 1},
-               {"TestA|TestFailing[AB]", false, 2},
-               // mix with parallel tests:
-               {"TestFailingB|TestParallelFailingA", true, 2},
-               {"TestFailingB|TestParallelFailingA", false, 2},
-               {"TestFailingB|TestParallelFailing[AB]", true, 3},
-               {"TestFailingB|TestParallelFailing[AB]", false, 3},
-               // mix with parallel sub-tests
-               {"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", true, 3},
-               {"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", false, 5},
-               {"TestParallelFailingSubtestsA", true, 1},
-               // only parallels:
-               {"TestParallelFailing[AB]", false, 2},
-               // non-parallel subtests:
-               {"TestFailingSubtestsA", true, 1},
-               {"TestFailingSubtestsA", false, 2},
-               // fatal test
-               {"TestFatal[CD]", true, 1},
-               {"TestFatal[CD]", false, 2},
-       }
-       for _, tt := range tests {
-               t.Run(tt.run, func(t *testing.T) {
-                       tg.runFail("test", "./testdata/src/failfast_test.go", "-run="+tt.run, "-failfast="+strconv.FormatBool(tt.failfast))
-                       nfail := strings.Count(tg.getStdout(), "FAIL - ")
-                       if nfail != tt.nfail {
-                               t.Errorf("go test -run=%s -failfast=%t printed %d FAILs, want %d", tt.run, tt.failfast, nfail, tt.nfail)
-                       }
-               })
-       }
- }
  // Issue 22986.
  func TestImportPath(t *testing.T) {
        tooSlow(t)
@@@ -5846,6 -2625,7 +2633,7 @@@ func init() {
  func TestBadCommandLines(t *testing.T) {
        tg := testgo(t)
        defer tg.cleanup()
+       tg.parallel()
  
        tg.tempFile("src/x/x.go", "package x\n")
        tg.setenv("GOPATH", tg.path("."))
        tg.tempFile("src/-x/x.go", "package x\n")
        tg.setenv("GOPATH", tg.path("."))
        tg.runFail("build", "--", "-x")
-       tg.grepStderr("invalid input directory name \"-x\"", "did not reject -x directory")
+       tg.grepStderr("invalid import path \"-x\"", "did not reject -x import path")
  
        tg.tempFile("src/-x/y/y.go", "package y\n")
        tg.setenv("GOPATH", tg.path("."))
        tg.grepStderr("invalid import path \"-x/y\"", "did not reject -x/y import path")
  }
  
- func TestBadCgoDirectives(t *testing.T) {
-       if !canCgo {
-               t.Skip("no cgo")
-       }
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.tempFile("src/x/x.go", "package x\n")
-       tg.setenv("GOPATH", tg.path("."))
-       if runtime.Compiler == "gc" {
-               tg.tempFile("src/x/x.go", `package x
-                       //go:cgo_ldflag "-fplugin=foo.so"
-                       import "C"
-               `)
-               tg.runFail("build", "x")
-               tg.grepStderr("//go:cgo_ldflag .* only allowed in cgo-generated code", "did not reject //go:cgo_ldflag directive")
-       }
-       tg.must(os.Remove(tg.path("src/x/x.go")))
-       tg.runFail("build", "x")
-       tg.grepStderr("no Go files", "did not report missing source code")
-       tg.tempFile("src/x/_cgo_yy.go", `package x
-               //go:cgo_ldflag "-fplugin=foo.so"
-               import "C"
-       `)
-       tg.runFail("build", "x")
-       tg.grepStderr("no Go files", "did not report missing source code") // _* files are ignored...
-       if runtime.Compiler == "gc" {
-               tg.runFail("build", tg.path("src/x/_cgo_yy.go")) // ... but if forced, the comment is rejected
-               // Actually, today there is a separate issue that _ files named
-               // on the command line are ignored. Once that is fixed,
-               // we want to see the cgo_ldflag error.
-               tg.grepStderr("//go:cgo_ldflag only allowed in cgo-generated code|no Go files", "did not reject //go:cgo_ldflag directive")
-       }
-       tg.must(os.Remove(tg.path("src/x/_cgo_yy.go")))
-       tg.tempFile("src/x/x.go", "package x\n")
-       tg.tempFile("src/x/y.go", `package x
-               // #cgo CFLAGS: -fplugin=foo.so
-               import "C"
-       `)
-       tg.runFail("build", "x")
-       tg.grepStderr("invalid flag in #cgo CFLAGS: -fplugin=foo.so", "did not reject -fplugin")
-       tg.tempFile("src/x/y.go", `package x
-               // #cgo CFLAGS: -Ibar -fplugin=foo.so
-               import "C"
-       `)
-       tg.runFail("build", "x")
-       tg.grepStderr("invalid flag in #cgo CFLAGS: -fplugin=foo.so", "did not reject -fplugin")
-       tg.tempFile("src/x/y.go", `package x
-               // #cgo pkg-config: -foo
-               import "C"
-       `)
-       tg.runFail("build", "x")
-       tg.grepStderr("invalid pkg-config package name: -foo", "did not reject pkg-config: -foo")
-       tg.tempFile("src/x/y.go", `package x
-               // #cgo pkg-config: @foo
-               import "C"
-       `)
-       tg.runFail("build", "x")
-       tg.grepStderr("invalid pkg-config package name: @foo", "did not reject pkg-config: -foo")
-       tg.tempFile("src/x/y.go", `package x
-               // #cgo CFLAGS: @foo
-               import "C"
-       `)
-       tg.runFail("build", "x")
-       tg.grepStderr("invalid flag in #cgo CFLAGS: @foo", "did not reject @foo flag")
-       tg.tempFile("src/x/y.go", `package x
-               // #cgo CFLAGS: -D
-               import "C"
-       `)
-       tg.runFail("build", "x")
-       tg.grepStderr("invalid flag in #cgo CFLAGS: -D without argument", "did not reject trailing -I flag")
-       // Note that -I @foo is allowed because we rewrite it into -I /path/to/src/@foo
-       // before the check is applied. There's no such rewrite for -D.
-       tg.tempFile("src/x/y.go", `package x
-               // #cgo CFLAGS: -D @foo
-               import "C"
-       `)
-       tg.runFail("build", "x")
-       tg.grepStderr("invalid flag in #cgo CFLAGS: -D @foo", "did not reject -D @foo flag")
-       tg.tempFile("src/x/y.go", `package x
-               // #cgo CFLAGS: -D@foo
-               import "C"
-       `)
-       tg.runFail("build", "x")
-       tg.grepStderr("invalid flag in #cgo CFLAGS: -D@foo", "did not reject -D@foo flag")
-       tg.setenv("CGO_CFLAGS", "-D@foo")
-       tg.tempFile("src/x/y.go", `package x
-               import "C"
-       `)
-       tg.run("build", "-n", "x")
-       tg.grepStderr("-D@foo", "did not find -D@foo in commands")
- }
  func TestTwoPkgConfigs(t *testing.T) {
        if !canCgo {
                t.Skip("no cgo")
@@@ -6066,6 -2734,7 +2742,7 @@@ func TestCgoCache(t *testing.T) 
  func TestFilepathUnderCwdFormat(t *testing.T) {
        tg := testgo(t)
        defer tg.cleanup()
+       tg.parallel()
        tg.run("test", "-x", "-cover", "log")
        tg.grepStderrNot(`\.log\.cover\.go`, "-x output should contain correctly formatted filepath under cwd")
  }
@@@ -6136,62 -2805,6 +2813,6 @@@ func TestLinkerTmpDirIsDeleted(t *testi
        }
  }
  
- func testCDAndGOPATHAreDifferent(tg *testgoData, cd, gopath string) {
-       skipIfGccgo(tg.t, "gccgo does not support -ldflags -X")
-       tg.setenv("GOPATH", gopath)
-       tg.tempDir("dir")
-       exe := tg.path("dir/a.exe")
-       tg.cd(cd)
-       tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked")
-       out, err := exec.Command(exe).CombinedOutput()
-       if err != nil {
-               tg.t.Fatal(err)
-       }
-       if string(out) != "linkXworked\n" {
-               tg.t.Errorf(`incorrect output with GOPATH=%q and CD=%q: expected "linkXworked\n", but have %q`, gopath, cd, string(out))
-       }
- }
- func TestCDAndGOPATHAreDifferent(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       gopath := filepath.Join(tg.pwd(), "testdata")
-       cd := filepath.Join(gopath, "src/my.pkg/main")
-       testCDAndGOPATHAreDifferent(tg, cd, gopath)
-       if runtime.GOOS == "windows" {
-               testCDAndGOPATHAreDifferent(tg, cd, strings.ReplaceAll(gopath, `\`, `/`))
-               testCDAndGOPATHAreDifferent(tg, cd, strings.ToUpper(gopath))
-               testCDAndGOPATHAreDifferent(tg, cd, strings.ToLower(gopath))
-       }
- }
- // Issue 26242.
- func TestGoTestWithoutTests(t *testing.T) {
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("test", "testnorun")
-       tg.grepStdout(`testnorun\t\[no test files\]`, "do not want test to run")
- }
- // Issue 25579.
- func TestGoBuildDashODevNull(t *testing.T) {
-       tooSlow(t)
-       tg := testgo(t)
-       defer tg.cleanup()
-       tg.parallel()
-       tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
-       tg.run("build", "-o", os.DevNull, filepath.Join(tg.pwd(), "testdata", "src", "hello", "hello.go"))
-       tg.mustNotExist("hello")
-       tg.mustNotExist("hello.exe")
- }
  // Issue 25093.
  func TestCoverpkgTestOnly(t *testing.T) {
        skipIfGccgo(t, "gccgo has no cover tool")
index b7ba884da642476d08d79f9ca05efe65263e26e9,6aea54340d71dbb276957bad85de173122556cdd..4bfc291fe00ee02ee934b243bd061a405ef76cfc
@@@ -11,6 -11,7 +11,7 @@@ import 
        "errors"
        "fmt"
        "go/build"
+       "go/scanner"
        "go/token"
        "io/ioutil"
        "os"
@@@ -186,20 -187,17 +187,17 @@@ type PackageInternal struct 
        Gccgoflags []string // -gccgoflags for this package
  }
  
+ // A NoGoError indicates that no Go files for the package were applicable to the
+ // build for that package.
+ //
+ // That may be because there were no files whatsoever, or because all files were
+ // excluded, or because all non-excluded files were test sources.
  type NoGoError struct {
        Package *Package
  }
  
  func (e *NoGoError) Error() string {
-       // Count files beginning with _ and ., which we will pretend don't exist at all.
-       dummy := 0
-       for _, name := range e.Package.IgnoredGoFiles {
-               if strings.HasPrefix(name, "_") || strings.HasPrefix(name, ".") {
-                       dummy++
-               }
-       }
-       if len(e.Package.IgnoredGoFiles) > dummy {
+       if len(e.Package.constraintIgnoredGoFiles()) > 0 {
                // Go files exist, but they were ignored due to build constraints.
                return "build constraints exclude all Go files in " + e.Package.Dir
        }
        return "no Go files in " + e.Package.Dir
  }
  
+ // rewordError returns a version of err with trivial layers removed and
+ // (possibly-wrapped) instances of build.NoGoError replaced with load.NoGoError,
+ // which more clearly distinguishes sub-cases.
+ func (p *Package) rewordError(err error) error {
+       if mErr, ok := err.(*search.MatchError); ok && mErr.Match.IsLiteral() {
+               err = mErr.Err
+       }
+       var noGo *build.NoGoError
+       if errors.As(err, &noGo) {
+               if p.Dir == "" && noGo.Dir != "" {
+                       p.Dir = noGo.Dir
+               }
+               err = &NoGoError{Package: p}
+       }
+       return err
+ }
  // Resolve returns the resolved version of imports,
  // which should be p.TestImports or p.XTestImports, NOT p.Imports.
  // The imports in p.TestImports and p.XTestImports are not recursively
@@@ -279,12 -294,6 +294,12 @@@ func (p *Package) copyBuild(pp *build.P
        p.SwigFiles = pp.SwigFiles
        p.SwigCXXFiles = pp.SwigCXXFiles
        p.SysoFiles = pp.SysoFiles
 +      if cfg.BuildMSan {
 +              // There's no way for .syso files to be built both with and without
 +              // support for memory sanitizer. Assume they are built without,
 +              // and drop them.
 +              p.SysoFiles = nil
 +      }
        p.CgoCFLAGS = pp.CgoCFLAGS
        p.CgoCPPFLAGS = pp.CgoCPPFLAGS
        p.CgoCXXFLAGS = pp.CgoCXXFLAGS
  
  // A PackageError describes an error loading information about a package.
  type PackageError struct {
-       ImportStack   []string // shortest path from package named on command line to this one
-       Pos           string   // position of error
-       Err           error    // the error itself
-       IsImportCycle bool     // the error is an import cycle
-       Hard          bool     // whether the error is soft or hard; soft errors are ignored in some places
+       ImportStack      []string // shortest path from package named on command line to this one
+       Pos              string   // position of error
+       Err              error    // the error itself
+       IsImportCycle    bool     // the error is an import cycle
+       Hard             bool     // whether the error is soft or hard; soft errors are ignored in some places
+       alwaysPrintStack bool     // whether to always print the ImportStack
  }
  
  func (p *PackageError) Error() string {
-       // Import cycles deserve special treatment.
-       if p.IsImportCycle {
-               return fmt.Sprintf("%s\npackage %s\n", p.Err, strings.Join(p.ImportStack, "\n\timports "))
-       }
-       if p.Pos != "" {
+       if p.Pos != "" && (len(p.ImportStack) == 0 || !p.alwaysPrintStack) {
                // Omit import stack. The full path to the file where the error
                // is the most important thing.
                return p.Pos + ": " + p.Err.Error()
        // last path on the stack, we don't omit the path. An error like
        // "package A imports B: error loading C caused by B" would not be clearer
        // if "imports B" were omitted.
-       stack := p.ImportStack
-       var ierr ImportPathError
-       if len(stack) > 0 && errors.As(p.Err, &ierr) && ierr.ImportPath() == stack[len(stack)-1] {
-               stack = stack[:len(stack)-1]
-       }
-       if len(stack) == 0 {
+       if len(p.ImportStack) == 0 {
                return p.Err.Error()
        }
-       return "package " + strings.Join(stack, "\n\timports ") + ": " + p.Err.Error()
+       var optpos string
+       if p.Pos != "" {
+               optpos = "\n\t" + p.Pos
+       }
+       return "package " + strings.Join(p.ImportStack, "\n\timports ") + optpos + ": " + p.Err.Error()
  }
  
+ func (p *PackageError) Unwrap() error { return p.Err }
  // PackageError implements MarshalJSON so that Err is marshaled as a string
  // and non-essential fields are omitted.
  func (p *PackageError) MarshalJSON() ([]byte, error) {
@@@ -541,9 -548,6 +554,6 @@@ func loadImport(pre *preload, path, src
                panic("LoadImport called with empty package path")
        }
  
-       stk.Push(path)
-       defer stk.Pop()
        var parentPath, parentRoot string
        parentIsStd := false
        if parent != nil {
                pre.preloadImports(bp.Imports, bp)
        }
        if bp == nil {
+               if importErr, ok := err.(ImportPathError); !ok || importErr.ImportPath() != path {
+                       // Only add path to the error's import stack if it's not already present on the error.
+                       stk.Push(path)
+                       defer stk.Pop()
+               }
                return &Package{
                        PackagePublic: PackagePublic{
                                ImportPath: path,
        importPath := bp.ImportPath
        p := packageCache[importPath]
        if p != nil {
+               stk.Push(path)
                p = reusePackage(p, stk)
+               stk.Pop()
        } else {
                p = new(Package)
                p.Internal.Local = build.IsLocalImport(path)
                // Load package.
                // loadPackageData may return bp != nil even if an error occurs,
                // in order to return partial information.
-               p.load(stk, bp, err)
-               if p.Error != nil && p.Error.Pos == "" {
+               p.load(path, stk, bp, err)
+               // Add position information unless this is a NoGoError or an ImportCycle error.
+               // Import cycles deserve special treatment.
+               var g *build.NoGoError
+               if p.Error != nil && p.Error.Pos == "" && !errors.As(err, &g) && !p.Error.IsImportCycle {
                        p = setErrorPos(p, importPos)
                }
  
                if !cfg.ModulesEnabled && path != cleanImport(path) {
                        p.Error = &PackageError{
                                ImportStack: stk.Copy(),
-                               Err:         fmt.Errorf("non-canonical import path: %q should be %q", path, pathpkg.Clean(path)),
+                               Err:         ImportErrorf(path, "non-canonical import path %q: should be %q", path, pathpkg.Clean(path)),
                        }
                        p.Incomplete = true
+                       setErrorPos(p, importPos)
                }
        }
  
                return setErrorPos(perr, importPos)
        }
        if mode&ResolveImport != 0 {
-               if perr := disallowVendor(srcDir, path, p, stk); perr != p {
+               if perr := disallowVendor(srcDir, path, parentPath, p, stk); perr != p {
                        return setErrorPos(perr, importPos)
                }
        }
@@@ -676,6 -691,11 +697,11 @@@ func loadPackageData(path, parentPath, 
        // we create from the full directory to the package.
        // Otherwise it is the usual import path.
        // For vendored imports, it is the expanded form.
+       //
+       // Note that when modules are enabled, local import paths are normally
+       // canonicalized by modload.ImportPaths before now. However, if there's an
+       // error resolving a local path, it will be returned untransformed
+       // so that 'go list -e' reports something useful.
        importKey := importSpec{
                path:        path,
                parentPath:  parentPath,
@@@ -1232,7 -1252,7 +1258,7 @@@ func disallowInternal(srcDir string, im
        // as if it were generated into the testing directory tree
        // (it's actually in a temporary directory outside any Go tree).
        // This cleans up a former kludge in passing functionality to the testing package.
-       if strings.HasPrefix(p.ImportPath, "testing/internal") && len(*stk) >= 2 && (*stk)[len(*stk)-2] == "testmain" {
+       if str.HasPathPrefix(p.ImportPath, "testing/internal") && importerPath == "testmain" {
                return p
        }
  
                return p
        }
  
-       // The stack includes p.ImportPath.
-       // If that's the only thing on the stack, we started
+       // importerPath is empty: we started
        // with a name given on the command line, not an
        // import. Anything listed on the command line is fine.
-       if len(*stk) == 1 {
+       if importerPath == "" {
                return p
        }
  
        // Internal is present, and srcDir is outside parent's tree. Not allowed.
        perr := *p
        perr.Error = &PackageError{
-               ImportStack: stk.Copy(),
-               Err:         ImportErrorf(p.ImportPath, "use of internal package "+p.ImportPath+" not allowed"),
+               alwaysPrintStack: true,
+               ImportStack:      stk.Copy(),
+               Err:              ImportErrorf(p.ImportPath, "use of internal package "+p.ImportPath+" not allowed"),
        }
        perr.Incomplete = true
        return &perr
@@@ -1330,16 -1350,15 +1356,15 @@@ func findInternal(path string) (index i
  // disallowVendor checks that srcDir is allowed to import p as path.
  // If the import is allowed, disallowVendor returns the original package p.
  // If not, it returns a new package containing just an appropriate error.
- func disallowVendor(srcDir string, path string, p *Package, stk *ImportStack) *Package {
-       // The stack includes p.ImportPath.
-       // If that's the only thing on the stack, we started
+ func disallowVendor(srcDir string, path string, importerPath string, p *Package, stk *ImportStack) *Package {
+       // If the importerPath is empty, we started
        // with a name given on the command line, not an
        // import. Anything listed on the command line is fine.
-       if len(*stk) == 1 {
+       if importerPath == "" {
                return p
        }
  
-       if perr := disallowVendorVisibility(srcDir, p, stk); perr != p {
+       if perr := disallowVendorVisibility(srcDir, p, importerPath, stk); perr != p {
                return perr
        }
  
  // is not subject to the rules, only subdirectories of vendor.
  // This allows people to have packages and commands named vendor,
  // for maximal compatibility with existing source trees.
- func disallowVendorVisibility(srcDir string, p *Package, stk *ImportStack) *Package {
-       // The stack includes p.ImportPath.
-       // If that's the only thing on the stack, we started
+ func disallowVendorVisibility(srcDir string, p *Package, importerPath string, stk *ImportStack) *Package {
+       // The stack does not include p.ImportPath.
+       // If there's nothing on the stack, we started
        // with a name given on the command line, not an
        // import. Anything listed on the command line is fine.
-       if len(*stk) == 1 {
+       if importerPath == "" {
                return p
        }
  
@@@ -1511,7 -1530,8 +1536,8 @@@ func (p *Package) DefaultExecName() str
  
  // load populates p using information from bp, err, which should
  // be the result of calling build.Context.Import.
- func (p *Package) load(stk *ImportStack, bp *build.Package, err error) {
+ // stk contains the import stack, not including path itself.
+ func (p *Package) load(path string, stk *ImportStack, bp *build.Package, err error) {
        p.copyBuild(bp)
  
        // The localPrefix is the path we interpret ./ imports relative to.
                p.Internal.LocalPrefix = dirToImportPath(p.Dir)
        }
  
-       if err != nil {
-               if _, ok := err.(*build.NoGoError); ok {
-                       err = &NoGoError{Package: p}
+       // setError sets p.Error if it hasn't already been set. We may proceed
+       // after encountering some errors so that 'go list -e' has more complete
+       // output. If there's more than one error, we should report the first.
+       setError := func(err error) {
+               if p.Error == nil {
+                       p.Error = &PackageError{
+                               ImportStack: stk.Copy(),
+                               Err:         err,
+                       }
                }
+       }
+       if err != nil {
                p.Incomplete = true
-               err = base.ExpandScanner(err)
-               p.Error = &PackageError{
-                       ImportStack: stk.Copy(),
-                       Err:         err,
+               // Report path in error stack unless err is an ImportPathError with path already set.
+               pushed := false
+               if e, ok := err.(ImportPathError); !ok || e.ImportPath() != path {
+                       stk.Push(path)
+                       pushed = true // Remember to pop after setError.
                }
-               return
+               setError(base.ExpandScanner(p.rewordError(err)))
+               if pushed {
+                       stk.Pop()
+               }
+               if _, isScanErr := err.(scanner.ErrorList); !isScanErr {
+                       return
+               }
+               // Fall through if there was an error parsing a file. 'go list -e' should
+               // still report imports and other metadata.
        }
  
        useBindir := p.Name == "main"
                if InstallTargetDir(p) == StalePath {
                        newPath := strings.Replace(p.ImportPath, "code.google.com/p/go.", "golang.org/x/", 1)
                        e := ImportErrorf(p.ImportPath, "the %v command has moved; use %v instead.", p.ImportPath, newPath)
-                       p.Error = &PackageError{Err: e}
+                       setError(e)
                        return
                }
                elem := p.DefaultExecName()
                p.Target = ""
        } else {
                p.Target = p.Internal.Build.PkgObj
-               if cfg.BuildLinkshared {
+               if cfg.BuildLinkshared && p.Target != "" {
+                       // TODO(bcmills): The reliance on p.Target implies that -linkshared does
+                       // not work for any package that lacks a Target â€” such as a non-main
+                       // package in module mode. We should probably fix that.
                        shlibnamefile := p.Target[:len(p.Target)-2] + ".shlibname"
                        shlib, err := ioutil.ReadFile(shlibnamefile)
                        if err != nil && !os.IsNotExist(err) {
                }
        }
  
+       // Check for case-insensitive collisions of import paths.
+       fold := str.ToFold(p.ImportPath)
+       if other := foldPath[fold]; other == "" {
+               foldPath[fold] = p.ImportPath
+       } else if other != p.ImportPath {
+               setError(ImportErrorf(p.ImportPath, "case-insensitive import collision: %q and %q", p.ImportPath, other))
+               return
+       }
+       if !SafeArg(p.ImportPath) {
+               setError(ImportErrorf(p.ImportPath, "invalid import path %q", p.ImportPath))
+               return
+       }
+       stk.Push(path)
+       defer stk.Pop()
        // Check for case-insensitive collision of input files.
        // To avoid problems on case-insensitive files, we reject any package
        // where two different input files have equal names under a case-insensitive
        inputs := p.AllFiles()
        f1, f2 := str.FoldDup(inputs)
        if f1 != "" {
-               p.Error = &PackageError{
-                       ImportStack: stk.Copy(),
-                       Err:         fmt.Errorf("case-insensitive file name collision: %q and %q", f1, f2),
-               }
+               setError(fmt.Errorf("case-insensitive file name collision: %q and %q", f1, f2))
                return
        }
  
        // so we shouldn't see any _cgo_ files anyway, but just be safe.
        for _, file := range inputs {
                if !SafeArg(file) || strings.HasPrefix(file, "_cgo_") {
-                       p.Error = &PackageError{
-                               ImportStack: stk.Copy(),
-                               Err:         fmt.Errorf("invalid input file name %q", file),
-                       }
+                       setError(fmt.Errorf("invalid input file name %q", file))
                        return
                }
        }
        if name := pathpkg.Base(p.ImportPath); !SafeArg(name) {
-               p.Error = &PackageError{
-                       ImportStack: stk.Copy(),
-                       Err:         fmt.Errorf("invalid input directory name %q", name),
-               }
-               return
-       }
-       if !SafeArg(p.ImportPath) {
-               p.Error = &PackageError{
-                       ImportStack: stk.Copy(),
-                       Err:         ImportErrorf(p.ImportPath, "invalid import path %q", p.ImportPath),
-               }
+               setError(fmt.Errorf("invalid input directory name %q", name))
                return
        }
  
                // code; see issue #16050).
        }
  
-       setError := func(err error) {
-               p.Error = &PackageError{
-                       ImportStack: stk.Copy(),
-                       Err:         err,
-               }
-       }
        // The gc toolchain only permits C source files with cgo or SWIG.
        if len(p.CFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() && cfg.BuildContext.Compiler == "gc" {
                setError(fmt.Errorf("C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CFiles, " ")))
                return
        }
  
-       // Check for case-insensitive collisions of import paths.
-       fold := str.ToFold(p.ImportPath)
-       if other := foldPath[fold]; other == "" {
-               foldPath[fold] = p.ImportPath
-       } else if other != p.ImportPath {
-               setError(ImportErrorf(p.ImportPath, "case-insensitive import collision: %q and %q", p.ImportPath, other))
-               return
-       }
        if cfg.ModulesEnabled && p.Error == nil {
                mainPath := p.ImportPath
                if p.Internal.CmdlineFiles {
@@@ -1874,7 -1900,9 +1906,9 @@@ func externalLinkingForced(p *Package) 
        // Some targets must use external linking even inside GOROOT.
        switch cfg.BuildContext.GOOS {
        case "android":
-               return true
+               if cfg.BuildContext.GOARCH != "arm64" {
+                       return true
+               }
        case "darwin":
                switch cfg.BuildContext.GOARCH {
                case "arm", "arm64":
@@@ -1935,13 -1963,22 +1969,22 @@@ func (p *Package) InternalXGoFiles() []
  // using absolute paths. "Possibly relevant" means that files are not excluded
  // due to build tags, but files with names beginning with . or _ are still excluded.
  func (p *Package) InternalAllGoFiles() []string {
-       var extra []string
+       return p.mkAbs(str.StringList(p.constraintIgnoredGoFiles(), p.GoFiles, p.CgoFiles, p.TestGoFiles, p.XTestGoFiles))
+ }
+ // constraintIgnoredGoFiles returns the list of Go files ignored for reasons
+ // other than having a name beginning with '.' or '_'.
+ func (p *Package) constraintIgnoredGoFiles() []string {
+       if len(p.IgnoredGoFiles) == 0 {
+               return nil
+       }
+       files := make([]string, 0, len(p.IgnoredGoFiles))
        for _, f := range p.IgnoredGoFiles {
-               if f != "" && f[0] != '.' || f[0] != '_' {
-                       extra = append(extra, f)
+               if f != "" && f[0] != '.' && f[0] != '_' {
+                       files = append(files, f)
                }
        }
-       return p.mkAbs(str.StringList(extra, p.GoFiles, p.CgoFiles, p.TestGoFiles, p.XTestGoFiles))
+       return files
  }
  
  // usesSwig reports whether the package needs to run SWIG.
@@@ -2035,7 -2072,7 +2078,7 @@@ func Packages(args []string) []*Packag
        var pkgs []*Package
        for _, pkg := range PackagesAndErrors(args) {
                if pkg.Error != nil {
-                       base.Errorf("can't load package: %s", pkg.Error)
+                       base.Errorf("%v", pkg.Error)
                        continue
                }
                pkgs = append(pkgs, pkg)
@@@ -2075,13 -2112,13 +2118,13 @@@ func PackagesAndErrors(patterns []strin
        for _, m := range matches {
                for _, pkg := range m.Pkgs {
                        if pkg == "" {
-                               panic(fmt.Sprintf("ImportPaths returned empty package for pattern %s", m.Pattern))
+                               panic(fmt.Sprintf("ImportPaths returned empty package for pattern %s", m.Pattern()))
                        }
                        p := loadImport(pre, pkg, base.Cwd, nil, &stk, nil, 0)
-                       p.Match = append(p.Match, m.Pattern)
+                       p.Match = append(p.Match, m.Pattern())
                        p.Internal.CmdlinePkg = true
-                       if m.Literal {
-                               // Note: do not set = m.Literal unconditionally
+                       if m.IsLiteral() {
+                               // Note: do not set = m.IsLiteral unconditionally
                                // because maybe we'll see p matching both
                                // a literal and also a non-literal pattern.
                                p.Internal.CmdlinePkgLiteral = true
                        seenPkg[p] = true
                        pkgs = append(pkgs, p)
                }
+               if len(m.Errs) > 0 {
+                       // In addition to any packages that were actually resolved from the
+                       // pattern, there was some error in resolving the pattern itself.
+                       // Report it as a synthetic package.
+                       p := new(Package)
+                       p.ImportPath = m.Pattern()
+                       p.Error = &PackageError{
+                               ImportStack: nil, // The error arose from a pattern, not an import.
+                               Err:         p.rewordError(m.Errs[0]),
+                       }
+                       p.Incomplete = true
+                       p.Match = append(p.Match, m.Pattern())
+                       p.Internal.CmdlinePkg = true
+                       if m.IsLiteral() {
+                               p.Internal.CmdlinePkgLiteral = true
+                       }
+                       pkgs = append(pkgs, p)
+               }
        }
  
        // Now that CmdlinePkg is set correctly,
@@@ -2127,7 -2183,7 +2189,7 @@@ func PackagesForBuild(args []string) []
        printed := map[*PackageError]bool{}
        for _, pkg := range pkgs {
                if pkg.Error != nil {
-                       base.Errorf("can't load package: %s", pkg.Error)
+                       base.Errorf("%v", pkg.Error)
                        printed[pkg.Error] = true
                }
                for _, err := range pkg.DepsErrors {
                        // Only print each once.
                        if !printed[err] {
                                printed[err] = true
-                               base.Errorf("%s", err)
+                               base.Errorf("%v", err)
                        }
                }
        }
@@@ -2229,9 -2285,7 +2291,7 @@@ func GoFilesPackage(gofiles []string) *
        pkg := new(Package)
        pkg.Internal.Local = true
        pkg.Internal.CmdlineFiles = true
-       stk.Push("main")
-       pkg.load(&stk, bp, err)
-       stk.Pop()
+       pkg.load("command-line-arguments", &stk, bp, err)
        pkg.Internal.LocalPrefix = dirToImportPath(dir)
        pkg.ImportPath = "command-line-arguments"
        pkg.Target = ""
index 2ce2cf0152b3c31a07665449bb5db86bf62dfeac,a4b4b60ca1f304cf7c0890b8c7e6a00222dbca78..7f1b4b02ef3b19f64ad8bc4aa2dfbce206cceff1
@@@ -101,6 -101,7 +101,7 @@@ type Arch struct 
        Minalign       int
        Dwarfregsp     int
        Dwarfreglr     int
+       Androiddynld   string
        Linuxdynld     string
        Freebsddynld   string
        Netbsddynld    string
@@@ -409,9 -410,6 +410,6 @@@ func (ctxt *Link) loadlib() 
        }
  
        // load internal packages, if not already
-       if ctxt.Arch.Family == sys.ARM {
-               loadinternal(ctxt, "math")
-       }
        if *flagRace {
                loadinternal(ctxt, "runtime/race")
        }
@@@ -970,7 -968,6 +968,7 @@@ var hostobj []Hostob
  // These packages can use internal linking mode.
  // Others trigger external mode.
  var internalpkg = []string{
 +      "crypto/internal/boring",
        "crypto/x509",
        "net",
        "os/user",
@@@ -1261,8 -1258,20 +1259,20 @@@ func (ctxt *Link) hostlink() 
                        }
                }
        case BuildModePIE:
-               // ELF.
-               if ctxt.HeadType != objabi.Hdarwin && ctxt.HeadType != objabi.Haix {
+               switch ctxt.HeadType {
+               case objabi.Hdarwin, objabi.Haix:
+               case objabi.Hwindows:
+                       // Enable ASLR.
+                       argv = append(argv, "-Wl,--dynamicbase")
+                       // enable high-entropy ASLR on 64-bit.
+                       if ctxt.Arch.PtrSize >= 8 {
+                               argv = append(argv, "-Wl,--high-entropy-va")
+                       }
+                       // Work around binutils limitation that strips relocation table for dynamicbase.
+                       // See https://sourceware.org/bugzilla/show_bug.cgi?id=19011
+                       argv = append(argv, "-Wl,--export-all-symbols")
+               default:
+                       // ELF.
                        if ctxt.UseRelro() {
                                argv = append(argv, "-Wl,-z,relro")
                        }
                // from the beginning of the section (like sym.STYPE).
                argv = append(argv, "-Wl,-znocopyreloc")
  
-               if ctxt.Arch.InFamily(sys.ARM, sys.ARM64) && (objabi.GOOS == "linux" || objabi.GOOS == "android") {
+               if ctxt.Arch.InFamily(sys.ARM, sys.ARM64) && objabi.GOOS == "linux" {
                        // On ARM, the GNU linker will generate COPY relocations
                        // even with -znocopyreloc set.
                        // https://sourceware.org/bugzilla/show_bug.cgi?id=19962
index e4e580fada7930a4ca4642f655c0f2507954de63,189399d12646d350517de6d293a9148021842259..d10e354c762b437c0fbd6358de5ec3588c0bb047
@@@ -33,17 -33,14 +33,19 @@@ import 
        "crypto/elliptic"
        "crypto/internal/randutil"
        "crypto/sha512"
-       "encoding/asn1"
        "errors"
        "io"
        "math/big"
+       "golang.org/x/crypto/cryptobyte"
+       "golang.org/x/crypto/cryptobyte/asn1"
  )
  
 +import (
 +      "crypto/internal/boring"
 +      "unsafe"
 +)
 +
  // A invertible implements fast inverse mod Curve.Params().N
  type invertible interface {
        // Inverse returns the inverse of k in GF(P)
@@@ -63,22 -60,32 +65,36 @@@ const 
  type PublicKey struct {
        elliptic.Curve
        X, Y *big.Int
 +
 +      boring unsafe.Pointer
  }
  
+ // Equal reports whether pub and x have the same value.
+ //
+ // Two keys are only considered to have the same value if they have the same Curve value.
+ // Note that for example elliptic.P256() and elliptic.P256().Params() are different
+ // values, as the latter is a generic not constant time implementation.
+ func (pub *PublicKey) Equal(x crypto.PublicKey) bool {
+       xx, ok := x.(*PublicKey)
+       if !ok {
+               return false
+       }
+       return pub.X.Cmp(xx.X) == 0 && pub.Y.Cmp(xx.Y) == 0 &&
+               // Standard library Curve implementations are singletons, so this check
+               // will work for those. Other Curves might be equivalent even if not
+               // singletons, but there is no definitive way to check for that, and
+               // better to err on the side of safety.
+               pub.Curve == xx.Curve
+ }
  // PrivateKey represents an ECDSA private key.
  type PrivateKey struct {
        PublicKey
        D *big.Int
 +
 +      boring unsafe.Pointer
  }
  
- type ecdsaSignature struct {
-       R, S *big.Int
- }
  // Public returns the public key corresponding to priv.
  func (priv *PrivateKey) Public() crypto.PublicKey {
        return &priv.PublicKey
  // where the private part is kept in, for example, a hardware module. Common
  // uses should use the Sign function in this package directly.
  func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
 +      if boring.Enabled && rand == boring.RandReader {
 +              b, err := boringPrivateKey(priv)
 +              if err != nil {
 +                      return nil, err
 +              }
 +              return boring.SignMarshalECDSA(b, digest)
 +      }
 +      boring.UnreachableExceptTests()
 +
        r, s, err := Sign(rand, priv, digest)
        if err != nil {
                return nil, err
        }
  
-       return asn1.Marshal(ecdsaSignature{r, s})
+       var b cryptobyte.Builder
+       b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
+               b.AddASN1BigInt(r)
+               b.AddASN1BigInt(s)
+       })
+       return b.Bytes()
  }
  
  var one = new(big.Int).SetInt64(1)
@@@ -130,15 -133,6 +151,15 @@@ func randFieldElement(c elliptic.Curve
  
  // GenerateKey generates a public and private key pair.
  func GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error) {
 +      if boring.Enabled && rand == boring.RandReader {
 +              x, y, d, err := boring.GenerateKeyECDSA(c.Params().Name)
 +              if err != nil {
 +                      return nil, err
 +              }
 +              return &PrivateKey{PublicKey: PublicKey{Curve: c, X: x, Y: y}, D: d}, nil
 +      }
 +      boring.UnreachableExceptTests()
 +
        k, err := randFieldElement(c, rand)
        if err != nil {
                return nil, err
@@@ -186,21 -180,12 +207,21 @@@ var errZeroParam = errors.New("zero par
  
  // Sign signs a hash (which should be the result of hashing a larger message)
  // using the private key, priv. If the hash is longer than the bit-length of the
- // private key's curve order, the hash will be truncated to that length.  It
+ // private key's curve order, the hash will be truncated to that length. It
  // returns the signature as a pair of integers. The security of the private key
  // depends on the entropy of rand.
  func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {
        randutil.MaybeReadByte(rand)
  
 +      if boring.Enabled && rand == boring.RandReader {
 +              b, err := boringPrivateKey(priv)
 +              if err != nil {
 +                      return nil, nil, err
 +              }
 +              return boring.SignECDSA(b, hash)
 +      }
 +      boring.UnreachableExceptTests()
 +
        // Get min(log2(q) / 2, 256) bits of entropy from rand.
        entropylen := (priv.Curve.Params().BitSize + 7) / 16
        if entropylen > 32 {
        return
  }
  
+ // SignASN1 signs a hash (which should be the result of hashing a larger message)
+ // using the private key, priv. If the hash is longer than the bit-length of the
+ // private key's curve order, the hash will be truncated to that length. It
+ // returns the ASN.1 encoded signature. The security of the private key
+ // depends on the entropy of rand.
+ func SignASN1(rand io.Reader, priv *PrivateKey, hash []byte) ([]byte, error) {
+       return priv.Sign(rand, hash, nil)
+ }
  // Verify verifies the signature in r, s of hash using the public key, pub. Its
  // return value records whether the signature is valid.
  func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool {
 +      if boring.Enabled {
 +              b, err := boringPublicKey(pub)
 +              if err != nil {
 +                      return false
 +              }
 +              return boring.VerifyECDSA(b, hash, r, s)
 +      }
 +      boring.UnreachableExceptTests()
 +
        // See [NSA] 3.4.2
        c := pub.Curve
        N := c.Params().N
        return x.Cmp(r) == 0
  }
  
+ // VerifyASN1 verifies the ASN.1 encoded signature, sig, of hash using the
+ // public key, pub. Its return value records whether the signature is valid.
+ func VerifyASN1(pub *PublicKey, hash, sig []byte) bool {
+       var (
+               r, s  = &big.Int{}, &big.Int{}
+               inner cryptobyte.String
+       )
+       input := cryptobyte.String(sig)
+       if !input.ReadASN1(&inner, asn1.SEQUENCE) ||
+               !input.Empty() ||
+               !inner.ReadASN1Integer(r) ||
+               !inner.ReadASN1Integer(s) ||
+               !inner.Empty() {
+               return false
+       }
+       return Verify(pub, hash, r, s)
+ }
  type zr struct {
        io.Reader
  }
index 6bd16f529daaef5d76ad52c1c4878c20781a9d60,499242ffc5b574196f51eb273925097c7270ec5f..27278cd8dabc187846eedd5e285789e923c92537
@@@ -14,8 -14,6 +14,8 @@@ import 
        "crypto/internal/randutil"
  )
  
 +import "crypto/internal/boring"
 +
  // This file implements encryption and decryption using PKCS#1 v1.5 padding.
  
  // PKCS1v15DecrypterOpts is for passing options to PKCS#1 v1.5 decryption using
@@@ -38,8 -36,8 +38,8 @@@ type PKCS1v15DecryptOptions struct 
  //
  // WARNING: use of this function to encrypt plaintexts other than
  // session keys is dangerous. Use RSA OAEP in new protocols.
 -func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) ([]byte, error) {
 -      randutil.MaybeReadByte(rand)
 +func EncryptPKCS1v15(random io.Reader, pub *PublicKey, msg []byte) ([]byte, error) {
 +      randutil.MaybeReadByte(random)
  
        if err := checkPub(pub); err != nil {
                return nil, err
                return nil, ErrMessageTooLong
        }
  
 +      if boring.Enabled && random == boring.RandReader {
 +              bkey, err := boringPublicKey(pub)
 +              if err != nil {
 +                      return nil, err
 +              }
 +              return boring.EncryptRSAPKCS1(bkey, msg)
 +      }
 +      boring.UnreachableExceptTests()
 +
        // EM = 0x00 || 0x02 || PS || 0x00 || M
        em := make([]byte, k)
        em[1] = 2
        ps, mm := em[2:len(em)-len(msg)-1], em[len(em)-len(msg):]
 -      err := nonZeroRandomBytes(ps, rand)
 +      err := nonZeroRandomBytes(ps, random)
        if err != nil {
                return nil, err
        }
        em[len(em)-len(msg)-1] = 0
        copy(mm, msg)
  
 +      if boring.Enabled {
 +              var bkey *boring.PublicKeyRSA
 +              bkey, err = boringPublicKey(pub)
 +              if err != nil {
 +                      return nil, err
 +              }
 +              return boring.EncryptRSANoPadding(bkey, em)
 +      }
 +
        m := new(big.Int).SetBytes(em)
        c := encrypt(new(big.Int), pub, m)
 -
        copyWithLeftPad(em, c.Bytes())
        return em, nil
  }
@@@ -96,19 -77,6 +96,19 @@@ func DecryptPKCS1v15(rand io.Reader, pr
        if err := checkPub(&priv.PublicKey); err != nil {
                return nil, err
        }
 +
 +      if boring.Enabled {
 +              bkey, err := boringPrivateKey(priv)
 +              if err != nil {
 +                      return nil, err
 +              }
 +              out, err := boring.DecryptRSAPKCS1(bkey, ciphertext)
 +              if err != nil {
 +                      return nil, ErrDecryption
 +              }
 +              return out, nil
 +      }
 +
        valid, out, index, err := decryptPKCS1v15(rand, priv, ciphertext)
        if err != nil {
                return nil, err
@@@ -176,26 -144,13 +176,26 @@@ func decryptPKCS1v15(rand io.Reader, pr
                return
        }
  
 -      c := new(big.Int).SetBytes(ciphertext)
 -      m, err := decrypt(rand, priv, c)
 -      if err != nil {
 -              return
 +      if boring.Enabled {
 +              var bkey *boring.PrivateKeyRSA
 +              bkey, err = boringPrivateKey(priv)
 +              if err != nil {
 +                      return
 +              }
 +              em, err = boring.DecryptRSANoPadding(bkey, ciphertext)
 +              if err != nil {
 +                      return
 +              }
 +      } else {
 +              c := new(big.Int).SetBytes(ciphertext)
 +              var m *big.Int
 +              m, err = decrypt(rand, priv, c)
 +              if err != nil {
 +                      return
 +              }
 +              em = leftPad(m.Bytes(), k)
        }
  
 -      em = leftPad(m.Bytes(), k)
        firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0)
        secondByteIsTwo := subtle.ConstantTimeByteEq(em[1], 2)
  
@@@ -274,7 -229,7 +274,7 @@@ var hashPrefixes = map[crypto.Hash][]by
  // messages is small, an attacker may be able to build a map from
  // messages to signatures and identify the signed messages. As ever,
  // signatures provide authenticity, not confidentiality.
 -func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error) {
 +func SignPKCS1v15(random io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error) {
        hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed))
        if err != nil {
                return nil, err
                return nil, ErrMessageTooLong
        }
  
 +      if boring.Enabled {
 +              bkey, err := boringPrivateKey(priv)
 +              if err != nil {
 +                      return nil, err
 +              }
 +              return boring.SignRSAPKCS1v15(bkey, hash, hashed)
 +      }
 +
        // EM = 0x00 || 0x01 || PS || 0x00 || T
        em := make([]byte, k)
        em[1] = 1
        copy(em[k-hashLen:k], hashed)
  
        m := new(big.Int).SetBytes(em)
 -      c, err := decryptAndCheck(rand, priv, m)
 +      c, err := decryptAndCheck(random, priv, m)
        if err != nil {
                return nil, err
        }
  // returning a nil error. If hash is zero then hashed is used directly. This
  // isn't advisable except for interoperability.
  func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error {
 +      if boring.Enabled {
 +              bkey, err := boringPublicKey(pub)
 +              if err != nil {
 +                      return err
 +              }
 +              if err := boring.VerifyRSAPKCS1v15(bkey, hash, hashed, sig); err != nil {
 +                      return ErrVerification
 +              }
 +              return nil
 +      }
 +
        hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed))
        if err != nil {
                return err
                return ErrVerification
        }
  
+       // RFC 8017 Section 8.2.2: If the length of the signature S is not k
+       // octets (where k is the length in octets of the RSA modulus n), output
+       // "invalid signature" and stop.
+       if k != len(sig) {
+               return ErrVerification
+       }
        c := new(big.Int).SetBytes(sig)
        m := encrypt(new(big.Int), pub, c)
        em := leftPad(m.Bytes(), k)
index d41247403495c86175a2da7a69d3010a145d599b,26b8c5f26fefd249ab2ac03eab1383e2436653ee..c5d825b42a0962db27e3ea570e16ef3d4c6ba2a6
@@@ -9,6 -9,7 +9,7 @@@ import 
        "crypto"
        "crypto/rand"
        "crypto/sha1"
+       "crypto/sha256"
        "encoding/base64"
        "encoding/hex"
        "io"
@@@ -64,7 -65,7 +65,7 @@@ func TestDecryptPKCS1v15(t *testing.T) 
                for i, test := range decryptPKCS1v15Tests {
                        out, err := decryptFunc(decodeBase64(test.in))
                        if err != nil {
 -                              t.Errorf("#%d error decrypting", i)
 +                              t.Errorf("#%d error decrypting: %v", i, err)
                        }
                        want := []byte(test.out)
                        if !bytes.Equal(out, want) {
@@@ -296,3 -297,20 +297,20 @@@ var rsaPrivateKey = &PrivateKey
                fromBase10("94560208308847015747498523884063394671606671904944666360068158221458669711639"),
        },
  }
+ func TestShortPKCS1v15Signature(t *testing.T) {
+       pub := &PublicKey{
+               E: 65537,
+               N: fromBase10("8272693557323587081220342447407965471608219912416565371060697606400726784709760494166080686904546560026343451112103559482851304715739629410219358933351333"),
+       }
+       sig, err := hex.DecodeString("193a310d0dcf64094c6e3a00c8219b80ded70535473acff72c08e1222974bb24a93a535b1dc4c59fc0e65775df7ba2007dd20e9193f4c4025a18a7070aee93")
+       if err != nil {
+               t.Fatalf("failed to decode signature: %s", err)
+       }
+       h := sha256.Sum256([]byte("hello"))
+       err = VerifyPKCS1v15(pub, crypto.SHA256, h[:], sig)
+       if err == nil {
+               t.Fatal("VerifyPKCS1v15 accepted a truncated signature")
+       }
+ }
diff --combined src/crypto/rsa/pss.go
index e32cb7e0a729abb1b0e3b4e6519b6778a19afb95,f9844d87329a843e53784fd032017ac0e3ad5956..b653be23dc003a06a37f0411228c82ac5b8d158f
@@@ -4,9 -4,7 +4,7 @@@
  
  package rsa
  
- // This file implements the PSS signature scheme [1].
- //
- // [1] https://www.emc.com/collateral/white-papers/h11300-pkcs-1v2-2-rsa-cryptography-standard-wp.pdf
+ // This file implements the RSASSA-PSS signature scheme according to RFC 8017.
  
  import (
        "bytes"
        "math/big"
  )
  
 +import "crypto/internal/boring"
 +
+ // Per RFC 8017, Section 9.1
+ //
+ //     EM = MGF1 xor DB || H( 8*0x00 || mHash || salt ) || 0xbc
+ //
+ // where
+ //
+ //     DB = PS || 0x01 || salt
+ //
+ // and PS can be empty so
+ //
+ //     emLen = dbLen + hLen + 1 = psLen + sLen + hLen + 2
+ //
  func emsaPSSEncode(mHash []byte, emBits int, salt []byte, hash hash.Hash) ([]byte, error) {
-       // See [1], section 9.1.1
+       // See RFC 8017, Section 9.1.1.
        hLen := hash.Size()
        sLen := len(salt)
        emLen := (emBits + 7) / 8
@@@ -32,7 -42,7 +44,7 @@@
        // 2.  Let mHash = Hash(M), an octet string of length hLen.
  
        if len(mHash) != hLen {
-               return nil, errors.New("crypto/rsa: input must be hashed message")
+               return nil, errors.New("crypto/rsa: input must be hashed with given hash")
        }
  
        // 3.  If emLen < hLen + sLen + 2, output "encoding error" and stop.
@@@ -42,8 -52,9 +54,9 @@@
        }
  
        em := make([]byte, emLen)
-       db := em[:emLen-sLen-hLen-2+1+sLen]
-       h := em[emLen-sLen-hLen-2+1+sLen : emLen-1]
+       psLen := emLen - sLen - hLen - 2
+       db := em[:psLen+1+sLen]
+       h := em[psLen+1+sLen : emLen-1]
  
        // 4.  Generate a random octet string salt of length sLen; if sLen = 0,
        //     then salt is the empty string.
@@@ -71,8 -82,8 +84,8 @@@
        // 8.  Let DB = PS || 0x01 || salt; DB is an octet string of length
        //     emLen - hLen - 1.
  
-       db[emLen-sLen-hLen-2] = 0x01
-       copy(db[emLen-sLen-hLen-1:], salt)
+       db[psLen] = 0x01
+       copy(db[psLen+1:], salt)
  
        // 9.  Let dbMask = MGF(H, emLen - hLen - 1).
        //
        // 11. Set the leftmost 8 * emLen - emBits bits of the leftmost octet in
        //     maskedDB to zero.
  
-       db[0] &= (0xFF >> uint(8*emLen-emBits))
+       db[0] &= 0xff >> (8*emLen - emBits)
  
        // 12. Let EM = maskedDB || H || 0xbc.
-       em[emLen-1] = 0xBC
+       em[emLen-1] = 0xbc
  
        // 13. Output EM.
        return em, nil
  }
  
  func emsaPSSVerify(mHash, em []byte, emBits, sLen int, hash hash.Hash) error {
+       // See RFC 8017, Section 9.1.2.
+       hLen := hash.Size()
+       if sLen == PSSSaltLengthEqualsHash {
+               sLen = hLen
+       }
+       emLen := (emBits + 7) / 8
+       if emLen != len(em) {
+               return errors.New("rsa: internal error: inconsistent length")
+       }
        // 1.  If the length of M is greater than the input limitation for the
        //     hash function (2^61 - 1 octets for SHA-1), output "inconsistent"
        //     and stop.
        //
        // 2.  Let mHash = Hash(M), an octet string of length hLen.
-       hLen := hash.Size()
        if hLen != len(mHash) {
                return ErrVerification
        }
  
        // 3.  If emLen < hLen + sLen + 2, output "inconsistent" and stop.
-       emLen := (emBits + 7) / 8
        if emLen < hLen+sLen+2 {
                return ErrVerification
        }
  
        // 4.  If the rightmost octet of EM does not have hexadecimal value
        //     0xbc, output "inconsistent" and stop.
-       if em[len(em)-1] != 0xBC {
+       if em[emLen-1] != 0xbc {
                return ErrVerification
        }
  
        // 5.  Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and
        //     let H be the next hLen octets.
        db := em[:emLen-hLen-1]
-       h := em[emLen-hLen-1 : len(em)-1]
+       h := em[emLen-hLen-1 : emLen-1]
  
        // 6.  If the leftmost 8 * emLen - emBits bits of the leftmost octet in
        //     maskedDB are not all equal to zero, output "inconsistent" and
        //     stop.
-       if em[0]&(0xFF<<uint(8-(8*emLen-emBits))) != 0 {
+       var bitMask byte = 0xff >> (8*emLen - emBits)
+       if em[0] & ^bitMask != 0 {
                return ErrVerification
        }
  
  
        // 9.  Set the leftmost 8 * emLen - emBits bits of the leftmost octet in DB
        //     to zero.
-       db[0] &= (0xFF >> uint(8*emLen-emBits))
+       db[0] &= bitMask
  
+       // If we don't know the salt length, look for the 0x01 delimiter.
        if sLen == PSSSaltLengthAuto {
-       FindSaltLength:
-               for sLen = emLen - (hLen + 2); sLen >= 0; sLen-- {
-                       switch db[emLen-hLen-sLen-2] {
-                       case 1:
-                               break FindSaltLength
-                       case 0:
-                               continue
-                       default:
-                               return ErrVerification
-                       }
-               }
-               if sLen < 0 {
+               psLen := bytes.IndexByte(db, 0x01)
+               if psLen < 0 {
                        return ErrVerification
                }
-       } else {
-               // 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero
-               //     or if the octet at position emLen - hLen - sLen - 1 (the leftmost
-               //     position is "position 1") does not have hexadecimal value 0x01,
-               //     output "inconsistent" and stop.
-               for _, e := range db[:emLen-hLen-sLen-2] {
-                       if e != 0x00 {
-                               return ErrVerification
-                       }
-               }
-               if db[emLen-hLen-sLen-2] != 0x01 {
+               sLen = len(db) - psLen - 1
+       }
+       // 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero
+       //     or if the octet at position emLen - hLen - sLen - 1 (the leftmost
+       //     position is "position 1") does not have hexadecimal value 0x01,
+       //     output "inconsistent" and stop.
+       psLen := emLen - hLen - sLen - 2
+       for _, e := range db[:psLen] {
+               if e != 0x00 {
                        return ErrVerification
                }
        }
+       if db[psLen] != 0x01 {
+               return ErrVerification
+       }
  
        // 11.  Let salt be the last sLen octets of DB.
        salt := db[len(db)-sLen:]
        h0 := hash.Sum(nil)
  
        // 14. If H = H', output "consistent." Otherwise, output "inconsistent."
-       if !bytes.Equal(h0, h) {
+       if !bytes.Equal(h0, h) { // TODO: constant time?
                return ErrVerification
        }
        return nil
  }
  
- // signPSSWithSalt calculates the signature of hashed using PSS [1] with specified salt.
+ // signPSSWithSalt calculates the signature of hashed using PSS with specified salt.
  // Note that hashed must be the result of hashing the input message using the
  // given hash function. salt is a random sequence of bytes whose length will be
  // later used to verify the signature.
  func signPSSWithSalt(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed, salt []byte) (s []byte, err error) {
-       nBits := priv.N.BitLen()
-       em, err := emsaPSSEncode(hashed, nBits-1, salt, hash.New())
+       emBits := priv.N.BitLen() - 1
+       em, err := emsaPSSEncode(hashed, emBits, salt, hash.New())
        if err != nil {
                return
        }
 +
 +      if boring.Enabled {
 +              bkey, err := boringPrivateKey(priv)
 +              if err != nil {
 +                      return nil, err
 +              }
 +              // Note: BoringCrypto takes care of the "AndCheck" part of "decryptAndCheck".
 +              // (It's not just decrypt.)
 +              s, err := boring.DecryptRSANoPadding(bkey, em)
 +              if err != nil {
 +                      return nil, err
 +              }
 +              return s, nil
 +      }
 +
        m := new(big.Int).SetBytes(em)
        c, err := decryptAndCheck(rand, priv, m)
        if err != nil {
                return
        }
-       s = make([]byte, (nBits+7)/8)
+       s = make([]byte, priv.Size())
        copyWithLeftPad(s, c.Bytes())
        return
  }
@@@ -240,16 -239,15 +256,15 @@@ type PSSOptions struct 
        // PSSSaltLength constants.
        SaltLength int
  
-       // Hash, if not zero, overrides the hash function passed to SignPSS.
-       // This is the only way to specify the hash function when using the
-       // crypto.Signer interface.
+       // Hash is the hash function used to generate the message digest. If not
+       // zero, it overrides the hash function passed to SignPSS. It's required
+       // when using PrivateKey.Sign.
        Hash crypto.Hash
  }
  
- // HashFunc returns pssOpts.Hash so that PSSOptions implements
- // crypto.SignerOpts.
- func (pssOpts *PSSOptions) HashFunc() crypto.Hash {
-       return pssOpts.Hash
+ // HashFunc returns opts.Hash so that PSSOptions implements crypto.SignerOpts.
+ func (opts *PSSOptions) HashFunc() crypto.Hash {
+       return opts.Hash
  }
  
  func (opts *PSSOptions) saltLength() int {
        return opts.SaltLength
  }
  
- // SignPSS calculates the signature of hashed using RSASSA-PSS [1].
- // Note that hashed must be the result of hashing the input message using the
- // given hash function. The opts argument may be nil, in which case sensible
- // defaults are used.
- func SignPSS(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte, opts *PSSOptions) ([]byte, error) {
+ // SignPSS calculates the signature of digest using PSS.
+ //
+ // digest must be the result of hashing the input message using the given hash
+ // function. The opts argument may be nil, in which case sensible defaults are
+ // used. If opts.Hash is set, it overrides hash.
+ func SignPSS(rand io.Reader, priv *PrivateKey, hash crypto.Hash, digest []byte, opts *PSSOptions) ([]byte, error) {
+       if opts != nil && opts.Hash != 0 {
+               hash = opts.Hash
+       }
        saltLength := opts.saltLength()
        switch saltLength {
        case PSSSaltLengthAuto:
-               saltLength = (priv.N.BitLen()+7)/8 - 2 - hash.Size()
+               saltLength = priv.Size() - 2 - hash.Size()
        case PSSSaltLengthEqualsHash:
                saltLength = hash.Size()
        }
  
-       if opts != nil && opts.Hash != 0 {
-               hash = opts.Hash
-       }
 +      if boring.Enabled && rand == boring.RandReader {
 +              bkey, err := boringPrivateKey(priv)
 +              if err != nil {
 +                      return nil, err
 +              }
-               return boring.SignRSAPSS(bkey, hash, hashed, saltLength)
++              return boring.SignRSAPSS(bkey, hash, digest, saltLength)
 +      }
 +
        salt := make([]byte, saltLength)
        if _, err := io.ReadFull(rand, salt); err != nil {
                return nil, err
        }
-       return signPSSWithSalt(rand, priv, hash, hashed, salt)
+       return signPSSWithSalt(rand, priv, hash, digest, salt)
  }
  
  // VerifyPSS verifies a PSS signature.
- // hashed is the result of hashing the input message using the given hash
- // function and sig is the signature. A valid signature is indicated by
- // returning a nil error. The opts argument may be nil, in which case sensible
- // defaults are used.
- func VerifyPSS(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte, opts *PSSOptions) error {
-       return verifyPSS(pub, hash, hashed, sig, opts.saltLength())
- }
- // verifyPSS verifies a PSS signature with the given salt length.
- func verifyPSS(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte, saltLen int) error {
+ //
+ // A valid signature is indicated by returning a nil error. digest must be the
+ // result of hashing the input message using the given hash function. The opts
+ // argument may be nil, in which case sensible defaults are used. opts.Hash is
+ // ignored.
+ func VerifyPSS(pub *PublicKey, hash crypto.Hash, digest []byte, sig []byte, opts *PSSOptions) error {
 +      if boring.Enabled {
 +              bkey, err := boringPublicKey(pub)
 +              if err != nil {
 +                      return err
 +              }
-               if err := boring.VerifyRSAPSS(bkey, hash, hashed, sig, saltLen); err != nil {
++              if err := boring.VerifyRSAPSS(bkey, hash, digest, sig, opts.saltLength()); err != nil {
 +                      return ErrVerification
 +              }
 +              return nil
 +      }
-       nBits := pub.N.BitLen()
-       if len(sig) != (nBits+7)/8 {
+       if len(sig) != pub.Size() {
                return ErrVerification
        }
        s := new(big.Int).SetBytes(sig)
        m := encrypt(new(big.Int), pub, s)
-       emBits := nBits - 1
+       emBits := pub.N.BitLen() - 1
        emLen := (emBits + 7) / 8
-       if emLen < len(m.Bytes()) {
+       emBytes := m.Bytes()
+       if emLen < len(emBytes) {
                return ErrVerification
        }
        em := make([]byte, emLen)
-       copyWithLeftPad(em, m.Bytes())
-       if saltLen == PSSSaltLengthEqualsHash {
-               saltLen = hash.Size()
-       }
-       return emsaPSSVerify(hashed, em, emBits, saltLen, hash.New())
+       copyWithLeftPad(em, emBytes)
+       return emsaPSSVerify(digest, em, emBits, opts.saltLength(), hash.New())
  }
diff --combined src/crypto/rsa/rsa.go
index 65fbcd664a444a574ff3363d876f26dc6db683dc,b4bfa13defbdf04136d10e640dd5b336142272b7..bd738f592c0544ea05948f9860e45534ea48d4b2
@@@ -2,7 -2,7 +2,7 @@@
  // Use of this source code is governed by a BSD-style
  // license that can be found in the LICENSE file.
  
- // Package rsa implements RSA encryption as specified in PKCS#1.
+ // Package rsa implements RSA encryption as specified in PKCS#1 and RFC 8017.
  //
  // RSA is a single, fundamental operation that is used in this package to
  // implement either public-key encryption or public-key signatures.
  // The original specification for encryption and signatures with RSA is PKCS#1
  // and the terms "RSA encryption" and "RSA signatures" by default refer to
  // PKCS#1 version 1.5. However, that specification has flaws and new designs
- // should use version two, usually called by just OAEP and PSS, where
+ // should use version 2, usually called by just OAEP and PSS, where
  // possible.
  //
  // Two sets of interfaces are included in this package. When a more abstract
  // interface isn't necessary, there are functions for encrypting/decrypting
  // with v1.5/OAEP and signing/verifying with v1.5/PSS. If one needs to abstract
- // over the public-key primitive, the PrivateKey struct implements the
+ // over the public key primitive, the PrivateKey type implements the
  // Decrypter and Signer interfaces from the crypto package.
  //
  // The RSA operations in this package are not implemented using constant-time algorithms.
@@@ -35,11 -35,6 +35,11 @@@ import 
        "crypto/internal/randutil"
  )
  
 +import (
 +      "crypto/internal/boring"
 +      "unsafe"
 +)
 +
  var bigZero = big.NewInt(0)
  var bigOne = big.NewInt(1)
  
@@@ -47,8 -42,6 +47,8 @@@
  type PublicKey struct {
        N *big.Int // modulus
        E int      // public exponent
 +
 +      boring unsafe.Pointer
  }
  
  // Size returns the modulus size in bytes. Raw signatures and ciphertexts
@@@ -57,6 -50,15 +57,15 @@@ func (pub *PublicKey) Size() int 
        return (pub.N.BitLen() + 7) / 8
  }
  
+ // Equal reports whether pub and x have the same value.
+ func (pub *PublicKey) Equal(x crypto.PublicKey) bool {
+       xx, ok := x.(*PublicKey)
+       if !ok {
+               return false
+       }
+       return pub.N.Cmp(xx.N) == 0 && pub.E == xx.E
+ }
  // OAEPOptions is an interface for passing options to OAEP decryption using the
  // crypto.Decrypter interface.
  type OAEPOptions struct {
@@@ -100,8 -102,6 +109,8 @@@ type PrivateKey struct 
        // Precomputed contains precomputed values that speed up private
        // operations, if available.
        Precomputed PrecomputedValues
 +
 +      boring unsafe.Pointer
  }
  
  // Public returns the public key corresponding to priv.
@@@ -111,7 -111,8 +120,8 @@@ func (priv *PrivateKey) Public() crypto
  
  // Sign signs digest with priv, reading randomness from rand. If opts is a
  // *PSSOptions then the PSS algorithm will be used, otherwise PKCS#1 v1.5 will
- // be used.
+ // be used. digest must be the result of hashing the input message using
+ // opts.HashFunc().
  //
  // This method implements crypto.Signer, which is an interface to support keys
  // where the private part is kept in, for example, a hardware module. Common
@@@ -231,32 -232,6 +241,32 @@@ func GenerateKey(random io.Reader, bit
  func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (*PrivateKey, error) {
        randutil.MaybeReadByte(random)
  
 +      if boring.Enabled && random == boring.RandReader && nprimes == 2 && (bits == 2048 || bits == 3072) {
 +              N, E, D, P, Q, Dp, Dq, Qinv, err := boring.GenerateKeyRSA(bits)
 +              if err != nil {
 +                      return nil, err
 +              }
 +              e64 := E.Int64()
 +              if !E.IsInt64() || int64(int(e64)) != e64 {
 +                      return nil, errors.New("crypto/rsa: generated key exponent too large")
 +              }
 +              key := &PrivateKey{
 +                      PublicKey: PublicKey{
 +                              N: N,
 +                              E: int(e64),
 +                      },
 +                      D:      D,
 +                      Primes: []*big.Int{P, Q},
 +                      Precomputed: PrecomputedValues{
 +                              Dp:        Dp,
 +                              Dq:        Dq,
 +                              Qinv:      Qinv,
 +                              CRTValues: make([]CRTValue, 0), // non-nil, to match Precompute
 +                      },
 +              }
 +              return key, nil
 +      }
 +
        priv := new(PrivateKey)
        priv.E = 65537
  
@@@ -386,7 -361,6 +396,7 @@@ func mgf1XOR(out []byte, hash hash.Hash
  var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA public key size")
  
  func encrypt(c *big.Int, pub *PublicKey, m *big.Int) *big.Int {
 +      boring.Unreachable()
        e := big.NewInt(int64(pub.E))
        c.Exp(m, e, pub.N)
        return c
@@@ -419,15 -393,6 +429,15 @@@ func EncryptOAEP(hash hash.Hash, rando
                return nil, ErrMessageTooLong
        }
  
 +      if boring.Enabled && random == boring.RandReader {
 +              bkey, err := boringPublicKey(pub)
 +              if err != nil {
 +                      return nil, err
 +              }
 +              return boring.EncryptRSAOAEP(hash, bkey, msg, label)
 +      }
 +      boring.UnreachableExceptTests()
 +
        hash.Write(label)
        lHash := hash.Sum(nil)
        hash.Reset()
        mgf1XOR(db, hash, seed)
        mgf1XOR(seed, hash, db)
  
 -      m := new(big.Int)
 -      m.SetBytes(em)
 -      c := encrypt(new(big.Int), pub, m)
 -      out := c.Bytes()
 +      var out []byte
 +      if boring.Enabled {
 +              var bkey *boring.PublicKeyRSA
 +              bkey, err = boringPublicKey(pub)
 +              if err != nil {
 +                      return nil, err
 +              }
 +              c, err := boring.EncryptRSANoPadding(bkey, em)
 +              if err != nil {
 +                      return nil, err
 +              }
 +              out = c
 +      } else {
 +              m := new(big.Int)
 +              m.SetBytes(em)
 +              c := encrypt(new(big.Int), pub, m)
 +              out = c.Bytes()
 +      }
  
        if len(out) < k {
                // If the output is too small, we need to left-pad with zeros.
@@@ -519,9 -470,6 +529,9 @@@ func (priv *PrivateKey) Precompute() 
  // decrypt performs an RSA decryption, resulting in a plaintext integer. If a
  // random source is given, RSA blinding is used.
  func decrypt(random io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err error) {
 +      if len(priv.Primes) <= 2 {
 +              boring.Unreachable()
 +      }
        // TODO(agl): can we get away with reusing blinds?
        if c.Cmp(priv.N) > 0 {
                err = ErrDecryption
@@@ -638,17 -586,6 +648,17 @@@ func DecryptOAEP(hash hash.Hash, rando
                return nil, ErrDecryption
        }
  
 +      if boring.Enabled {
 +              bkey, err := boringPrivateKey(priv)
 +              if err != nil {
 +                      return nil, err
 +              }
 +              out, err := boring.DecryptRSAOAEP(hash, bkey, ciphertext, label)
 +              if err != nil {
 +                      return nil, ErrDecryption
 +              }
 +              return out, nil
 +      }
        c := new(big.Int).SetBytes(ciphertext)
  
        m, err := decrypt(random, priv, c)
diff --combined src/crypto/tls/auth.go
index 98c96d3ba21e9ec6b3f8f2b962ec8b2295668a90,ad5f9a2e4399e69d15da935c402aad613cae28b8..a807e0528e4e55608e42e8b0f1758e619f49f9c2
@@@ -11,7 -11,6 +11,6 @@@ import 
        "crypto/ed25519"
        "crypto/elliptic"
        "crypto/rsa"
-       "encoding/asn1"
        "errors"
        "fmt"
        "hash"
@@@ -27,14 -26,7 +26,7 @@@ func verifyHandshakeSignature(sigType u
                if !ok {
                        return fmt.Errorf("expected an ECDSA public key, got %T", pubkey)
                }
-               ecdsaSig := new(ecdsaSignature)
-               if _, err := asn1.Unmarshal(sig, ecdsaSig); err != nil {
-                       return err
-               }
-               if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
-                       return errors.New("ECDSA signature contained zero or negative values")
-               }
-               if !ecdsa.Verify(pubKey, signed, ecdsaSig.R, ecdsaSig.S) {
+               if !ecdsa.VerifyASN1(pubKey, signed, sig) {
                        return errors.New("ECDSA verification failure")
                }
        case signatureEd25519:
@@@ -114,7 -106,7 +106,7 @@@ func typeAndHashFromSignatureScheme(sig
        case Ed25519:
                sigType = signatureEd25519
        default:
-               return 0, 0, fmt.Errorf("unsupported signature algorithm: %#04x", signatureAlgorithm)
+               return 0, 0, fmt.Errorf("unsupported signature algorithm: %v", signatureAlgorithm)
        }
        switch signatureAlgorithm {
        case PKCS1WithSHA1, ECDSAWithSHA1:
        case Ed25519:
                hash = directSigning
        default:
-               return 0, 0, fmt.Errorf("unsupported signature algorithm: %#04x", signatureAlgorithm)
+               return 0, 0, fmt.Errorf("unsupported signature algorithm: %v", signatureAlgorithm)
        }
        return sigType, hash, nil
  }
@@@ -153,6 -145,25 +145,25 @@@ func legacyTypeAndHashFromPublicKey(pu
        }
  }
  
+ var rsaSignatureSchemes = []struct {
+       scheme          SignatureScheme
+       minModulusBytes int
+       maxVersion      uint16
+ }{
+       // RSA-PSS is used with PSSSaltLengthEqualsHash, and requires
+       //    emLen >= hLen + sLen + 2
+       {PSSWithSHA256, crypto.SHA256.Size()*2 + 2, VersionTLS13},
+       {PSSWithSHA384, crypto.SHA384.Size()*2 + 2, VersionTLS13},
+       {PSSWithSHA512, crypto.SHA512.Size()*2 + 2, VersionTLS13},
+       // PKCS#1 v1.5 uses prefixes from hashPrefixes in crypto/rsa, and requires
+       //    emLen >= len(prefix) + hLen + 11
+       // TLS 1.3 dropped support for PKCS#1 v1.5 in favor of RSA-PSS.
+       {PKCS1WithSHA256, 19 + crypto.SHA256.Size() + 11, VersionTLS12},
+       {PKCS1WithSHA384, 19 + crypto.SHA384.Size() + 11, VersionTLS12},
+       {PKCS1WithSHA512, 19 + crypto.SHA512.Size() + 11, VersionTLS12},
+       {PKCS1WithSHA1, 15 + crypto.SHA1.Size() + 11, VersionTLS12},
+ }
  // signatureSchemesForCertificate returns the list of supported SignatureSchemes
  // for a given certificate, based on the public key and the protocol version,
  // and optionally filtered by its explicit SupportedSignatureAlgorithms.
@@@ -189,23 -200,12 +200,12 @@@ func signatureSchemesForCertificate(ver
                        return nil
                }
        case *rsa.PublicKey:
-               if version != VersionTLS13 {
-                       sigAlgs = []SignatureScheme{
-                               PSSWithSHA256,
-                               PSSWithSHA384,
-                               PSSWithSHA512,
-                               PKCS1WithSHA256,
-                               PKCS1WithSHA384,
-                               PKCS1WithSHA512,
-                               PKCS1WithSHA1,
+               size := pub.Size()
+               sigAlgs = make([]SignatureScheme, 0, len(rsaSignatureSchemes))
+               for _, candidate := range rsaSignatureSchemes {
+                       if size >= candidate.minModulusBytes && version <= candidate.maxVersion {
+                               sigAlgs = append(sigAlgs, candidate.scheme)
                        }
-                       break
-               }
-               // TLS 1.3 dropped support for PKCS#1 v1.5 in favor of RSA-PSS.
-               sigAlgs = []SignatureScheme{
-                       PSSWithSHA256,
-                       PSSWithSHA384,
-                       PSSWithSHA512,
                }
        case ed25519.PublicKey:
                sigAlgs = []SignatureScheme{Ed25519}
@@@ -241,9 -241,6 +241,9 @@@ func selectSignatureScheme(vers uint16
        // Pick signature scheme in the peer's preference order, as our
        // preference order is not configurable.
        for _, preferredAlg := range peerAlgs {
 +              if needFIPS() && !isSupportedSignatureAlgorithm(preferredAlg, fipsSupportedSignatureAlgorithms) {
 +                      continue
 +              }
                if isSupportedSignatureAlgorithm(preferredAlg, supportedAlgs) {
                        return preferredAlg, nil
                }
@@@ -278,6 -275,7 +278,7 @@@ func unsupportedCertificateError(cert *
                        return fmt.Errorf("tls: unsupported certificate curve (%s)", pub.Curve.Params().Name)
                }
        case *rsa.PublicKey:
+               return fmt.Errorf("tls: certificate RSA key size too small for supported signature algorithms")
        case ed25519.PublicKey:
        default:
                return fmt.Errorf("tls: unsupported certificate key (%T)", pub)
index f2dc0f2265a98171d9cc1a4121853ef720e334fe,c42e3491e46f16873c2195397bbdd56e9536b2a5..c23d93f3c0855d83c38579d15594c051deb75535
@@@ -62,7 -62,7 +62,7 @@@ func TestSignatureSelection(t *testing.
                        t.Errorf("test[%d]: unexpected selectSignatureScheme error: %v", testNo, err)
                }
                if test.expectedSigAlg != sigAlg {
-                       t.Errorf("test[%d]: expected signature scheme %#x, got %#x", testNo, test.expectedSigAlg, sigAlg)
+                       t.Errorf("test[%d]: expected signature scheme %v, got %v", testNo, test.expectedSigAlg, sigAlg)
                }
                sigType, hashFunc, err := typeAndHashFromSignatureScheme(sigAlg)
                if err != nil {
                {rsaCert, []SignatureScheme{PKCS1WithSHA256}, VersionTLS13},
                {pkcs1Cert, []SignatureScheme{PSSWithSHA256, PKCS1WithSHA256}, VersionTLS13},
                {ecdsaCert, []SignatureScheme{ECDSAWithSHA1}, VersionTLS13},
+               // The key can be too small for the hash.
+               {rsaCert, []SignatureScheme{PSSWithSHA512}, VersionTLS12},
        }
  
        for testNo, test := range badTests {
                sigAlg, err := selectSignatureScheme(test.tlsVersion, test.cert, test.peerSigAlgs)
                if err == nil {
-                       t.Errorf("test[%d]: unexpected success, got %#x", testNo, sigAlg)
+                       t.Errorf("test[%d]: unexpected success, got %v", testNo, sigAlg)
                }
        }
  }
@@@ -127,7 -129,7 +129,7 @@@ func TestLegacyTypeAndHash(t *testing.T
                t.Errorf("RSA: expected signature type %#x, got %#x", expectedSigType, sigType)
        }
        if expectedHashFunc := crypto.MD5SHA1; expectedHashFunc != hashFunc {
-               t.Errorf("RSA: expected hash %#x, got %#x", expectedHashFunc, sigType)
+               t.Errorf("RSA: expected hash %#x, got %#x", expectedHashFunc, hashFunc)
        }
  
        sigType, hashFunc, err = legacyTypeAndHashFromPublicKey(testECDSAPrivateKey.Public())
                t.Errorf("ECDSA: expected signature type %#x, got %#x", expectedSigType, sigType)
        }
        if expectedHashFunc := crypto.SHA1; expectedHashFunc != hashFunc {
-               t.Errorf("ECDSA: expected hash %#x, got %#x", expectedHashFunc, sigType)
+               t.Errorf("ECDSA: expected hash %#x, got %#x", expectedHashFunc, hashFunc)
        }
  
        // Ed25519 is not supported by TLS 1.0 and 1.1.
  // TestSupportedSignatureAlgorithms checks that all supportedSignatureAlgorithms
  // have valid type and hash information.
  func TestSupportedSignatureAlgorithms(t *testing.T) {
 -      for _, sigAlg := range supportedSignatureAlgorithms {
 +      for _, sigAlg := range supportedSignatureAlgorithms() {
                sigType, hash, err := typeAndHashFromSignatureScheme(sigAlg)
                if err != nil {
-                       t.Errorf("%#04x: unexpected error: %v", sigAlg, err)
+                       t.Errorf("%v: unexpected error: %v", sigAlg, err)
                }
                if sigType == 0 {
-                       t.Errorf("%#04x: missing signature type", sigAlg)
+                       t.Errorf("%v: missing signature type", sigAlg)
                }
                if hash == 0 && sigAlg != Ed25519 {
-                       t.Errorf("%#04x: missing hash", sigAlg)
+                       t.Errorf("%v: missing hash", sigAlg)
                }
        }
  }
diff --combined src/crypto/tls/common.go
index cd1fd2aaf8402aaa1d0cb4e6c7cde47cd91a8569,9121148ee853d3ab6e0573602146255b5d8fe49c..2a61dae2ed097b8e8a8a878dceac535b23996d96
@@@ -19,7 -19,6 +19,6 @@@ import 
        "fmt"
        "internal/cpu"
        "io"
-       "math/big"
        "net"
        "strings"
        "sync"
@@@ -100,7 -99,6 +99,6 @@@ const 
        extensionCertificateAuthorities  uint16 = 47
        extensionSignatureAlgorithmsCert uint16 = 50
        extensionKeyShare                uint16 = 51
-       extensionNextProtoNeg            uint16 = 13172 // not IANA assigned
        extensionRenegotiationInfo       uint16 = 0xff01
  )
  
@@@ -173,11 -171,11 +171,11 @@@ const 
  // hash function associated with the Ed25519 signature scheme.
  var directSigning crypto.Hash = 0
  
 -// supportedSignatureAlgorithms contains the signature and hash algorithms that
 +// defaultSupportedSignatureAlgorithms contains the signature and hash algorithms that
  // the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+
  // CertificateRequest. The two fields are merged to match with TLS 1.3.
  // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
 -var supportedSignatureAlgorithms = []SignatureScheme{
 +var defaultSupportedSignatureAlgorithms = []SignatureScheme{
        PSSWithSHA256,
        ECDSAWithP256AndSHA256,
        Ed25519,
@@@ -301,6 -299,8 +299,8 @@@ type ClientSessionCache interface 
        Put(sessionKey string, cs *ClientSessionState)
  }
  
+ //go:generate stringer -type=SignatureScheme,CurveID,ClientAuthType -output=common_string.go
  // SignatureScheme identifies a signature algorithm supported by TLS. See
  // RFC 8446, Section 4.2.3.
  type SignatureScheme uint16
@@@ -549,7 -549,7 +549,7 @@@ type Config struct 
        // server's certificate chain and host name.
        // If InsecureSkipVerify is true, TLS accepts any certificate
        // presented by the server and any host name in that certificate.
-       // In this mode, TLS is susceptible to man-in-the-middle attacks.
+       // In this mode, TLS is susceptible to machine-in-the-middle attacks.
        // This should be used only for testing.
        InsecureSkipVerify bool
  
@@@ -779,9 -779,6 +779,9 @@@ func (c *Config) time() time.Time 
  }
  
  func (c *Config) cipherSuites() []uint16 {
 +      if needFIPS() {
 +              return fipsCipherSuites(c)
 +      }
        s := c.CipherSuites
        if s == nil {
                s = defaultCipherSuites()
@@@ -799,9 -796,6 +799,9 @@@ var supportedVersions = []uint16
  func (c *Config) supportedVersions() []uint16 {
        versions := make([]uint16, 0, len(supportedVersions))
        for _, v := range supportedVersions {
 +              if needFIPS() && (v < fipsMinVersion(c) || v > fipsMaxVersion(c)) {
 +                      continue
 +              }
                if c != nil && c.MinVersion != 0 && v < c.MinVersion {
                        continue
                }
@@@ -838,9 -832,6 +838,9 @@@ func supportedVersionsFromMax(maxVersio
  var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
  
  func (c *Config) curvePreferences() []CurveID {
 +      if needFIPS() {
 +              return fipsCurvePreferences(c)
 +      }
        if c == nil || len(c.CurvePreferences) == 0 {
                return defaultCurvePreferences
        }
@@@ -1274,13 -1265,6 +1274,6 @@@ func (c *lruSessionCache) Get(sessionKe
        return nil, false
  }
  
- // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
- type dsaSignature struct {
-       R, S *big.Int
- }
- type ecdsaSignature dsaSignature
  var emptyConfig Config
  
  func defaultConfig() *Config {
@@@ -1317,8 -1301,7 +1310,8 @@@ func initDefaultCipherSuites() 
                hasGCMAsm = hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X
        )
  
 -      if hasGCMAsm {
 +      if hasGCMAsm || boringEnabled {
 +              // If BoringCrypto is enabled, always prioritize AES-GCM.
                // If AES-GCM hardware is provided then prioritise AES-GCM
                // cipher suites.
                topCipherSuites = []uint16{
index b7c643f441810ae51dc1ec01857f732d1beef0f5,64be82e88c714d87e1cbf5ddb68e35316bb03b8b..e8ffcaf8db16e209743d9f6ee2f9cdbd257cc586
@@@ -112,10 -112,7 +112,10 @@@ func (c *Conn) makeClientHello() (*clie
        }
  
        if hello.vers >= VersionTLS12 {
 -              hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms
 +              hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
 +      }
 +      if testingOnlyForceClientHelloSignatureAlgorithms != nil {
 +              hello.supportedSignatureAlgorithms = testingOnlyForceClientHelloSignatureAlgorithms
        }
  
        var params ecdheParameters
@@@ -806,8 -803,6 +806,8 @@@ func (c *Conn) verifyServerCertificate(
  
        if !c.config.InsecureSkipVerify {
                opts := x509.VerifyOptions{
 +                      IsBoring: isBoringCertificate,
 +
                        Roots:         c.config.RootCAs,
                        CurrentTime:   c.config.time(),
                        DNSName:       c.config.ServerName,
        return nil
  }
  
- // tls11SignatureSchemes contains the signature schemes that we synthesise for
- // a TLS <= 1.1 connection, based on the supported certificate types.
- var (
-       tls11SignatureSchemes      = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
-       tls11SignatureSchemesECDSA = tls11SignatureSchemes[:3]
-       tls11SignatureSchemesRSA   = tls11SignatureSchemes[3:]
- )
  // certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
  // <= 1.2 CertificateRequest, making an effort to fill in missing information.
  func certificateRequestInfoFromMsg(vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo {
        }
  
        if !certReq.hasSignatureAlgorithm {
-               // Prior to TLS 1.2, the signature schemes were not
-               // included in the certificate request message. In this
-               // case we use a plausible list based on the acceptable
-               // certificate types.
+               // Prior to TLS 1.2, signature schemes did not exist. In this case we
+               // make up a list based on the acceptable certificate types, to help
+               // GetClientCertificate and SupportsCertificate select the right certificate.
+               // The hash part of the SignatureScheme is a lie here, because
+               // TLS 1.0 and 1.1 always use MD5+SHA1 for RSA and SHA1 for ECDSA.
                switch {
                case rsaAvail && ecAvail:
-                       cri.SignatureSchemes = tls11SignatureSchemes
+                       cri.SignatureSchemes = []SignatureScheme{
+                               ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
+                               PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
+                       }
                case rsaAvail:
-                       cri.SignatureSchemes = tls11SignatureSchemesRSA
+                       cri.SignatureSchemes = []SignatureScheme{
+                               PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
+                       }
                case ecAvail:
-                       cri.SignatureSchemes = tls11SignatureSchemesECDSA
+                       cri.SignatureSchemes = []SignatureScheme{
+                               ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
+                       }
                }
                return cri
        }
index 1dc3854d21e765e28b2a324ffcd1df733a1b4027,b16415a03c238326a3004f43c1df8eb206f7529e..ca98a309f3d7507222168bbb7a1fedf24a99c248
@@@ -241,7 -241,7 +241,7 @@@ func (hs *serverHandshakeState) process
        hs.ecdheOk = supportsECDHE(c.config, hs.clientHello.supportedCurves, hs.clientHello.supportedPoints)
  
        if hs.ecdheOk {
-               // Although omiting the ec_point_formats extension is permitted, some
+               // Although omitting the ec_point_formats extension is permitted, some
                // old OpenSSL version will refuse to handshake if not present.
                //
                // Per RFC 4492, section 5.1.2, implementations MUST support the
@@@ -492,7 -492,7 +492,7 @@@ func (hs *serverHandshakeState) doFullH
                }
                if c.vers >= VersionTLS12 {
                        certReq.hasSignatureAlgorithm = true
 -                      certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms
 +                      certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
                }
  
                // An empty list of certificateAuthorities signals to
@@@ -747,8 -747,6 +747,8 @@@ func (c *Conn) processCertsFromClient(c
  
        if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
                opts := x509.VerifyOptions{
 +                      IsBoring: isBoringCertificate,
 +
                        Roots:         c.config.ClientCAs,
                        CurrentTime:   c.config.time(),
                        Intermediates: x509.NewCertPool(),
index a68f4711ee856351a26abc6a170136a71337429f,9ef85dbf1bab9b282d1ad09ca66b679277ea9895..72d8c6b753ac1c3d7c9dea3b84022d0182fc1f56
@@@ -65,7 -65,7 +65,7 @@@ var pkgDeps = map[string][]string
        // but not Unicode tables.
        "math":          {"internal/cpu", "unsafe", "math/bits"},
        "math/bits":     {"unsafe"},
-       "math/cmplx":    {"math"},
+       "math/cmplx":    {"math", "math/bits"},
        "math/rand":     {"L0", "math"},
        "strconv":       {"L0", "unicode/utf8", "math", "math/bits"},
        "unicode/utf16": {},
        "reflect":                {"L2"},
        "sort":                   {"internal/reflectlite"},
  
 +      "crypto/internal/boring":         {"L2", "C", "crypto", "crypto/cipher", "crypto/internal/boring/sig", "crypto/subtle", "encoding/asn1", "hash", "math/big"},
 +      "crypto/internal/boring/fipstls": {"sync/atomic"},
 +      "crypto/internal/cipherhw":       {"crypto/internal/boring"},
 +      "crypto/tls/fipsonly":            {"crypto/internal/boring/fipstls", "crypto/internal/boring/sig"},
 +
        "L3": {
                "L2",
                "crypto",
                "crypto/cipher",
 +              "crypto/internal/boring",
 +              "crypto/internal/boring/fipstls",
                "crypto/internal/subtle",
                "crypto/subtle",
                "encoding/base32",
        "syscall/js":                        {"L0"},
        "internal/oserror":                  {"L0"},
        "internal/syscall/unix":             {"L0", "syscall"},
-       "internal/syscall/windows":          {"L0", "syscall", "internal/syscall/windows/sysdll"},
+       "internal/syscall/windows":          {"L0", "syscall", "internal/syscall/windows/sysdll", "unicode/utf16"},
        "internal/syscall/windows/registry": {"L0", "syscall", "internal/syscall/windows/sysdll", "unicode/utf16"},
+       "internal/syscall/execenv":          {"L0", "syscall", "internal/syscall/windows", "unicode/utf16"},
        "time": {
                // "L0" without the "io" package:
                "errors",
        },
  
        "internal/cfg":     {"L0"},
-       "internal/poll":    {"L0", "internal/oserror", "internal/race", "syscall", "time", "unicode/utf16", "unicode/utf8", "internal/syscall/windows"},
+       "internal/poll":    {"L0", "internal/oserror", "internal/race", "syscall", "time", "unicode/utf16", "unicode/utf8", "internal/syscall/windows", "internal/syscall/unix"},
        "internal/testlog": {"L0"},
-       "os":               {"L1", "os", "syscall", "time", "internal/oserror", "internal/poll", "internal/syscall/windows", "internal/syscall/unix", "internal/testlog"},
+       "os":               {"L1", "os", "syscall", "time", "internal/oserror", "internal/poll", "internal/syscall/windows", "internal/syscall/unix", "internal/syscall/execenv", "internal/testlog"},
        "path/filepath":    {"L2", "os", "syscall", "internal/syscall/windows"},
        "io/ioutil":        {"L2", "os", "path/filepath", "time"},
-       "os/exec":          {"L2", "os", "context", "path/filepath", "syscall"},
+       "os/exec":          {"L2", "os", "context", "path/filepath", "syscall", "internal/syscall/execenv"},
        "os/signal":        {"L2", "os", "syscall"},
  
        // OS enables basic operating system functionality,
        "regexp":         {"L2", "regexp/syntax"},
        "regexp/syntax":  {"L2"},
        "runtime/debug":  {"L2", "fmt", "io/ioutil", "os", "time"},
-       "runtime/pprof":  {"L2", "compress/gzip", "context", "encoding/binary", "fmt", "io/ioutil", "os", "text/tabwriter", "time"},
+       "runtime/pprof":  {"L2", "compress/gzip", "context", "encoding/binary", "fmt", "io/ioutil", "os", "syscall", "text/tabwriter", "time"},
        "runtime/trace":  {"L0", "context", "fmt"},
        "text/tabwriter": {"L2"},
  
-       "testing":               {"L2", "flag", "fmt", "internal/race", "os", "runtime/debug", "runtime/pprof", "runtime/trace", "time"},
-       "testing/iotest":        {"L2", "log"},
-       "testing/quick":         {"L2", "flag", "fmt", "reflect", "time"},
-       "internal/testenv":      {"L2", "OS", "flag", "testing", "syscall", "internal/cfg"},
-       "internal/lazyregexp":   {"L2", "OS", "regexp"},
-       "internal/lazytemplate": {"L2", "OS", "text/template"},
+       "testing":                  {"L2", "flag", "fmt", "internal/race", "os", "runtime/debug", "runtime/pprof", "runtime/trace", "time"},
+       "testing/iotest":           {"L2", "log"},
+       "testing/quick":            {"L2", "flag", "fmt", "reflect", "time"},
+       "internal/obscuretestdata": {"L2", "OS", "encoding/base64"},
+       "internal/testenv":         {"L2", "OS", "flag", "testing", "syscall", "internal/cfg"},
+       "internal/lazyregexp":      {"L2", "OS", "regexp"},
+       "internal/lazytemplate":    {"L2", "OS", "text/template"},
  
        // L4 is defined as L3+fmt+log+time, because in general once
        // you're using L3 packages, use of fmt, log, or time is not a big deal.
  
        // Mathematical crypto: dependencies on fmt (L4) and math/big.
        // We could avoid some of the fmt, but math/big imports fmt anyway.
-       "crypto/dsa":      {"L4", "CRYPTO", "math/big"},
-       "crypto/ecdsa":    {"L4", "CRYPTO", "crypto/elliptic", "math/big", "encoding/asn1"},
+       "crypto/dsa": {"L4", "CRYPTO", "math/big"},
+       "crypto/ecdsa": {
+               "L4", "CRYPTO", "crypto/elliptic", "math/big",
+               "golang.org/x/crypto/cryptobyte", "golang.org/x/crypto/cryptobyte/asn1",
+       },
        "crypto/elliptic": {"L4", "CRYPTO", "math/big"},
        "crypto/rsa":      {"L4", "CRYPTO", "crypto/rand", "math/big"},