]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/dist/test.go
misc/cgo: move easy tests to cmd/cgo/internal
[gostls13.git] / src / cmd / dist / test.go
1 // Copyright 2015 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package main
6
7 import (
8         "bytes"
9         "flag"
10         "fmt"
11         "io/fs"
12         "log"
13         "os"
14         "os/exec"
15         "path/filepath"
16         "reflect"
17         "regexp"
18         "runtime"
19         "strconv"
20         "strings"
21         "time"
22 )
23
24 func cmdtest() {
25         gogcflags = os.Getenv("GO_GCFLAGS")
26         setNoOpt()
27
28         var t tester
29
30         var noRebuild bool
31         flag.BoolVar(&t.listMode, "list", false, "list available tests")
32         flag.BoolVar(&t.rebuild, "rebuild", false, "rebuild everything first")
33         flag.BoolVar(&noRebuild, "no-rebuild", false, "overrides -rebuild (historical dreg)")
34         flag.BoolVar(&t.keepGoing, "k", false, "keep going even when error occurred")
35         flag.BoolVar(&t.race, "race", false, "run in race builder mode (different set of tests)")
36         flag.BoolVar(&t.compileOnly, "compile-only", false, "compile tests, but don't run them. This is for some builders. Not all dist tests respect this flag, but most do.")
37         flag.StringVar(&t.banner, "banner", "##### ", "banner prefix; blank means no section banners")
38         flag.StringVar(&t.runRxStr, "run", "",
39                 "run only those tests matching the regular expression; empty means to run all. "+
40                         "Special exception: if the string begins with '!', the match is inverted.")
41         flag.BoolVar(&t.msan, "msan", false, "run in memory sanitizer builder mode")
42         flag.BoolVar(&t.asan, "asan", false, "run in address sanitizer builder mode")
43
44         xflagparse(-1) // any number of args
45         if noRebuild {
46                 t.rebuild = false
47         }
48
49         t.run()
50 }
51
52 // tester executes cmdtest.
53 type tester struct {
54         race        bool
55         msan        bool
56         asan        bool
57         listMode    bool
58         rebuild     bool
59         failed      bool
60         keepGoing   bool
61         compileOnly bool // just try to compile all tests, but no need to run
62         runRxStr    string
63         runRx       *regexp.Regexp
64         runRxWant   bool     // want runRx to match (true) or not match (false)
65         runNames    []string // tests to run, exclusive with runRx; empty means all
66         banner      string   // prefix, or "" for none
67         lastHeading string   // last dir heading printed
68
69         short      bool
70         cgoEnabled bool
71         partial    bool
72
73         goExe    string // For host tests
74         goTmpDir string // For host tests
75
76         tests        []distTest
77         timeoutScale int
78
79         worklist []*work
80 }
81
82 type work struct {
83         dt    *distTest
84         cmd   *exec.Cmd
85         start chan bool
86         out   []byte
87         err   error
88         end   chan bool
89 }
90
91 // A distTest is a test run by dist test.
92 // Each test has a unique name and belongs to a group (heading)
93 type distTest struct {
94         name    string // unique test name; may be filtered with -run flag
95         heading string // group section; this header is printed before the test is run.
96         fn      func(*distTest) error
97 }
98
99 func (t *tester) run() {
100         timelog("start", "dist test")
101
102         os.Setenv("PATH", fmt.Sprintf("%s%c%s", gorootBin, os.PathListSeparator, os.Getenv("PATH")))
103
104         t.short = true
105         if v := os.Getenv("GO_TEST_SHORT"); v != "" {
106                 short, err := strconv.ParseBool(v)
107                 if err != nil {
108                         fatalf("invalid GO_TEST_SHORT %q: %v", v, err)
109                 }
110                 t.short = short
111         }
112
113         cmd := exec.Command(gorootBinGo, "env", "CGO_ENABLED", "GOEXE", "GOTMPDIR")
114         cmd.Stderr = new(bytes.Buffer)
115         slurp, err := cmd.Output()
116         if err != nil {
117                 fatalf("Error running %s: %v\n%s", cmd, err, cmd.Stderr)
118         }
119         parts := strings.Split(string(slurp), "\n")
120         if len(parts) < 3 {
121                 fatalf("Error running %s: output contains <3 lines\n%s", cmd, cmd.Stderr)
122         }
123         t.cgoEnabled, _ = strconv.ParseBool(parts[0])
124         t.goExe = parts[1]
125         t.goTmpDir = parts[2]
126
127         if flag.NArg() > 0 && t.runRxStr != "" {
128                 fatalf("the -run regular expression flag is mutually exclusive with test name arguments")
129         }
130
131         t.runNames = flag.Args()
132
133         // Set GOTRACEBACK to system if the user didn't set a level explicitly.
134         // Since we're running tests for Go, we want as much detail as possible
135         // if something goes wrong.
136         //
137         // Set it before running any commands just in case something goes wrong.
138         if ok := isEnvSet("GOTRACEBACK"); !ok {
139                 if err := os.Setenv("GOTRACEBACK", "system"); err != nil {
140                         if t.keepGoing {
141                                 log.Printf("Failed to set GOTRACEBACK: %v", err)
142                         } else {
143                                 fatalf("Failed to set GOTRACEBACK: %v", err)
144                         }
145                 }
146         }
147
148         if t.rebuild {
149                 t.out("Building packages and commands.")
150                 // Force rebuild the whole toolchain.
151                 goInstall(toolenv(), gorootBinGo, append([]string{"-a"}, toolchain...)...)
152         }
153
154         if !t.listMode {
155                 if builder := os.Getenv("GO_BUILDER_NAME"); builder == "" {
156                         // Ensure that installed commands are up to date, even with -no-rebuild,
157                         // so that tests that run commands end up testing what's actually on disk.
158                         // If everything is up-to-date, this is a no-op.
159                         // We first build the toolchain twice to allow it to converge,
160                         // as when we first bootstrap.
161                         // See cmdbootstrap for a description of the overall process.
162                         //
163                         // On the builders, we skip this step: we assume that 'dist test' is
164                         // already using the result of a clean build, and because of test sharding
165                         // and virtualization we usually start with a clean GOCACHE, so we would
166                         // end up rebuilding large parts of the standard library that aren't
167                         // otherwise relevant to the actual set of packages under test.
168                         goInstall(toolenv(), gorootBinGo, toolchain...)
169                         goInstall(toolenv(), gorootBinGo, toolchain...)
170                         goInstall(toolenv(), gorootBinGo, "cmd")
171                 }
172         }
173
174         t.timeoutScale = 1
175         if s := os.Getenv("GO_TEST_TIMEOUT_SCALE"); s != "" {
176                 t.timeoutScale, err = strconv.Atoi(s)
177                 if err != nil {
178                         fatalf("failed to parse $GO_TEST_TIMEOUT_SCALE = %q as integer: %v", s, err)
179                 }
180         }
181
182         if t.runRxStr != "" {
183                 if t.runRxStr[0] == '!' {
184                         t.runRxWant = false
185                         t.runRxStr = t.runRxStr[1:]
186                 } else {
187                         t.runRxWant = true
188                 }
189                 t.runRx = regexp.MustCompile(t.runRxStr)
190         }
191
192         t.registerTests()
193         if t.listMode {
194                 for _, tt := range t.tests {
195                         fmt.Println(tt.name)
196                 }
197                 return
198         }
199
200         for _, name := range t.runNames {
201                 if !t.isRegisteredTestName(name) {
202                         fatalf("unknown test %q", name)
203                 }
204         }
205
206         // On a few builders, make GOROOT unwritable to catch tests writing to it.
207         if strings.HasPrefix(os.Getenv("GO_BUILDER_NAME"), "linux-") {
208                 if os.Getuid() == 0 {
209                         // Don't bother making GOROOT unwritable:
210                         // we're running as root, so permissions would have no effect.
211                 } else {
212                         xatexit(t.makeGOROOTUnwritable())
213                 }
214         }
215
216         if err := t.maybeLogMetadata(); err != nil {
217                 t.failed = true
218                 if t.keepGoing {
219                         log.Printf("Failed logging metadata: %v", err)
220                 } else {
221                         fatalf("Failed logging metadata: %v", err)
222                 }
223         }
224
225         for _, dt := range t.tests {
226                 if !t.shouldRunTest(dt.name) {
227                         t.partial = true
228                         continue
229                 }
230                 dt := dt // dt used in background after this iteration
231                 if err := dt.fn(&dt); err != nil {
232                         t.runPending(&dt) // in case that hasn't been done yet
233                         t.failed = true
234                         if t.keepGoing {
235                                 log.Printf("Failed: %v", err)
236                         } else {
237                                 fatalf("Failed: %v", err)
238                         }
239                 }
240         }
241         t.runPending(nil)
242         timelog("end", "dist test")
243
244         if t.failed {
245                 fmt.Println("\nFAILED")
246                 xexit(1)
247         } else if t.partial {
248                 fmt.Println("\nALL TESTS PASSED (some were excluded)")
249         } else {
250                 fmt.Println("\nALL TESTS PASSED")
251         }
252 }
253
254 func (t *tester) shouldRunTest(name string) bool {
255         if t.runRx != nil {
256                 return t.runRx.MatchString(name) == t.runRxWant
257         }
258         if len(t.runNames) == 0 {
259                 return true
260         }
261         for _, runName := range t.runNames {
262                 if runName == name {
263                         return true
264                 }
265         }
266         return false
267 }
268
269 func (t *tester) maybeLogMetadata() error {
270         if t.compileOnly {
271                 // We need to run a subprocess to log metadata. Don't do that
272                 // on compile-only runs.
273                 return nil
274         }
275         t.out("Test execution environment.")
276         // Helper binary to print system metadata (CPU model, etc). This is a
277         // separate binary from dist so it need not build with the bootstrap
278         // toolchain.
279         //
280         // TODO(prattmic): If we split dist bootstrap and dist test then this
281         // could be simplified to directly use internal/sysinfo here.
282         return t.dirCmd(filepath.Join(goroot, "src/cmd/internal/metadata"), gorootBinGo, []string{"run", "main.go"}).Run()
283 }
284
285 // goTest represents all options to a "go test" command. The final command will
286 // combine configuration from goTest and tester flags.
287 type goTest struct {
288         timeout  time.Duration // If non-zero, override timeout
289         short    bool          // If true, force -short
290         tags     []string      // Build tags
291         race     bool          // Force -race
292         bench    bool          // Run benchmarks (briefly), not tests.
293         runTests string        // Regexp of tests to run
294         cpu      string        // If non-empty, -cpu flag
295         goroot   string        // If non-empty, use alternate goroot for go command
296
297         gcflags   string // If non-empty, build with -gcflags=all=X
298         ldflags   string // If non-empty, build with -ldflags=X
299         buildmode string // If non-empty, -buildmode flag
300
301         dir string   // If non-empty, run in GOROOT/src-relative directory dir
302         env []string // Environment variables to add, as KEY=VAL. KEY= unsets a variable
303
304         // We have both pkg and pkgs as a convenience. Both may be set, in which
305         // case they will be combined. If both are empty, the default is ".".
306         pkgs []string // Multiple packages to test
307         pkg  string   // A single package to test
308
309         testFlags []string // Additional flags accepted by this test
310 }
311
312 // bgCommand returns a go test Cmd. The result has Stdout and Stderr set to nil
313 // and is intended to be added to the work queue.
314 func (opts *goTest) bgCommand(t *tester) *exec.Cmd {
315         goCmd, build, run, pkgs, setupCmd := opts.buildArgs(t)
316
317         // Combine the flags.
318         args := append([]string{"test"}, build...)
319         if t.compileOnly {
320                 args = append(args, "-c", "-o", os.DevNull)
321         } else {
322                 args = append(args, run...)
323         }
324         args = append(args, pkgs...)
325         if !t.compileOnly {
326                 args = append(args, opts.testFlags...)
327         }
328
329         cmd := exec.Command(goCmd, args...)
330         setupCmd(cmd)
331
332         return cmd
333 }
334
335 // command returns a go test Cmd intended to be run immediately.
336 func (opts *goTest) command(t *tester) *exec.Cmd {
337         cmd := opts.bgCommand(t)
338         cmd.Stdout = os.Stdout
339         cmd.Stderr = os.Stderr
340         return cmd
341 }
342
343 func (opts *goTest) run(t *tester) error {
344         return opts.command(t).Run()
345 }
346
347 // runHostTest runs a test that should be built and run on the host GOOS/GOARCH,
348 // but run with GOOS/GOARCH set to the target GOOS/GOARCH. This is for tests
349 // that do nothing but compile and run other binaries. If the host and target
350 // are different, then the assumption is that the target is running in an
351 // emulator and does not have a Go toolchain at all, so the test needs to run on
352 // the host, but its resulting binaries will be run through a go_exec wrapper
353 // that runs them on the target.
354 func (opts *goTest) runHostTest(t *tester) error {
355         goCmd, build, run, pkgs, setupCmd := opts.buildArgs(t)
356
357         // Build the host test binary
358         if len(pkgs) != 1 {
359                 // We can't compile more than one package.
360                 panic("host tests must have a single test package")
361         }
362         if len(opts.env) != 0 {
363                 // It's not clear if these are for the host or the target.
364                 panic("host tests must not have environment variables")
365         }
366
367         f, err := os.CreateTemp(t.goTmpDir, "test.test-*"+t.goExe)
368         if err != nil {
369                 fatalf("failed to create temporary file: %s", err)
370         }
371         bin := f.Name()
372         f.Close()
373         xatexit(func() { os.Remove(bin) })
374
375         args := append([]string{"test", "-c", "-o", bin}, build...)
376         args = append(args, pkgs...)
377         cmd := exec.Command(goCmd, args...)
378         setupCmd(cmd)
379         cmd.Stdout = os.Stdout
380         cmd.Stderr = os.Stderr
381         setEnv(cmd, "GOARCH", gohostarch)
382         setEnv(cmd, "GOOS", gohostos)
383         if vflag > 1 {
384                 errprintf("%s\n", cmd)
385         }
386         if err := cmd.Run(); err != nil {
387                 return err
388         }
389
390         if t.compileOnly {
391                 return nil
392         }
393
394         // Transform run flags to be passed directly to a test binary.
395         for i, f := range run {
396                 if !strings.HasPrefix(f, "-") {
397                         panic("run flag does not start with -: " + f)
398                 }
399                 run[i] = "-test." + f[1:]
400         }
401
402         // Run the test
403         args = append(run, opts.testFlags...)
404         cmd = exec.Command(bin, args...)
405         setupCmd(cmd)
406         cmd.Stdout = os.Stdout
407         cmd.Stderr = os.Stderr
408         if vflag > 1 {
409                 errprintf("%s\n", cmd)
410         }
411         return cmd.Run()
412 }
413
414 // buildArgs is in internal helper for goTest that constructs the elements of
415 // the "go test" command line. goCmd is the path to the go command to use. build
416 // is the flags for building the test. run is the flags for running the test.
417 // pkgs is the list of packages to build and run.
418 //
419 // The caller is responsible for adding opts.testFlags, and must call setupCmd
420 // on the resulting exec.Cmd to set its directory and environment.
421 func (opts *goTest) buildArgs(t *tester) (goCmd string, build, run, pkgs []string, setupCmd func(*exec.Cmd)) {
422         goCmd = gorootBinGo
423         if opts.goroot != "" {
424                 goCmd = filepath.Join(opts.goroot, "bin", "go")
425         }
426
427         run = append(run, "-count=1") // Disallow caching
428         if opts.timeout != 0 {
429                 d := opts.timeout * time.Duration(t.timeoutScale)
430                 run = append(run, "-timeout="+d.String())
431         }
432         if opts.short || t.short {
433                 run = append(run, "-short")
434         }
435         var tags []string
436         if t.iOS() {
437                 tags = append(tags, "lldb")
438         }
439         if noOpt {
440                 tags = append(tags, "noopt")
441         }
442         tags = append(tags, opts.tags...)
443         if len(tags) > 0 {
444                 build = append(build, "-tags="+strings.Join(tags, ","))
445         }
446         if t.race || opts.race {
447                 build = append(build, "-race")
448         }
449         if t.msan {
450                 build = append(build, "-msan")
451         }
452         if t.asan {
453                 build = append(build, "-asan")
454         }
455         if opts.bench {
456                 // Run no tests.
457                 run = append(run, "-run=^$")
458                 // Run benchmarks as a smoke test
459                 run = append(run, "-bench=.*", "-benchtime=.1s")
460         } else if opts.runTests != "" {
461                 run = append(run, "-run="+opts.runTests)
462         }
463         if opts.cpu != "" {
464                 run = append(run, "-cpu="+opts.cpu)
465         }
466
467         if opts.gcflags != "" {
468                 build = append(build, "-gcflags=all="+opts.gcflags)
469         }
470         if opts.ldflags != "" {
471                 build = append(build, "-ldflags="+opts.ldflags)
472         }
473         if opts.buildmode != "" {
474                 build = append(build, "-buildmode="+opts.buildmode)
475         }
476
477         pkgs = opts.pkgs
478         if opts.pkg != "" {
479                 pkgs = append(pkgs[:len(pkgs):len(pkgs)], opts.pkg)
480         }
481         if len(pkgs) == 0 {
482                 pkgs = []string{"."}
483         }
484
485         thisGoroot := goroot
486         if opts.goroot != "" {
487                 thisGoroot = opts.goroot
488         }
489         var dir string
490         if opts.dir != "" {
491                 if filepath.IsAbs(opts.dir) {
492                         panic("dir must be relative, got: " + opts.dir)
493                 }
494                 dir = filepath.Join(thisGoroot, "src", opts.dir)
495         } else {
496                 dir = filepath.Join(thisGoroot, "src")
497         }
498         setupCmd = func(cmd *exec.Cmd) {
499                 setDir(cmd, dir)
500                 if len(opts.env) != 0 {
501                         for _, kv := range opts.env {
502                                 if i := strings.Index(kv, "="); i < 0 {
503                                         unsetEnv(cmd, kv[:len(kv)-1])
504                                 } else {
505                                         setEnv(cmd, kv[:i], kv[i+1:])
506                                 }
507                         }
508                 }
509         }
510
511         return
512 }
513
514 // ranGoTest and stdMatches are state closed over by the stdlib
515 // testing func in registerStdTest below. The tests are run
516 // sequentially, so there's no need for locks.
517 //
518 // ranGoBench and benchMatches are the same, but are only used
519 // in -race mode.
520 var (
521         ranGoTest  bool
522         stdMatches []string
523
524         ranGoBench   bool
525         benchMatches []string
526 )
527
528 func (t *tester) registerStdTest(pkg string) {
529         heading := "Testing packages."
530         testPrefix := "go_test:"
531         gcflags := gogcflags
532
533         testName := testPrefix + pkg
534         if t.runRx == nil || t.runRx.MatchString(testName) == t.runRxWant {
535                 stdMatches = append(stdMatches, pkg)
536         }
537
538         t.tests = append(t.tests, distTest{
539                 name:    testName,
540                 heading: heading,
541                 fn: func(dt *distTest) error {
542                         if ranGoTest {
543                                 return nil
544                         }
545                         t.runPending(dt)
546                         timelog("start", dt.name)
547                         defer timelog("end", dt.name)
548                         ranGoTest = true
549
550                         timeoutSec := 180 * time.Second
551                         for _, pkg := range stdMatches {
552                                 if pkg == "cmd/go" {
553                                         timeoutSec *= 3
554                                         break
555                                 }
556                         }
557                         return (&goTest{
558                                 timeout: timeoutSec,
559                                 gcflags: gcflags,
560                                 pkgs:    stdMatches,
561                         }).run(t)
562                 },
563         })
564 }
565
566 func (t *tester) registerRaceBenchTest(pkg string) {
567         testName := "go_test_bench:" + pkg
568         if t.runRx == nil || t.runRx.MatchString(testName) == t.runRxWant {
569                 benchMatches = append(benchMatches, pkg)
570         }
571         t.tests = append(t.tests, distTest{
572                 name:    testName,
573                 heading: "Running benchmarks briefly.",
574                 fn: func(dt *distTest) error {
575                         if ranGoBench {
576                                 return nil
577                         }
578                         t.runPending(dt)
579                         timelog("start", dt.name)
580                         defer timelog("end", dt.name)
581                         ranGoBench = true
582                         return (&goTest{
583                                 timeout: 1200 * time.Second, // longer timeout for race with benchmarks
584                                 race:    true,
585                                 bench:   true,
586                                 cpu:     "4",
587                                 pkgs:    benchMatches,
588                         }).run(t)
589                 },
590         })
591 }
592
593 func (t *tester) registerTests() {
594         // registerStdTestSpecially tracks import paths in the standard library
595         // whose test registration happens in a special way.
596         registerStdTestSpecially := map[string]bool{
597                 "internal/testdir": true, // Registered at the bottom with sharding.
598                 // cgo tests are registered specially because they involve unusual build
599                 // conditions and flags.
600                 "cmd/cgo/internal/teststdio":      true,
601                 "cmd/cgo/internal/testlife":       true,
602                 "cmd/cgo/internal/testfortran":    true,
603                 "cmd/cgo/internal/testgodefs":     true,
604                 "cmd/cgo/internal/testso":         true,
605                 "cmd/cgo/internal/testsovar":      true,
606                 "cmd/cgo/internal/testcarchive":   true,
607                 "cmd/cgo/internal/testcshared":    true,
608                 "cmd/cgo/internal/testshared":     true,
609                 "cmd/cgo/internal/testplugin":     true,
610                 "cmd/cgo/internal/testsanitizers": true,
611                 "cmd/cgo/internal/testerrors":     true,
612         }
613
614         // Fast path to avoid the ~1 second of `go list std cmd` when
615         // the caller lists specific tests to run. (as the continuous
616         // build coordinator does).
617         if len(t.runNames) > 0 {
618                 for _, name := range t.runNames {
619                         if strings.HasPrefix(name, "go_test:") {
620                                 t.registerStdTest(strings.TrimPrefix(name, "go_test:"))
621                         }
622                         if strings.HasPrefix(name, "go_test_bench:") {
623                                 t.registerRaceBenchTest(strings.TrimPrefix(name, "go_test_bench:"))
624                         }
625                 }
626         } else {
627                 // Use a format string to only list packages and commands that have tests.
628                 const format = "{{if (or .TestGoFiles .XTestGoFiles)}}{{.ImportPath}}{{end}}"
629                 cmd := exec.Command(gorootBinGo, "list", "-f", format)
630                 if t.race {
631                         cmd.Args = append(cmd.Args, "-tags=race")
632                 }
633                 cmd.Args = append(cmd.Args, "std", "cmd")
634                 cmd.Stderr = new(bytes.Buffer)
635                 all, err := cmd.Output()
636                 if err != nil {
637                         fatalf("Error running go list std cmd: %v:\n%s", err, cmd.Stderr)
638                 }
639                 pkgs := strings.Fields(string(all))
640                 for _, pkg := range pkgs {
641                         if registerStdTestSpecially[pkg] {
642                                 continue
643                         }
644                         t.registerStdTest(pkg)
645                 }
646                 if t.race {
647                         for _, pkg := range pkgs {
648                                 if registerStdTestSpecially[pkg] {
649                                         continue
650                                 }
651                                 if t.packageHasBenchmarks(pkg) {
652                                         t.registerRaceBenchTest(pkg)
653                                 }
654                         }
655                 }
656         }
657
658         if t.race {
659                 return
660         }
661
662         // Test the os/user package in the pure-Go mode too.
663         if !t.compileOnly {
664                 t.registerTest("osusergo", "os/user with tag osusergo",
665                         &goTest{
666                                 timeout: 300 * time.Second,
667                                 tags:    []string{"osusergo"},
668                                 pkg:     "os/user",
669                         })
670                 t.registerTest("purego:hash/maphash", "hash/maphash purego implementation",
671                         &goTest{
672                                 timeout: 300 * time.Second,
673                                 tags:    []string{"purego"},
674                                 pkg:     "hash/maphash",
675                         })
676         }
677
678         // Test ios/amd64 for the iOS simulator.
679         if goos == "darwin" && goarch == "amd64" && t.cgoEnabled {
680                 t.registerTest("amd64ios", "GOOS=ios on darwin/amd64",
681                         &goTest{
682                                 timeout:  300 * time.Second,
683                                 runTests: "SystemRoots",
684                                 env:      []string{"GOOS=ios", "CGO_ENABLED=1"},
685                                 pkg:      "crypto/x509",
686                         })
687         }
688
689         // Runtime CPU tests.
690         if !t.compileOnly && t.hasParallelism() {
691                 t.registerTest("runtime:cpu124", "GOMAXPROCS=2 runtime -cpu=1,2,4 -quick",
692                         &goTest{
693                                 timeout:   300 * time.Second,
694                                 cpu:       "1,2,4",
695                                 short:     true,
696                                 testFlags: []string{"-quick"},
697                                 // We set GOMAXPROCS=2 in addition to -cpu=1,2,4 in order to test runtime bootstrap code,
698                                 // creation of first goroutines and first garbage collections in the parallel setting.
699                                 env: []string{"GOMAXPROCS=2"},
700                                 pkg: "runtime",
701                         })
702         }
703
704         // morestack tests. We only run these on in long-test mode
705         // (with GO_TEST_SHORT=false) because the runtime test is
706         // already quite long and mayMoreStackMove makes it about
707         // twice as slow.
708         if !t.compileOnly && !t.short {
709                 // hooks is the set of maymorestack hooks to test with.
710                 hooks := []string{"mayMoreStackPreempt", "mayMoreStackMove"}
711                 // pkgs is the set of test packages to run.
712                 pkgs := []string{"runtime", "reflect", "sync"}
713                 // hookPkgs is the set of package patterns to apply
714                 // the maymorestack hook to.
715                 hookPkgs := []string{"runtime/...", "reflect", "sync"}
716                 // unhookPkgs is the set of package patterns to
717                 // exclude from hookPkgs.
718                 unhookPkgs := []string{"runtime/testdata/..."}
719                 for _, hook := range hooks {
720                         // Construct the build flags to use the
721                         // maymorestack hook in the compiler and
722                         // assembler. We pass this via the GOFLAGS
723                         // environment variable so that it applies to
724                         // both the test itself and to binaries built
725                         // by the test.
726                         goFlagsList := []string{}
727                         for _, flag := range []string{"-gcflags", "-asmflags"} {
728                                 for _, hookPkg := range hookPkgs {
729                                         goFlagsList = append(goFlagsList, flag+"="+hookPkg+"=-d=maymorestack=runtime."+hook)
730                                 }
731                                 for _, unhookPkg := range unhookPkgs {
732                                         goFlagsList = append(goFlagsList, flag+"="+unhookPkg+"=")
733                                 }
734                         }
735                         goFlags := strings.Join(goFlagsList, " ")
736
737                         for _, pkg := range pkgs {
738                                 t.registerTest(hook+":"+pkg, "maymorestack="+hook,
739                                         &goTest{
740                                                 timeout: 600 * time.Second,
741                                                 short:   true,
742                                                 env:     []string{"GOFLAGS=" + goFlags},
743                                                 pkg:     pkg,
744                                         })
745                         }
746                 }
747         }
748
749         // On the builders only, test that a moved GOROOT still works.
750         // Fails on iOS because CC_FOR_TARGET refers to clangwrap.sh
751         // in the unmoved GOROOT.
752         // Fails on Android, js/wasm and wasip1/wasm with an exec format error.
753         // Fails on plan9 with "cannot find GOROOT" (issue #21016).
754         if os.Getenv("GO_BUILDER_NAME") != "" && goos != "android" && !t.iOS() && goos != "plan9" && goos != "js" && goos != "wasip1" {
755                 t.tests = append(t.tests, distTest{
756                         name:    "moved_goroot",
757                         heading: "moved GOROOT",
758                         fn: func(dt *distTest) error {
759                                 t.runPending(dt)
760                                 timelog("start", dt.name)
761                                 defer timelog("end", dt.name)
762                                 moved := goroot + "-moved"
763                                 if err := os.Rename(goroot, moved); err != nil {
764                                         if goos == "windows" {
765                                                 // Fails on Windows (with "Access is denied") if a process
766                                                 // or binary is in this directory. For instance, using all.bat
767                                                 // when run from c:\workdir\go\src fails here
768                                                 // if GO_BUILDER_NAME is set. Our builders invoke tests
769                                                 // a different way which happens to work when sharding
770                                                 // tests, but we should be tolerant of the non-sharded
771                                                 // all.bat case.
772                                                 log.Printf("skipping test on Windows")
773                                                 return nil
774                                         }
775                                         return err
776                                 }
777
778                                 // Run `go test fmt` in the moved GOROOT, without explicitly setting
779                                 // GOROOT in the environment. The 'go' command should find itself.
780                                 cmd := (&goTest{
781                                         goroot: moved,
782                                         pkg:    "fmt",
783                                 }).command(t)
784                                 unsetEnv(cmd, "GOROOT")
785                                 err := cmd.Run()
786
787                                 if rerr := os.Rename(moved, goroot); rerr != nil {
788                                         fatalf("failed to restore GOROOT: %v", rerr)
789                                 }
790                                 return err
791                         },
792                 })
793         }
794
795         // Test that internal linking of standard packages does not
796         // require libgcc. This ensures that we can install a Go
797         // release on a system that does not have a C compiler
798         // installed and still build Go programs (that don't use cgo).
799         for _, pkg := range cgoPackages {
800                 if !t.internalLink() {
801                         break
802                 }
803
804                 // ARM libgcc may be Thumb, which internal linking does not support.
805                 if goarch == "arm" {
806                         break
807                 }
808
809                 // What matters is that the tests build and start up.
810                 // Skip expensive tests, especially x509 TestSystemRoots.
811                 run := "^Test[^CS]"
812                 if pkg == "net" {
813                         run = "TestTCPStress"
814                 }
815                 t.registerTest("nolibgcc:"+pkg, "Testing without libgcc.",
816                         &goTest{
817                                 ldflags:  "-linkmode=internal -libgcc=none",
818                                 runTests: run,
819                                 pkg:      pkg,
820                         })
821         }
822
823         // Stub out following test on alpine until 54354 resolved.
824         builderName := os.Getenv("GO_BUILDER_NAME")
825         disablePIE := strings.HasSuffix(builderName, "-alpine")
826
827         // Test internal linking of PIE binaries where it is supported.
828         if t.internalLinkPIE() && !disablePIE {
829                 t.registerTest("pie_internal", "internal linking of -buildmode=pie",
830                         &goTest{
831                                 timeout:   60 * time.Second,
832                                 buildmode: "pie",
833                                 ldflags:   "-linkmode=internal",
834                                 env:       []string{"CGO_ENABLED=0"},
835                                 pkg:       "reflect",
836                         })
837                 // Also test a cgo package.
838                 if t.cgoEnabled && t.internalLink() && !disablePIE {
839                         t.registerTest("pie_internal_cgo", "internal linking of -buildmode=pie",
840                                 &goTest{
841                                         timeout:   60 * time.Second,
842                                         buildmode: "pie",
843                                         ldflags:   "-linkmode=internal",
844                                         pkg:       "os/user",
845                                 })
846                 }
847         }
848
849         // sync tests
850         if t.hasParallelism() {
851                 t.registerTest("sync_cpu", "sync -cpu=10",
852                         &goTest{
853                                 timeout: 120 * time.Second,
854                                 cpu:     "10",
855                                 pkg:     "sync",
856                         })
857         }
858
859         if t.raceDetectorSupported() {
860                 t.registerRaceTests()
861         }
862
863         if t.cgoEnabled && !t.iOS() {
864                 // Disabled on iOS. golang.org/issue/15919
865                 t.registerTest("cgo_teststdio", "", &goTest{dir: "cmd/cgo/internal/teststdio", timeout: 5 * time.Minute}, rtHostTest{})
866                 t.registerTest("cgo_testlife", "", &goTest{dir: "cmd/cgo/internal/testlife", timeout: 5 * time.Minute}, rtHostTest{})
867                 if goos != "android" {
868                         t.registerTest("cgo_testfortran", "", &goTest{dir: "cmd/cgo/internal/testfortran", timeout: 5 * time.Minute}, rtHostTest{})
869                 }
870                 if t.hasSwig() && goos != "android" {
871                         t.registerTest("swig_stdio", "", &goTest{dir: "../misc/swig/stdio"})
872                         if t.hasCxx() {
873                                 t.registerTest("swig_callback", "", &goTest{dir: "../misc/swig/callback"})
874                                 const cflags = "-flto -Wno-lto-type-mismatch -Wno-unknown-warning-option"
875                                 t.registerTest("swig_callback_lto", "",
876                                         &goTest{
877                                                 dir: "../misc/swig/callback",
878                                                 env: []string{
879                                                         "CGO_CFLAGS=" + cflags,
880                                                         "CGO_CXXFLAGS=" + cflags,
881                                                         "CGO_LDFLAGS=" + cflags,
882                                                 },
883                                         })
884                         }
885                 }
886         }
887         if t.cgoEnabled {
888                 t.registerCgoTests()
889         }
890
891         // Don't run these tests with $GO_GCFLAGS because most of them
892         // assume that they can run "go install" with no -gcflags and not
893         // recompile the entire standard library. If make.bash ran with
894         // special -gcflags, that's not true.
895         if t.cgoEnabled && gogcflags == "" {
896                 t.registerTest("cgo_testgodefs", "", &goTest{dir: "cmd/cgo/internal/testgodefs", timeout: 5 * time.Minute}, rtHostTest{})
897
898                 t.registerTest("cgo_testso", "", &goTest{dir: "cmd/cgo/internal/testso", timeout: 600 * time.Second})
899                 t.registerTest("cgo_testsovar", "", &goTest{dir: "cmd/cgo/internal/testsovar", timeout: 600 * time.Second})
900                 if t.supportedBuildmode("c-archive") {
901                         t.registerTest("cgo_testcarchive", "", &goTest{dir: "cmd/cgo/internal/testcarchive", timeout: 5 * time.Minute}, rtHostTest{})
902                 }
903                 if t.supportedBuildmode("c-shared") {
904                         t.registerTest("cgo_testcshared", "", &goTest{dir: "cmd/cgo/internal/testcshared", timeout: 5 * time.Minute}, rtHostTest{})
905                 }
906                 if t.supportedBuildmode("shared") {
907                         t.registerTest("cgo_testshared", "", &goTest{dir: "cmd/cgo/internal/testshared", timeout: 600 * time.Second})
908                 }
909                 if t.supportedBuildmode("plugin") {
910                         t.registerTest("cgo_testplugin", "", &goTest{dir: "cmd/cgo/internal/testplugin", timeout: 600 * time.Second})
911                 }
912                 if goos == "linux" || (goos == "freebsd" && goarch == "amd64") {
913                         // because Pdeathsig of syscall.SysProcAttr struct used in cmd/cgo/internal/testsanitizers is only
914                         // supported on Linux and FreeBSD.
915                         t.registerTest("cgo_testsanitizers", "", &goTest{dir: "cmd/cgo/internal/testsanitizers", timeout: 5 * time.Minute}, rtHostTest{})
916                 }
917                 if t.hasBash() && goos != "android" && !t.iOS() && gohostos != "windows" {
918                         t.registerTest("cgo_errors", "", &goTest{dir: "cmd/cgo/internal/testerrors", timeout: 5 * time.Minute}, rtHostTest{})
919                 }
920         }
921
922         if goos != "android" && !t.iOS() {
923                 // There are no tests in this directory, only benchmarks.
924                 // Check that the test binary builds.
925                 t.registerTest("bench_go1", "", &goTest{dir: "../test/bench/go1"})
926         }
927         if goos != "android" && !t.iOS() {
928                 // Only start multiple test dir shards on builders,
929                 // where they get distributed to multiple machines.
930                 // See issues 20141 and 31834.
931                 nShards := 1
932                 if os.Getenv("GO_BUILDER_NAME") != "" {
933                         nShards = 10
934                 }
935                 if n, err := strconv.Atoi(os.Getenv("GO_TEST_SHARDS")); err == nil {
936                         nShards = n
937                 }
938                 for shard := 0; shard < nShards; shard++ {
939                         t.registerTest(
940                                 fmt.Sprintf("test:%d_%d", shard, nShards),
941                                 "../test",
942                                 &goTest{
943                                         dir:       "internal/testdir",
944                                         testFlags: []string{fmt.Sprintf("-shard=%d", shard), fmt.Sprintf("-shards=%d", nShards)},
945                                 },
946                                 rtHostTest{},
947                         )
948                 }
949         }
950         // Only run the API check on fast development platforms.
951         // Every platform checks the API on every GOOS/GOARCH/CGO_ENABLED combination anyway,
952         // so we really only need to run this check once anywhere to get adequate coverage.
953         // To help developers avoid trybot-only failures, we try to run on typical developer machines
954         // which is darwin,linux,windows/amd64 and darwin/arm64.
955         if goos == "darwin" || ((goos == "linux" || goos == "windows") && goarch == "amd64") {
956                 t.registerTest("api", "", &goTest{dir: "cmd/api", timeout: 5 * time.Minute, testFlags: []string{"-check"}})
957         }
958
959         // Ensure that the toolchain can bootstrap itself.
960         // This test adds another ~45s to all.bash if run sequentially, so run it only on the builders.
961         if os.Getenv("GO_BUILDER_NAME") != "" && goos != "android" && !t.iOS() {
962                 t.registerTest("reboot", "", &goTest{dir: "../misc/reboot", timeout: 5 * time.Minute}, rtHostTest{})
963         }
964 }
965
966 // isRegisteredTestName reports whether a test named testName has already
967 // been registered.
968 func (t *tester) isRegisteredTestName(testName string) bool {
969         for _, tt := range t.tests {
970                 if tt.name == testName {
971                         return true
972                 }
973         }
974         return false
975 }
976
977 type registerTestOpt interface {
978         isRegisterTestOpt()
979 }
980
981 // rtSequential is a registerTest option that causes the registered test to run
982 // sequentially.
983 type rtSequential struct{}
984
985 func (rtSequential) isRegisterTestOpt() {}
986
987 // rtPreFunc is a registerTest option that runs a pre function before running
988 // the test.
989 type rtPreFunc struct {
990         pre func(*distTest) bool // Return false to skip the test
991 }
992
993 func (rtPreFunc) isRegisterTestOpt() {}
994
995 // rtHostTest is a registerTest option that indicates this is a host test that
996 // should be run using goTest.runHostTest. It implies rtSequential.
997 type rtHostTest struct{}
998
999 func (rtHostTest) isRegisterTestOpt() {}
1000
1001 // registerTest registers a test that runs the given goTest.
1002 //
1003 // If heading is "", it uses test.dir as the heading.
1004 func (t *tester) registerTest(name, heading string, test *goTest, opts ...registerTestOpt) {
1005         seq := false
1006         hostTest := false
1007         var preFunc func(*distTest) bool
1008         for _, opt := range opts {
1009                 switch opt := opt.(type) {
1010                 case rtSequential:
1011                         seq = true
1012                 case rtPreFunc:
1013                         preFunc = opt.pre
1014                 case rtHostTest:
1015                         seq, hostTest = true, true
1016                 }
1017         }
1018         if t.isRegisteredTestName(name) {
1019                 panic("duplicate registered test name " + name)
1020         }
1021         if heading == "" {
1022                 heading = test.dir
1023         }
1024         t.tests = append(t.tests, distTest{
1025                 name:    name,
1026                 heading: heading,
1027                 fn: func(dt *distTest) error {
1028                         if preFunc != nil && !preFunc(dt) {
1029                                 return nil
1030                         }
1031                         if seq {
1032                                 t.runPending(dt)
1033                                 if hostTest {
1034                                         return test.runHostTest(t)
1035                                 }
1036                                 return test.run(t)
1037                         }
1038                         w := &work{
1039                                 dt:  dt,
1040                                 cmd: test.bgCommand(t),
1041                         }
1042                         t.worklist = append(t.worklist, w)
1043                         return nil
1044                 },
1045         })
1046 }
1047
1048 // bgDirCmd constructs a Cmd intended to be run in the background as
1049 // part of the worklist. The worklist runner will buffer its output
1050 // and replay it sequentially. The command will be run in dir.
1051 func (t *tester) bgDirCmd(dir, bin string, args ...string) *exec.Cmd {
1052         cmd := exec.Command(bin, args...)
1053         if filepath.IsAbs(dir) {
1054                 setDir(cmd, dir)
1055         } else {
1056                 setDir(cmd, filepath.Join(goroot, dir))
1057         }
1058         return cmd
1059 }
1060
1061 // dirCmd constructs a Cmd intended to be run in the foreground.
1062 // The command will be run in dir, and Stdout and Stderr will go to os.Stdout
1063 // and os.Stderr.
1064 func (t *tester) dirCmd(dir string, cmdline ...interface{}) *exec.Cmd {
1065         bin, args := flattenCmdline(cmdline)
1066         cmd := t.bgDirCmd(dir, bin, args...)
1067         cmd.Stdout = os.Stdout
1068         cmd.Stderr = os.Stderr
1069         if vflag > 1 {
1070                 errprintf("%s\n", strings.Join(cmd.Args, " "))
1071         }
1072         return cmd
1073 }
1074
1075 // flattenCmdline flattens a mixture of string and []string as single list
1076 // and then interprets it as a command line: first element is binary, then args.
1077 func flattenCmdline(cmdline []interface{}) (bin string, args []string) {
1078         var list []string
1079         for _, x := range cmdline {
1080                 switch x := x.(type) {
1081                 case string:
1082                         list = append(list, x)
1083                 case []string:
1084                         list = append(list, x...)
1085                 default:
1086                         panic("invalid addCmd argument type: " + reflect.TypeOf(x).String())
1087                 }
1088         }
1089
1090         bin = list[0]
1091         if !filepath.IsAbs(bin) {
1092                 panic("command is not absolute: " + bin)
1093         }
1094         return bin, list[1:]
1095 }
1096
1097 // addCmd adds a command to the worklist. Commands can be run in
1098 // parallel, but their output will be buffered and replayed in the
1099 // order they were added to worklist.
1100 func (t *tester) addCmd(dt *distTest, dir string, cmdline ...interface{}) *exec.Cmd {
1101         bin, args := flattenCmdline(cmdline)
1102         w := &work{
1103                 dt:  dt,
1104                 cmd: t.bgDirCmd(dir, bin, args...),
1105         }
1106         t.worklist = append(t.worklist, w)
1107         return w.cmd
1108 }
1109
1110 func (t *tester) iOS() bool {
1111         return goos == "ios"
1112 }
1113
1114 func (t *tester) out(v string) {
1115         if t.banner == "" {
1116                 return
1117         }
1118         fmt.Println("\n" + t.banner + v)
1119 }
1120
1121 // extLink reports whether the current goos/goarch supports
1122 // external linking. This should match the test in determineLinkMode
1123 // in cmd/link/internal/ld/config.go.
1124 func (t *tester) extLink() bool {
1125         if goarch == "ppc64" && goos != "aix" {
1126                 return false
1127         }
1128         return true
1129 }
1130
1131 func (t *tester) internalLink() bool {
1132         if gohostos == "dragonfly" {
1133                 // linkmode=internal fails on dragonfly since errno is a TLS relocation.
1134                 return false
1135         }
1136         if goos == "android" {
1137                 return false
1138         }
1139         if goos == "ios" {
1140                 return false
1141         }
1142         if goos == "windows" && goarch == "arm64" {
1143                 return false
1144         }
1145         // Internally linking cgo is incomplete on some architectures.
1146         // https://golang.org/issue/10373
1147         // https://golang.org/issue/14449
1148         if goarch == "loong64" || goarch == "mips64" || goarch == "mips64le" || goarch == "mips" || goarch == "mipsle" || goarch == "riscv64" {
1149                 return false
1150         }
1151         if goos == "aix" {
1152                 // linkmode=internal isn't supported.
1153                 return false
1154         }
1155         return true
1156 }
1157
1158 func (t *tester) internalLinkPIE() bool {
1159         switch goos + "-" + goarch {
1160         case "darwin-amd64", "darwin-arm64",
1161                 "linux-amd64", "linux-arm64", "linux-ppc64le",
1162                 "android-arm64",
1163                 "windows-amd64", "windows-386", "windows-arm":
1164                 return true
1165         }
1166         return false
1167 }
1168
1169 // supportedBuildMode reports whether the given build mode is supported.
1170 func (t *tester) supportedBuildmode(mode string) bool {
1171         switch mode {
1172         case "c-archive", "c-shared", "shared", "plugin", "pie":
1173         default:
1174                 fatalf("internal error: unknown buildmode %s", mode)
1175                 return false
1176         }
1177
1178         return buildModeSupported("gc", mode, goos, goarch)
1179 }
1180
1181 func (t *tester) registerCgoTests() {
1182         cgoTest := func(name string, subdir, linkmode, buildmode string, opts ...registerTestOpt) *goTest {
1183                 gt := &goTest{
1184                         dir:       "../misc/cgo/" + subdir,
1185                         buildmode: buildmode,
1186                         ldflags:   "-linkmode=" + linkmode,
1187                 }
1188
1189                 if linkmode == "internal" {
1190                         gt.tags = append(gt.tags, "internal")
1191                         if buildmode == "pie" {
1192                                 gt.tags = append(gt.tags, "internal_pie")
1193                         }
1194                 }
1195                 if buildmode == "static" {
1196                         // This isn't actually a Go buildmode, just a convenient way to tell
1197                         // cgoTest we want static linking.
1198                         gt.buildmode = ""
1199                         if linkmode == "external" {
1200                                 gt.ldflags += ` -extldflags "-static -pthread"`
1201                         } else if linkmode == "auto" {
1202                                 gt.env = append(gt.env, "CGO_LDFLAGS=-static -pthread")
1203                         } else {
1204                                 panic("unknown linkmode with static build: " + linkmode)
1205                         }
1206                         gt.tags = append(gt.tags, "static")
1207                 }
1208
1209                 t.registerTest("cgo:"+name, "../misc/cgo/test", gt, opts...)
1210                 return gt
1211         }
1212
1213         cgoTest("test-auto", "test", "auto", "")
1214
1215         // Stub out various buildmode=pie tests  on alpine until 54354 resolved.
1216         builderName := os.Getenv("GO_BUILDER_NAME")
1217         disablePIE := strings.HasSuffix(builderName, "-alpine")
1218
1219         if t.internalLink() {
1220                 cgoTest("test-internal", "test", "internal", "")
1221         }
1222
1223         os := gohostos
1224         p := gohostos + "/" + goarch
1225         switch {
1226         case os == "darwin", os == "windows":
1227                 if !t.extLink() {
1228                         break
1229                 }
1230                 // test linkmode=external, but __thread not supported, so skip testtls.
1231                 cgoTest("test-external", "test", "external", "")
1232
1233                 gt := cgoTest("test-external-s", "test", "external", "")
1234                 gt.ldflags += " -s"
1235
1236                 if t.supportedBuildmode("pie") && !disablePIE {
1237                         cgoTest("test-auto-pie", "test", "auto", "pie")
1238                         if t.internalLink() && t.internalLinkPIE() {
1239                                 cgoTest("test-internal-pie", "test", "internal", "pie")
1240                         }
1241                 }
1242
1243         case os == "aix", os == "android", os == "dragonfly", os == "freebsd", os == "linux", os == "netbsd", os == "openbsd":
1244                 gt := cgoTest("test-external-g0", "test", "external", "")
1245                 gt.env = append(gt.env, "CGO_CFLAGS=-g0 -fdiagnostics-color")
1246
1247                 cgoTest("testtls-auto", "testtls", "auto", "")
1248                 cgoTest("testtls-external", "testtls", "external", "")
1249                 switch {
1250                 case os == "aix":
1251                         // no static linking
1252                 case p == "freebsd/arm":
1253                         // -fPIC compiled tls code will use __tls_get_addr instead
1254                         // of __aeabi_read_tp, however, on FreeBSD/ARM, __tls_get_addr
1255                         // is implemented in rtld-elf, so -fPIC isn't compatible with
1256                         // static linking on FreeBSD/ARM with clang. (cgo depends on
1257                         // -fPIC fundamentally.)
1258                 default:
1259                         // Check for static linking support
1260                         var staticCheck rtPreFunc
1261                         ccName := compilerEnvLookup("CC", defaultcc, goos, goarch)
1262                         cc, err := exec.LookPath(ccName)
1263                         if err != nil {
1264                                 staticCheck.pre = func(*distTest) bool {
1265                                         fmt.Printf("$CC (%q) not found, skip cgo static linking test.\n", ccName)
1266                                         return false
1267                                 }
1268                         } else {
1269                                 cmd := t.dirCmd("misc/cgo/test", cc, "-xc", "-o", "/dev/null", "-static", "-")
1270                                 cmd.Stdin = strings.NewReader("int main() {}")
1271                                 cmd.Stdout, cmd.Stderr = nil, nil // Discard output
1272                                 if err := cmd.Run(); err != nil {
1273                                         // Skip these tests
1274                                         staticCheck.pre = func(*distTest) bool {
1275                                                 fmt.Println("No support for static linking found (lacks libc.a?), skip cgo static linking test.")
1276                                                 return false
1277                                         }
1278                                 }
1279                         }
1280
1281                         // Doing a static link with boringcrypto gets
1282                         // a C linker warning on Linux.
1283                         // in function `bio_ip_and_port_to_socket_and_addr':
1284                         // warning: Using 'getaddrinfo' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
1285                         if staticCheck.pre == nil && goos == "linux" && strings.Contains(goexperiment, "boringcrypto") {
1286                                 staticCheck.pre = func(*distTest) bool {
1287                                         fmt.Println("skipping static linking check on Linux when using boringcrypto to avoid C linker warning about getaddrinfo")
1288                                         return false
1289                                 }
1290                         }
1291
1292                         // Static linking tests
1293                         if goos != "android" && p != "netbsd/arm" {
1294                                 // TODO(#56629): Why does this fail on netbsd-arm?
1295                                 cgoTest("testtls-static", "testtls", "external", "static", staticCheck)
1296                         }
1297                         cgoTest("nocgo-auto", "nocgo", "auto", "", staticCheck)
1298                         cgoTest("nocgo-external", "nocgo", "external", "", staticCheck)
1299                         if goos != "android" {
1300                                 cgoTest("nocgo-static", "nocgo", "external", "static", staticCheck)
1301                                 cgoTest("test-static", "test", "external", "static", staticCheck)
1302                                 // -static in CGO_LDFLAGS triggers a different code path
1303                                 // than -static in -extldflags, so test both.
1304                                 // See issue #16651.
1305                                 if goarch != "loong64" {
1306                                         // TODO(#56623): Why does this fail on loong64?
1307                                         cgoTest("test-static-env", "test", "auto", "static", staticCheck)
1308                                 }
1309                         }
1310
1311                         // PIE linking tests
1312                         if t.supportedBuildmode("pie") && !disablePIE {
1313                                 cgoTest("test-pie", "test", "auto", "pie")
1314                                 if t.internalLink() && t.internalLinkPIE() {
1315                                         cgoTest("test-pie-internal", "test", "internal", "pie")
1316                                 }
1317                                 cgoTest("testtls-pie", "testtls", "auto", "pie")
1318                                 cgoTest("nocgo-pie", "nocgo", "auto", "pie")
1319                         }
1320                 }
1321         }
1322 }
1323
1324 // run pending test commands, in parallel, emitting headers as appropriate.
1325 // When finished, emit header for nextTest, which is going to run after the
1326 // pending commands are done (and runPending returns).
1327 // A test should call runPending if it wants to make sure that it is not
1328 // running in parallel with earlier tests, or if it has some other reason
1329 // for needing the earlier tests to be done.
1330 func (t *tester) runPending(nextTest *distTest) {
1331         worklist := t.worklist
1332         t.worklist = nil
1333         for _, w := range worklist {
1334                 w.start = make(chan bool)
1335                 w.end = make(chan bool)
1336                 go func(w *work) {
1337                         if !<-w.start {
1338                                 timelog("skip", w.dt.name)
1339                                 w.out = []byte(fmt.Sprintf("skipped due to earlier error\n"))
1340                         } else {
1341                                 timelog("start", w.dt.name)
1342                                 w.out, w.err = w.cmd.CombinedOutput()
1343                                 if w.err != nil {
1344                                         if isUnsupportedVMASize(w) {
1345                                                 timelog("skip", w.dt.name)
1346                                                 w.out = []byte(fmt.Sprintf("skipped due to unsupported VMA\n"))
1347                                                 w.err = nil
1348                                         }
1349                                 }
1350                         }
1351                         timelog("end", w.dt.name)
1352                         w.end <- true
1353                 }(w)
1354         }
1355
1356         started := 0
1357         ended := 0
1358         var last *distTest
1359         for ended < len(worklist) {
1360                 for started < len(worklist) && started-ended < maxbg {
1361                         w := worklist[started]
1362                         started++
1363                         w.start <- !t.failed || t.keepGoing
1364                 }
1365                 w := worklist[ended]
1366                 dt := w.dt
1367                 if dt.heading != "" && t.lastHeading != dt.heading {
1368                         t.lastHeading = dt.heading
1369                         t.out(dt.heading)
1370                 }
1371                 if dt != last {
1372                         // Assumes all the entries for a single dt are in one worklist.
1373                         last = w.dt
1374                         if vflag > 0 {
1375                                 fmt.Printf("# go tool dist test -run=^%s$\n", dt.name)
1376                         }
1377                 }
1378                 if vflag > 1 {
1379                         errprintf("%s\n", strings.Join(w.cmd.Args, " "))
1380                 }
1381                 ended++
1382                 <-w.end
1383                 os.Stdout.Write(w.out)
1384                 if w.err != nil {
1385                         log.Printf("Failed: %v", w.err)
1386                         t.failed = true
1387                 }
1388         }
1389         if t.failed && !t.keepGoing {
1390                 fatalf("FAILED")
1391         }
1392
1393         if dt := nextTest; dt != nil {
1394                 if dt.heading != "" && t.lastHeading != dt.heading {
1395                         t.lastHeading = dt.heading
1396                         t.out(dt.heading)
1397                 }
1398                 if vflag > 0 {
1399                         fmt.Printf("# go tool dist test -run=^%s$\n", dt.name)
1400                 }
1401         }
1402 }
1403
1404 func (t *tester) hasBash() bool {
1405         switch gohostos {
1406         case "windows", "plan9":
1407                 return false
1408         }
1409         return true
1410 }
1411
1412 func (t *tester) hasCxx() bool {
1413         cxx, _ := exec.LookPath(compilerEnvLookup("CXX", defaultcxx, goos, goarch))
1414         return cxx != ""
1415 }
1416
1417 func (t *tester) hasSwig() bool {
1418         swig, err := exec.LookPath("swig")
1419         if err != nil {
1420                 return false
1421         }
1422
1423         // Check that swig was installed with Go support by checking
1424         // that a go directory exists inside the swiglib directory.
1425         // See https://golang.org/issue/23469.
1426         output, err := exec.Command(swig, "-go", "-swiglib").Output()
1427         if err != nil {
1428                 return false
1429         }
1430         swigDir := strings.TrimSpace(string(output))
1431
1432         _, err = os.Stat(filepath.Join(swigDir, "go"))
1433         if err != nil {
1434                 return false
1435         }
1436
1437         // Check that swig has a new enough version.
1438         // See https://golang.org/issue/22858.
1439         out, err := exec.Command(swig, "-version").CombinedOutput()
1440         if err != nil {
1441                 return false
1442         }
1443
1444         re := regexp.MustCompile(`[vV]ersion +(\d+)([.]\d+)?([.]\d+)?`)
1445         matches := re.FindSubmatch(out)
1446         if matches == nil {
1447                 // Can't find version number; hope for the best.
1448                 return true
1449         }
1450
1451         major, err := strconv.Atoi(string(matches[1]))
1452         if err != nil {
1453                 // Can't find version number; hope for the best.
1454                 return true
1455         }
1456         if major < 3 {
1457                 return false
1458         }
1459         if major > 3 {
1460                 // 4.0 or later
1461                 return true
1462         }
1463
1464         // We have SWIG version 3.x.
1465         if len(matches[2]) > 0 {
1466                 minor, err := strconv.Atoi(string(matches[2][1:]))
1467                 if err != nil {
1468                         return true
1469                 }
1470                 if minor > 0 {
1471                         // 3.1 or later
1472                         return true
1473                 }
1474         }
1475
1476         // We have SWIG version 3.0.x.
1477         if len(matches[3]) > 0 {
1478                 patch, err := strconv.Atoi(string(matches[3][1:]))
1479                 if err != nil {
1480                         return true
1481                 }
1482                 if patch < 6 {
1483                         // Before 3.0.6.
1484                         return false
1485                 }
1486         }
1487
1488         return true
1489 }
1490
1491 // hasParallelism is a copy of the function
1492 // internal/testenv.HasParallelism, which can't be used here
1493 // because cmd/dist can not import internal packages during bootstrap.
1494 func (t *tester) hasParallelism() bool {
1495         switch goos {
1496         case "js", "wasip1":
1497                 return false
1498         }
1499         return true
1500 }
1501
1502 func (t *tester) raceDetectorSupported() bool {
1503         if gohostos != goos {
1504                 return false
1505         }
1506         if !t.cgoEnabled {
1507                 return false
1508         }
1509         if !raceDetectorSupported(goos, goarch) {
1510                 return false
1511         }
1512         // The race detector doesn't work on Alpine Linux:
1513         // golang.org/issue/14481
1514         if isAlpineLinux() {
1515                 return false
1516         }
1517         // NetBSD support is unfinished.
1518         // golang.org/issue/26403
1519         if goos == "netbsd" {
1520                 return false
1521         }
1522         return true
1523 }
1524
1525 func isAlpineLinux() bool {
1526         if runtime.GOOS != "linux" {
1527                 return false
1528         }
1529         fi, err := os.Lstat("/etc/alpine-release")
1530         return err == nil && fi.Mode().IsRegular()
1531 }
1532
1533 func (t *tester) registerRaceTests() {
1534         hdr := "Testing race detector"
1535         t.registerTest("race:runtime/race", hdr,
1536                 &goTest{
1537                         race:     true,
1538                         runTests: "Output",
1539                         pkg:      "runtime/race",
1540                 })
1541         t.registerTest("race", hdr,
1542                 &goTest{
1543                         race:     true,
1544                         runTests: "TestParse|TestEcho|TestStdinCloseRace|TestClosedPipeRace|TestTypeRace|TestFdRace|TestFdReadRace|TestFileCloseRace",
1545                         pkgs:     []string{"flag", "net", "os", "os/exec", "encoding/gob"},
1546                 })
1547         // We don't want the following line, because it
1548         // slows down all.bash (by 10 seconds on my laptop).
1549         // The race builder should catch any error here, but doesn't.
1550         // TODO(iant): Figure out how to catch this.
1551         // t.registerTest("race:cmd/go", hdr, &goTest{race: true, runTests: "TestParallelTest", pkg: "cmd/go"})
1552         if t.cgoEnabled {
1553                 // Building misc/cgo/test takes a long time.
1554                 // There are already cgo-enabled packages being tested with the race detector.
1555                 // We shouldn't need to redo all of misc/cgo/test too.
1556                 // The race buildler will take care of this.
1557                 // t.registerTest("race:misc/cgo/test", hdr, &goTest{dir: "../misc/cgo/test", race: true, env: []string{"GOTRACEBACK=2"}})
1558         }
1559         if t.extLink() {
1560                 // Test with external linking; see issue 9133.
1561                 t.registerTest("race:external", hdr,
1562                         &goTest{
1563                                 race:     true,
1564                                 ldflags:  "-linkmode=external",
1565                                 runTests: "TestParse|TestEcho|TestStdinCloseRace",
1566                                 pkgs:     []string{"flag", "os/exec"},
1567                         })
1568         }
1569 }
1570
1571 // cgoPackages is the standard packages that use cgo.
1572 var cgoPackages = []string{
1573         "net",
1574         "os/user",
1575 }
1576
1577 var funcBenchmark = []byte("\nfunc Benchmark")
1578
1579 // packageHasBenchmarks reports whether pkg has benchmarks.
1580 // On any error, it conservatively returns true.
1581 //
1582 // This exists just to eliminate work on the builders, since compiling
1583 // a test in race mode just to discover it has no benchmarks costs a
1584 // second or two per package, and this function returns false for
1585 // about 100 packages.
1586 func (t *tester) packageHasBenchmarks(pkg string) bool {
1587         pkgDir := filepath.Join(goroot, "src", pkg)
1588         d, err := os.Open(pkgDir)
1589         if err != nil {
1590                 return true // conservatively
1591         }
1592         defer d.Close()
1593         names, err := d.Readdirnames(-1)
1594         if err != nil {
1595                 return true // conservatively
1596         }
1597         for _, name := range names {
1598                 if !strings.HasSuffix(name, "_test.go") {
1599                         continue
1600                 }
1601                 slurp, err := os.ReadFile(filepath.Join(pkgDir, name))
1602                 if err != nil {
1603                         return true // conservatively
1604                 }
1605                 if bytes.Contains(slurp, funcBenchmark) {
1606                         return true
1607                 }
1608         }
1609         return false
1610 }
1611
1612 // makeGOROOTUnwritable makes all $GOROOT files & directories non-writable to
1613 // check that no tests accidentally write to $GOROOT.
1614 func (t *tester) makeGOROOTUnwritable() (undo func()) {
1615         dir := os.Getenv("GOROOT")
1616         if dir == "" {
1617                 panic("GOROOT not set")
1618         }
1619
1620         type pathMode struct {
1621                 path string
1622                 mode os.FileMode
1623         }
1624         var dirs []pathMode // in lexical order
1625
1626         undo = func() {
1627                 for i := range dirs {
1628                         os.Chmod(dirs[i].path, dirs[i].mode) // best effort
1629                 }
1630         }
1631
1632         filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
1633                 if suffix := strings.TrimPrefix(path, dir+string(filepath.Separator)); suffix != "" {
1634                         if suffix == ".git" {
1635                                 // Leave Git metadata in whatever state it was in. It may contain a lot
1636                                 // of files, and it is highly unlikely that a test will try to modify
1637                                 // anything within that directory.
1638                                 return filepath.SkipDir
1639                         }
1640                 }
1641                 if err != nil {
1642                         return nil
1643                 }
1644
1645                 info, err := d.Info()
1646                 if err != nil {
1647                         return nil
1648                 }
1649
1650                 mode := info.Mode()
1651                 if mode&0222 != 0 && (mode.IsDir() || mode.IsRegular()) {
1652                         dirs = append(dirs, pathMode{path, mode})
1653                 }
1654                 return nil
1655         })
1656
1657         // Run over list backward to chmod children before parents.
1658         for i := len(dirs) - 1; i >= 0; i-- {
1659                 err := os.Chmod(dirs[i].path, dirs[i].mode&^0222)
1660                 if err != nil {
1661                         dirs = dirs[i:] // Only undo what we did so far.
1662                         undo()
1663                         fatalf("failed to make GOROOT read-only: %v", err)
1664                 }
1665         }
1666
1667         return undo
1668 }
1669
1670 // raceDetectorSupported is a copy of the function
1671 // internal/platform.RaceDetectorSupported, which can't be used here
1672 // because cmd/dist can not import internal packages during bootstrap.
1673 // The race detector only supports 48-bit VMA on arm64. But we don't have
1674 // a good solution to check VMA size(See https://golang.org/issue/29948)
1675 // raceDetectorSupported will always return true for arm64. But race
1676 // detector tests may abort on non 48-bit VMA configuration, the tests
1677 // will be marked as "skipped" in this case.
1678 func raceDetectorSupported(goos, goarch string) bool {
1679         switch goos {
1680         case "linux":
1681                 return goarch == "amd64" || goarch == "ppc64le" || goarch == "arm64" || goarch == "s390x"
1682         case "darwin":
1683                 return goarch == "amd64" || goarch == "arm64"
1684         case "freebsd", "netbsd", "openbsd", "windows":
1685                 return goarch == "amd64"
1686         default:
1687                 return false
1688         }
1689 }
1690
1691 // buildModeSupports is a copy of the function
1692 // internal/platform.BuildModeSupported, which can't be used here
1693 // because cmd/dist can not import internal packages during bootstrap.
1694 func buildModeSupported(compiler, buildmode, goos, goarch string) bool {
1695         if compiler == "gccgo" {
1696                 return true
1697         }
1698
1699         platform := goos + "/" + goarch
1700
1701         switch buildmode {
1702         case "archive":
1703                 return true
1704
1705         case "c-archive":
1706                 switch goos {
1707                 case "aix", "darwin", "ios", "windows":
1708                         return true
1709                 case "linux":
1710                         switch goarch {
1711                         case "386", "amd64", "arm", "armbe", "arm64", "arm64be", "loong64", "ppc64le", "riscv64", "s390x":
1712                                 // linux/ppc64 not supported because it does
1713                                 // not support external linking mode yet.
1714                                 return true
1715                         default:
1716                                 // Other targets do not support -shared,
1717                                 // per ParseFlags in
1718                                 // cmd/compile/internal/base/flag.go.
1719                                 // For c-archive the Go tool passes -shared,
1720                                 // so that the result is suitable for inclusion
1721                                 // in a PIE or shared library.
1722                                 return false
1723                         }
1724                 case "freebsd":
1725                         return goarch == "amd64"
1726                 }
1727                 return false
1728
1729         case "c-shared":
1730                 switch platform {
1731                 case "linux/amd64", "linux/arm", "linux/arm64", "linux/loong64", "linux/386", "linux/ppc64le", "linux/riscv64", "linux/s390x",
1732                         "android/amd64", "android/arm", "android/arm64", "android/386",
1733                         "freebsd/amd64",
1734                         "darwin/amd64", "darwin/arm64",
1735                         "windows/amd64", "windows/386", "windows/arm64":
1736                         return true
1737                 }
1738                 return false
1739
1740         case "default":
1741                 return true
1742
1743         case "exe":
1744                 return true
1745
1746         case "pie":
1747                 switch platform {
1748                 case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/loong64", "linux/ppc64le", "linux/riscv64", "linux/s390x",
1749                         "android/amd64", "android/arm", "android/arm64", "android/386",
1750                         "freebsd/amd64",
1751                         "darwin/amd64", "darwin/arm64",
1752                         "ios/amd64", "ios/arm64",
1753                         "aix/ppc64",
1754                         "windows/386", "windows/amd64", "windows/arm", "windows/arm64":
1755                         return true
1756                 }
1757                 return false
1758
1759         case "shared":
1760                 switch platform {
1761                 case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64le", "linux/s390x":
1762                         return true
1763                 }
1764                 return false
1765
1766         case "plugin":
1767                 switch platform {
1768                 case "linux/amd64", "linux/arm", "linux/arm64", "linux/386", "linux/s390x", "linux/ppc64le",
1769                         "android/amd64", "android/386",
1770                         "darwin/amd64", "darwin/arm64",
1771                         "freebsd/amd64":
1772                         return true
1773                 }
1774                 return false
1775
1776         default:
1777                 return false
1778         }
1779 }
1780
1781 // isUnsupportedVMASize reports whether the failure is caused by an unsupported
1782 // VMA for the race detector (for example, running the race detector on an
1783 // arm64 machine configured with 39-bit VMA)
1784 func isUnsupportedVMASize(w *work) bool {
1785         unsupportedVMA := []byte("unsupported VMA range")
1786         return w.dt.name == "race" && bytes.Contains(w.out, unsupportedVMA)
1787 }
1788
1789 // isEnvSet reports whether the environment variable evar is
1790 // set in the environment.
1791 func isEnvSet(evar string) bool {
1792         evarEq := evar + "="
1793         for _, e := range os.Environ() {
1794                 if strings.HasPrefix(e, evarEq) {
1795                         return true
1796                 }
1797         }
1798         return false
1799 }