Source file 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  	"encoding/json"
    10  	"flag"
    11  	"fmt"
    12  	"io"
    13  	"io/fs"
    14  	"log"
    15  	"os"
    16  	"os/exec"
    17  	"path/filepath"
    18  	"reflect"
    19  	"regexp"
    20  	"runtime"
    21  	"slices"
    22  	"strconv"
    23  	"strings"
    24  	"time"
    25  )
    26  
    27  func cmdtest() {
    28  	gogcflags = os.Getenv("GO_GCFLAGS")
    29  	setNoOpt()
    30  
    31  	var t tester
    32  
    33  	t.asmflags = os.Getenv("GO_TEST_ASMFLAGS")
    34  
    35  	var noRebuild bool
    36  	flag.BoolVar(&t.listMode, "list", false, "list available tests")
    37  	flag.BoolVar(&t.rebuild, "rebuild", false, "rebuild everything first")
    38  	flag.BoolVar(&noRebuild, "no-rebuild", false, "overrides -rebuild (historical dreg)")
    39  	flag.BoolVar(&t.keepGoing, "k", false, "keep going even when error occurred")
    40  	flag.BoolVar(&t.race, "race", false, "run in race builder mode (different set of tests)")
    41  	flag.BoolVar(&t.compileOnly, "compile-only", false, "compile tests, but don't run them")
    42  	flag.StringVar(&t.banner, "banner", "##### ", "banner prefix; blank means no section banners")
    43  	flag.StringVar(&t.runRxStr, "run", "",
    44  		"run only those tests matching the regular expression; empty means to run all. "+
    45  			"Special exception: if the string begins with '!', the match is inverted.")
    46  	flag.BoolVar(&t.msan, "msan", false, "run in memory sanitizer builder mode")
    47  	flag.BoolVar(&t.asan, "asan", false, "run in address sanitizer builder mode")
    48  	flag.BoolVar(&t.json, "json", false, "report test results in JSON")
    49  	flag.StringVar(&t.artifactsDir, "artifacts-dir", "", "save test artifacts in the specified directory")
    50  	flag.StringVar(&debugTrace, "debug-trace", debugTrace, "write a merged trace of the test run to `file`")
    51  
    52  	xflagparse(-1) // any number of args
    53  	if noRebuild {
    54  		debugTraceAppend = true
    55  		t.rebuild = false
    56  	}
    57  
    58  	t.run()
    59  }
    60  
    61  // tester executes cmdtest.
    62  type tester struct {
    63  	race         bool
    64  	msan         bool
    65  	asan         bool
    66  	listMode     bool
    67  	rebuild      bool
    68  	failed       bool
    69  	keepGoing    bool
    70  	compileOnly  bool // just try to compile all tests, but no need to run
    71  	short        bool
    72  	cgoEnabled   bool
    73  	asmflags     string
    74  	json         bool
    75  	artifactsDir string
    76  	runRxStr     string
    77  	runRx        *regexp.Regexp
    78  	runRxWant    bool     // want runRx to match (true) or not match (false)
    79  	runNames     []string // tests to run, exclusive with runRx; empty means all
    80  	banner       string   // prefix, or "" for none
    81  	lastHeading  string   // last dir heading printed
    82  
    83  	tests               []distTest // use addTest to extend
    84  	testNames           map[string]bool
    85  	timeoutScale        int // a non-negative integer factor to scale test timeout by; defaults to 1
    86  	deferSimdGODEBUGs   bool
    87  	simdGODEBUGInsertAt int
    88  
    89  	worklist []*work
    90  }
    91  
    92  // work tracks command execution for a test.
    93  type work struct {
    94  	dt    *distTest     // unique test name, etc.
    95  	cmd   *exec.Cmd     // must write stdout/stderr to out
    96  	flush func()        // if non-nil, called after cmd.Run
    97  	start chan bool     // a true means to start, a false means to skip
    98  	out   bytes.Buffer  // combined stdout/stderr from cmd
    99  	err   error         // work result
   100  	end   chan struct{} // a value means cmd ended (or was skipped)
   101  }
   102  
   103  // printSkip prints a skip message for all of work.
   104  func (w *work) printSkip(t *tester, msg string) {
   105  	if t.json {
   106  		synthesizeSkipEvent(json.NewEncoder(&w.out), w.dt.name, msg)
   107  		return
   108  	}
   109  	fmt.Fprintln(&w.out, msg)
   110  }
   111  
   112  // A distTest is a test run by dist test.
   113  // Each test has a unique name and belongs to a group (heading)
   114  type distTest struct {
   115  	name    string // unique test name; may be filtered with -run flag
   116  	heading string // group section; this header is printed before the test is run.
   117  	fn      func(*distTest) error
   118  }
   119  
   120  func (t *tester) run() {
   121  	timelog("start", "dist test")
   122  	distSpan := startSpan("dist test")
   123  
   124  	os.Setenv("PATH", fmt.Sprintf("%s%c%s", gorootBin, os.PathListSeparator, os.Getenv("PATH")))
   125  
   126  	t.short = true
   127  	if v := os.Getenv("GO_TEST_SHORT"); v != "" {
   128  		short, err := strconv.ParseBool(v)
   129  		if err != nil {
   130  			fatalf("invalid GO_TEST_SHORT %q: %v", v, err)
   131  		}
   132  		t.short = short
   133  	}
   134  
   135  	cmd := exec.Command(gorootBinGo, "env", "CGO_ENABLED")
   136  	cmd.Stderr = new(bytes.Buffer)
   137  	slurp, err := cmd.Output()
   138  	if err != nil {
   139  		fatalf("Error running %s: %v\n%s", cmd, err, cmd.Stderr)
   140  	}
   141  	parts := strings.Split(string(slurp), "\n")
   142  	if nlines := len(parts) - 1; nlines < 1 {
   143  		fatalf("Error running %s: output contains <1 lines\n%s", cmd, cmd.Stderr)
   144  	}
   145  	t.cgoEnabled, _ = strconv.ParseBool(parts[0])
   146  
   147  	if flag.NArg() > 0 && t.runRxStr != "" {
   148  		fatalf("the -run regular expression flag is mutually exclusive with test name arguments")
   149  	}
   150  
   151  	t.runNames = flag.Args()
   152  
   153  	// Set GOTRACEBACK to system if the user didn't set a level explicitly.
   154  	// Since we're running tests for Go, we want as much detail as possible
   155  	// if something goes wrong.
   156  	//
   157  	// Set it before running any commands just in case something goes wrong.
   158  	if ok := isEnvSet("GOTRACEBACK"); !ok {
   159  		if err := os.Setenv("GOTRACEBACK", "system"); err != nil {
   160  			if t.keepGoing {
   161  				log.Printf("Failed to set GOTRACEBACK: %v", err)
   162  			} else {
   163  				fatalf("Failed to set GOTRACEBACK: %v", err)
   164  			}
   165  		}
   166  	}
   167  
   168  	if t.rebuild {
   169  		t.out("Building packages and commands.")
   170  		// Force rebuild the whole toolchain.
   171  		rebuildSpan := startSpan("rebuild toolchain")
   172  		goInstall(toolenv(), gorootBinGo, append(append(maybeTraceFlag("rebuildToolchain"), "-a"), toolchain...)...)
   173  		rebuildSpan.done()
   174  	}
   175  
   176  	if !t.listMode {
   177  		if builder := os.Getenv("GO_BUILDER_NAME"); builder == "" {
   178  			// Ensure that installed commands are up to date, even with -no-rebuild,
   179  			// so that tests that run commands end up testing what's actually on disk.
   180  			// If everything is up-to-date, this is a no-op.
   181  			// We first build the toolchain twice to allow it to converge,
   182  			// as when we first bootstrap.
   183  			// See cmdbootstrap for a description of the overall process.
   184  			//
   185  			// On the builders, we skip this step: we assume that 'dist test' is
   186  			// already using the result of a clean build, and because of test sharding
   187  			// and virtualization we usually start with a clean GOCACHE, so we would
   188  			// end up rebuilding large parts of the standard library that aren't
   189  			// otherwise relevant to the actual set of packages under test.
   190  			toolchain1Span := startSpan("toolchain1")
   191  			goInstall(toolenv(), gorootBinGo, append(maybeTraceFlag("toolchain1"), toolchain...)...)
   192  			toolchain1Span.done()
   193  			toolchain2Span := startSpan("toolchain2")
   194  			goInstall(toolenv(), gorootBinGo, append(maybeTraceFlag("toolchain2"), toolchain...)...)
   195  			toolchain2Span.done()
   196  			toolsSpan := startSpan("tools")
   197  			goInstall(toolenv(), gorootBinGo, append(maybeTraceFlag("tools"), toolsToInstall...)...)
   198  			toolsSpan.done()
   199  		}
   200  	}
   201  
   202  	t.timeoutScale = 1
   203  	if s := os.Getenv("GO_TEST_TIMEOUT_SCALE"); s != "" {
   204  		t.timeoutScale, err = strconv.Atoi(s)
   205  		if err != nil {
   206  			fatalf("failed to parse $GO_TEST_TIMEOUT_SCALE = %q as integer: %v", s, err)
   207  		}
   208  	}
   209  
   210  	if t.runRxStr != "" {
   211  		if t.runRxStr[0] == '!' {
   212  			t.runRxWant = false
   213  			t.runRxStr = t.runRxStr[1:]
   214  		} else {
   215  			t.runRxWant = true
   216  		}
   217  		t.runRx = regexp.MustCompile(t.runRxStr)
   218  	}
   219  
   220  	t.registerTests()
   221  	if t.listMode {
   222  		for _, tt := range t.tests {
   223  			fmt.Println(tt.name)
   224  		}
   225  		return
   226  	}
   227  
   228  	for _, name := range t.runNames {
   229  		if !t.testNames[name] {
   230  			fatalf("unknown test %q", name)
   231  		}
   232  	}
   233  
   234  	// On a few builders, make GOROOT unwritable to catch tests writing to it.
   235  	if strings.Contains(os.Getenv("GO_BUILDER_NAME"), "-linux-") {
   236  		if os.Getuid() == 0 {
   237  			// Don't bother making GOROOT unwritable:
   238  			// we're running as root, so permissions would have no effect.
   239  		} else {
   240  			xatexit(t.makeGOROOTUnwritable())
   241  		}
   242  	}
   243  
   244  	if !t.json {
   245  		if err := t.maybeLogMetadata(); err != nil {
   246  			t.failed = true
   247  			if t.keepGoing {
   248  				log.Printf("Failed logging metadata: %v", err)
   249  			} else {
   250  				fatalf("Failed logging metadata: %v", err)
   251  			}
   252  		}
   253  	}
   254  
   255  	var simdGODEBUGCh chan simdGODEBUGList
   256  	if t.deferSimdGODEBUGs {
   257  		simdGODEBUGCh = make(chan simdGODEBUGList, 1)
   258  		go func() {
   259  			simdGODEBUGCh <- t.listSimdGODEBUGs(true)
   260  		}()
   261  	}
   262  
   263  	var anyIncluded, someExcluded bool
   264  	runDistTest := func(dt distTest) {
   265  		if !t.shouldRunTest(dt.name) {
   266  			someExcluded = true
   267  			return
   268  		}
   269  		anyIncluded = true
   270  		if err := dt.fn(&dt); err != nil {
   271  			t.runPending(&dt) // in case that hasn't been done yet
   272  			t.failed = true
   273  			if t.keepGoing {
   274  				log.Printf("Failed: %v", err)
   275  			} else {
   276  				fatalf("Failed: %v", err)
   277  			}
   278  		}
   279  	}
   280  	tests := t.tests
   281  	for i, dt := range tests {
   282  		if simdGODEBUGCh != nil && i == t.simdGODEBUGInsertAt {
   283  			start := len(t.tests)
   284  			t.addSimdGODEBUGTests(<-simdGODEBUGCh)
   285  			simdGODEBUGCh = nil
   286  			for _, sdt := range t.tests[start:] {
   287  				runDistTest(sdt)
   288  			}
   289  		}
   290  		runDistTest(dt)
   291  	}
   292  	if simdGODEBUGCh != nil {
   293  		start := len(t.tests)
   294  		t.addSimdGODEBUGTests(<-simdGODEBUGCh)
   295  		for _, sdt := range t.tests[start:] {
   296  			runDistTest(sdt)
   297  		}
   298  	}
   299  	t.runPending(nil)
   300  	timelog("end", "dist test")
   301  	distSpan.done()
   302  	if debugTrace != "" {
   303  		writeTrace()
   304  	}
   305  
   306  	if !t.json {
   307  		if t.failed {
   308  			fmt.Println("\nFAILED")
   309  		} else if !anyIncluded {
   310  			fmt.Println()
   311  			errprintf("go tool dist: warning: %q matched no tests; use the -list flag to list available tests\n", t.runRxStr)
   312  			fmt.Println("NO TESTS TO RUN")
   313  		} else if someExcluded {
   314  			fmt.Println("\nALL TESTS PASSED (some were excluded)")
   315  		} else {
   316  			fmt.Println("\nALL TESTS PASSED")
   317  		}
   318  	}
   319  	if t.failed {
   320  		xexit(1)
   321  	}
   322  }
   323  
   324  func (t *tester) shouldRunTest(name string) bool {
   325  	if t.runRx != nil {
   326  		return t.runRx.MatchString(name) == t.runRxWant
   327  	}
   328  	if len(t.runNames) == 0 {
   329  		return true
   330  	}
   331  	return slices.Contains(t.runNames, name)
   332  }
   333  
   334  func (t *tester) maybeLogMetadata() error {
   335  	if t.compileOnly {
   336  		// We need to run a subprocess to log metadata. Don't do that
   337  		// on compile-only runs.
   338  		return nil
   339  	}
   340  	t.out("Test execution environment.")
   341  	// Helper binary to print system metadata (CPU model, etc). This is a
   342  	// separate binary from dist so it need not build with the bootstrap
   343  	// toolchain.
   344  	//
   345  	// TODO(prattmic): If we split dist bootstrap and dist test then this
   346  	// could be simplified to directly use internal/sysinfo here.
   347  	return t.dirCmd(filepath.Join(goroot, "src/cmd/internal/metadata"), gorootBinGo, []string{"run", "main.go"}).Run()
   348  }
   349  
   350  // testName returns the dist test name for a given package and variant.
   351  func testName(pkg, variant string) string {
   352  	name := pkg
   353  	if variant != "" {
   354  		name += ":" + variant
   355  	}
   356  	return name
   357  }
   358  
   359  // goTest represents all options to a "go test" command. The final command will
   360  // combine configuration from goTest and tester flags.
   361  type goTest struct {
   362  	short    bool     // If true, force -short
   363  	tags     []string // Build tags
   364  	race     bool     // Force -race
   365  	bench    bool     // Run benchmarks (briefly), not tests.
   366  	runTests string   // Regexp of tests to run
   367  	cpu      string   // If non-empty, -cpu flag
   368  	parallel int      // If > 0, -p flag
   369  	skip     string   // If non-empty, -skip flag
   370  
   371  	gcflags   string // If non-empty, build with -gcflags=all=X
   372  	ldflags   string // If non-empty, build with -ldflags=X
   373  	buildmode string // If non-empty, -buildmode flag
   374  
   375  	env []string // Environment variables to add, as KEY=VAL. KEY= unsets a variable
   376  
   377  	// timeout optionally raises the per-package test timeout to be at least this long.
   378  	// The zero value means to stay with the default test timeout.
   379  	// When adding new tests, this field generally doesn't need to be set, not unless
   380  	// the go commmand's default test timeout proves to be insufficient.
   381  	//
   382  	// In either case, the per-package test timeout get scaled by a multiplier,
   383  	// and applied only if the end result is longer than the go command's default
   384  	// test timeout.
   385  	timeout time.Duration
   386  
   387  	runOnHost bool // When cross-compiling, run this test on the host instead of guest
   388  
   389  	// variant, if non-empty, is a name used to distinguish different
   390  	// configurations of the same test package(s). If set, the Package field
   391  	// in test2json output is rewritten to pkg:variant.
   392  	variant string
   393  
   394  	// We have both pkg and pkgs as a convenience. Both may be set, in which
   395  	// case they will be combined. At least one must be set.
   396  	pkgs []string // Multiple packages to test
   397  	pkg  string   // A single package to test
   398  
   399  	testFlags []string // Additional flags accepted by this test
   400  	trace     string   // If non-empty, write go test -debug-trace output to <workdir>/<trace>.trace
   401  }
   402  
   403  // compileOnly reports whether this test is only for compiling,
   404  // indicated by runTests being set to '^$' and bench being false.
   405  func (opts *goTest) compileOnly() bool {
   406  	return opts.runTests == "^$" && !opts.bench
   407  }
   408  
   409  // scaledTimeout reports the per-package test timeout scaled by t.timeoutScale.
   410  func (opts *goTest) scaledTimeout(t *tester) time.Duration {
   411  	d := goTestDefaultTimeout
   412  	if opts.timeout != 0 {
   413  		d = opts.timeout
   414  	}
   415  	d *= time.Duration(t.timeoutScale)
   416  	return d
   417  }
   418  
   419  const goTestDefaultTimeout = 10 * time.Minute // Default value of go test -timeout flag.
   420  
   421  // bgCommand returns a go test Cmd and a post-Run flush function. The result
   422  // will write its output to stdout and stderr. If stdout==stderr, bgCommand
   423  // ensures Writes are serialized. The caller should call flush() after Cmd exits.
   424  func (opts *goTest) bgCommand(t *tester, stdout, stderr io.Writer) (cmd *exec.Cmd, flush func()) {
   425  	build, run, pkgs, testFlags, setupCmd := opts.buildArgs(t)
   426  
   427  	// Combine the flags.
   428  	args := append([]string{"test"}, build...)
   429  	if t.compileOnly || opts.compileOnly() {
   430  		args = append(args, "-c", "-o", os.DevNull)
   431  	} else {
   432  		args = append(args, run...)
   433  	}
   434  	args = append(args, pkgs...)
   435  	if !t.compileOnly && !opts.compileOnly() {
   436  		args = append(args, testFlags...)
   437  	}
   438  
   439  	cmd = exec.Command(gorootBinGo, args...)
   440  	setupCmd(cmd)
   441  	if t.json && opts.variant != "" {
   442  		// Rewrite Package in the JSON output to be pkg:variant.
   443  		//
   444  		// We only want to process JSON on the child's stdout. Ideally if
   445  		// stdout==stderr, we would also use the same testJSONFilter for
   446  		// cmd.Stdout and cmd.Stderr in order to keep the underlying
   447  		// interleaving of writes, but then it would see even partial writes
   448  		// interleaved, which would corrupt the JSON. So, we only process
   449  		// cmd.Stdout. This has another consequence though: if stdout==stderr,
   450  		// we have to serialize Writes in case the Writer is not concurrent
   451  		// safe. If we were just passing stdout/stderr through to exec, it would
   452  		// do this for us, but since we're wrapping stdout, we have to do it
   453  		// ourselves.
   454  		if stdout == stderr {
   455  			stdout = &lockedWriter{w: stdout}
   456  			stderr = stdout
   457  		}
   458  		f := &testJSONFilter{w: stdout, variant: opts.variant}
   459  		cmd.Stdout = f
   460  		flush = f.Flush
   461  	} else {
   462  		cmd.Stdout = stdout
   463  		flush = func() {}
   464  	}
   465  	cmd.Stderr = stderr
   466  
   467  	return cmd, flush
   468  }
   469  
   470  // run runs a go test and returns an error if it does not succeed.
   471  func (opts *goTest) run(t *tester) error {
   472  	cmd, flush := opts.bgCommand(t, os.Stdout, os.Stderr)
   473  	err := cmd.Run()
   474  	flush()
   475  	return err
   476  }
   477  
   478  // buildArgs is in internal helper for goTest that constructs the elements of
   479  // the "go test" command line. build is the flags for building the test. run is
   480  // the flags for running the test. pkgs is the list of packages to build and
   481  // run. testFlags is the list of flags to pass to the test package.
   482  //
   483  // The caller must call setupCmd on the resulting exec.Cmd to set its directory
   484  // and environment.
   485  func (opts *goTest) buildArgs(t *tester) (build, run, pkgs, testFlags []string, setupCmd func(*exec.Cmd)) {
   486  	run = append(run, "-count=1") // Disallow caching.
   487  	if d := opts.scaledTimeout(t); d > goTestDefaultTimeout {
   488  		run = append(run, "-timeout="+d.String())
   489  	}
   490  	if opts.short || t.short {
   491  		run = append(run, "-short")
   492  	}
   493  	var tags []string
   494  	if noOpt {
   495  		tags = append(tags, "noopt")
   496  	}
   497  	tags = append(tags, opts.tags...)
   498  	if len(tags) > 0 {
   499  		build = append(build, "-tags="+strings.Join(tags, ","))
   500  	}
   501  	if t.race || opts.race {
   502  		build = append(build, "-race")
   503  	}
   504  	if t.msan {
   505  		build = append(build, "-msan")
   506  	}
   507  	if t.asan {
   508  		build = append(build, "-asan")
   509  	}
   510  	if opts.bench {
   511  		// Run no tests.
   512  		run = append(run, "-run=^$")
   513  		// Run benchmarks briefly as a smoke test.
   514  		run = append(run, "-bench=.*", "-benchtime=.1s")
   515  	} else if opts.runTests != "" {
   516  		run = append(run, "-run="+opts.runTests)
   517  	}
   518  	if opts.cpu != "" {
   519  		run = append(run, "-cpu="+opts.cpu)
   520  	}
   521  	if opts.parallel > 0 {
   522  		build = append(build, "-p="+strconv.Itoa(opts.parallel))
   523  	}
   524  	if opts.skip != "" {
   525  		run = append(run, "-skip="+opts.skip)
   526  	}
   527  	if t.json {
   528  		build = append(build, "-json")
   529  	}
   530  	if t.artifactsDir != "" {
   531  		run = append(run, "-artifacts", "-outputdir="+t.artifactsDir)
   532  	}
   533  
   534  	if opts.gcflags != "" {
   535  		build = append(build, "-gcflags=all="+opts.gcflags)
   536  	}
   537  	if opts.ldflags != "" {
   538  		build = append(build, "-ldflags="+opts.ldflags)
   539  	}
   540  	if t.asmflags != "" {
   541  		build = append(build, "-asmflags="+t.asmflags)
   542  	}
   543  	if opts.buildmode != "" {
   544  		build = append(build, "-buildmode="+opts.buildmode)
   545  	}
   546  	if opts.trace != "" {
   547  		build = append(build, maybeTraceFlag(opts.trace)...)
   548  	}
   549  
   550  	pkgs = opts.packages()
   551  
   552  	runOnHost := opts.runOnHost && (goarch != gohostarch || goos != gohostos)
   553  	needTestFlags := len(opts.testFlags) > 0 || runOnHost
   554  	if needTestFlags {
   555  		testFlags = append([]string{"-args"}, opts.testFlags...)
   556  	}
   557  	if runOnHost {
   558  		// -target is a special flag understood by tests that can run on the host
   559  		testFlags = append(testFlags, "-target="+goos+"/"+goarch)
   560  	}
   561  
   562  	setupCmd = func(cmd *exec.Cmd) {
   563  		setDir(cmd, filepath.Join(goroot, "src"))
   564  		if len(opts.env) != 0 {
   565  			for _, kv := range opts.env {
   566  				if i := strings.Index(kv, "="); i < 0 {
   567  					unsetEnv(cmd, kv[:len(kv)-1])
   568  				} else {
   569  					setEnv(cmd, kv[:i], kv[i+1:])
   570  				}
   571  			}
   572  		}
   573  		if runOnHost {
   574  			setEnv(cmd, "GOARCH", gohostarch)
   575  			setEnv(cmd, "GOOS", gohostos)
   576  		}
   577  	}
   578  
   579  	return
   580  }
   581  
   582  // packages returns the full list of packages to be run by this goTest. This
   583  // will always include at least one package.
   584  func (opts *goTest) packages() []string {
   585  	pkgs := opts.pkgs
   586  	if opts.pkg != "" {
   587  		pkgs = append(pkgs[:len(pkgs):len(pkgs)], opts.pkg)
   588  	}
   589  	if len(pkgs) == 0 {
   590  		panic("no packages")
   591  	}
   592  	return pkgs
   593  }
   594  
   595  // printSkip prints a skip message for all of goTest.
   596  func (opts *goTest) printSkip(t *tester, msg string) {
   597  	if t.json {
   598  		enc := json.NewEncoder(os.Stdout)
   599  		for _, pkg := range opts.packages() {
   600  			synthesizeSkipEvent(enc, pkg, msg)
   601  		}
   602  		return
   603  	}
   604  	fmt.Println(msg)
   605  }
   606  
   607  // ranGoTest and stdMatches are state closed over by the stdlib
   608  // testing func in registerStdTest below. The tests are run
   609  // sequentially, so there's no need for locks.
   610  //
   611  // ranGoBench and benchMatches are the same, but are only used
   612  // in -race mode.
   613  var (
   614  	ranGoTest  bool
   615  	stdMatches []string
   616  
   617  	ranGoBench   bool
   618  	benchMatches []string
   619  )
   620  
   621  // maxTestGOMAXPROCS caps per-process GOMAXPROCS when running many test
   622  // packages concurrently on high-core-count machines, avoiding severe
   623  // N*N thread oversubscription while keeping full build parallelism via -p.
   624  const maxTestGOMAXPROCS = 32
   625  
   626  func (t *tester) registerStdTest(pkg string) {
   627  	const stdTestHeading = "Testing packages." // known to addTest for a safety check
   628  	gcflags := gogcflags
   629  	name := testName(pkg, "")
   630  	if t.runRx == nil || t.runRx.MatchString(name) == t.runRxWant {
   631  		stdMatches = append(stdMatches, pkg)
   632  	}
   633  	t.addTest(name, stdTestHeading, func(dt *distTest) error {
   634  		if ranGoTest {
   635  			return nil
   636  		}
   637  		t.runPending(dt)
   638  		timelog("start", dt.name)
   639  		defer timelog("end", dt.name)
   640  		ranGoTest = true
   641  
   642  		stdSpan := startSpan("go test std cmd")
   643  		defer stdSpan.done()
   644  
   645  		gt := &goTest{
   646  			gcflags: gcflags,
   647  			pkgs:    stdMatches,
   648  			trace:   "std",
   649  		}
   650  		if len(stdMatches) > 1 && t.hasParallelism() && !isEnvSet("GOMAXPROCS") {
   651  			if n := runtime.GOMAXPROCS(0); n > maxTestGOMAXPROCS {
   652  				gt.parallel = n
   653  				gt.env = []string{"GOMAXPROCS=" + strconv.Itoa(maxTestGOMAXPROCS)}
   654  			}
   655  		}
   656  		return gt.run(t)
   657  	})
   658  }
   659  
   660  func (t *tester) registerRaceBenchTest(pkg string) {
   661  	const raceBenchHeading = "Running benchmarks briefly." // known to addTest for a safety check
   662  	name := testName(pkg, "racebench")
   663  	if t.runRx == nil || t.runRx.MatchString(name) == t.runRxWant {
   664  		benchMatches = append(benchMatches, pkg)
   665  	}
   666  	t.addTest(name, raceBenchHeading, func(dt *distTest) error {
   667  		if ranGoBench {
   668  			return nil
   669  		}
   670  		t.runPending(dt)
   671  		timelog("start", dt.name)
   672  		defer timelog("end", dt.name)
   673  		ranGoBench = true
   674  		return (&goTest{
   675  			// Include the variant even though there's no overlap in test names.
   676  			// This makes the test targets distinct, allowing our build system to record
   677  			// elapsed time for each one, which is useful for load-balancing test shards.
   678  			variant: "racebench",
   679  			timeout: 20 * time.Minute, // longer timeout for race with benchmarks
   680  			race:    true,
   681  			bench:   true,
   682  			cpu:     "4",
   683  			pkgs:    benchMatches,
   684  		}).run(t)
   685  	})
   686  }
   687  
   688  func (t *tester) registerTests() {
   689  	// Fast path to avoid the ~1 second of `go list std cmd` when
   690  	// the caller lists specific tests to run. (as the continuous
   691  	// build coordinator does).
   692  	if len(t.runNames) > 0 {
   693  		for _, name := range t.runNames {
   694  			if !strings.Contains(name, ":") {
   695  				t.registerStdTest(name)
   696  			} else if strings.HasSuffix(name, ":racebench") {
   697  				t.registerRaceBenchTest(strings.TrimSuffix(name, ":racebench"))
   698  			}
   699  		}
   700  	} else {
   701  		// Use 'go list std cmd' to get a list of all Go packages
   702  		// that running 'go test std cmd' could find problems in.
   703  		// (In race test mode, also set -tags=race.)
   704  		// This includes vendored packages and other
   705  		// packages without tests so that 'dist test' finds if any of
   706  		// them don't build, have a problem reported by high-confidence
   707  		// vet checks that come with 'go test', and anything else it
   708  		// may check in the future. See go.dev/issue/60463.
   709  		// Most packages have tests, so there is not much saved
   710  		// by skipping non-test packages.
   711  		// For the packages without any test files,
   712  		// 'go test' knows not to actually build a test binary,
   713  		// so the only cost is the vet, and we still want to run vet.
   714  		cmd := exec.Command(gorootBinGo, "list")
   715  		if t.race {
   716  			cmd.Args = append(cmd.Args, "-tags=race")
   717  		}
   718  		cmd.Args = append(cmd.Args, "std", "cmd")
   719  		cmd.Stderr = new(bytes.Buffer)
   720  		all, err := cmd.Output()
   721  		if err != nil {
   722  			fatalf("Error running go list std cmd: %v:\n%s", err, cmd.Stderr)
   723  		}
   724  		pkgs := strings.Fields(string(all))
   725  		for _, pkg := range pkgs {
   726  			if t.short && (strings.HasPrefix(pkg, "vendor/") || strings.HasPrefix(pkg, "cmd/vendor/")) {
   727  				// Vendored code has no tests, and we don't care too much about vet errors
   728  				// since we can't modify the code, so skip the tests in short mode.
   729  				// We still let the longtest builders vet them.
   730  				continue
   731  			}
   732  			t.registerStdTest(pkg)
   733  		}
   734  		if t.race && !t.short {
   735  			for _, pkg := range pkgs {
   736  				if t.packageHasBenchmarks(pkg) {
   737  					t.registerRaceBenchTest(pkg)
   738  				}
   739  			}
   740  		}
   741  	}
   742  
   743  	if t.race {
   744  		return
   745  	}
   746  
   747  	// Test the os/user package in the pure-Go mode too.
   748  	if !t.compileOnly {
   749  		t.registerTest("os/user with tag osusergo",
   750  			&goTest{
   751  				variant: "osusergo",
   752  				tags:    []string{"osusergo"},
   753  				pkg:     "os/user",
   754  			})
   755  	}
   756  
   757  	// Tests that the nethttpomithttp2* build tags don't rot too much,
   758  	// even if there's not a regular builder on them.
   759  	for _, tag := range []string{"nethttpomithttp2", "nethttpomithttp2server", "nethttpomithttp2client"} {
   760  		t.registerTest("net/http with tag "+tag, &goTest{
   761  			variant: tag,
   762  			tags:    []string{tag},
   763  			pkg:     "net/http",
   764  		})
   765  	}
   766  
   767  	// Check that all crypto packages compile with the purego build tag.
   768  	t.registerTest("crypto with tag purego (build and vet only)", &goTest{
   769  		variant:  "purego",
   770  		tags:     []string{"purego"},
   771  		pkg:      "crypto/...",
   772  		runTests: "^$", // only ensure they compile
   773  	})
   774  
   775  	// Check that all crypto packages compile (and test correctly, in longmode) with fips.
   776  	if t.fips140Supported() {
   777  		// Test standard crypto packages with fips140=on.
   778  		t.registerTest("GOFIPS140=latest go test crypto/...", &goTest{
   779  			variant: "gofips140",
   780  			env:     []string{"GOFIPS140=latest"},
   781  			pkg:     "crypto/...",
   782  		})
   783  
   784  		// Test that earlier FIPS snapshots build.
   785  		// In long mode, test that they work too.
   786  		for _, version := range fips140Versions() {
   787  			suffix := " # (build and vet only)"
   788  			run := "^$" // only ensure they compile
   789  			if !t.short {
   790  				suffix = ""
   791  				run = ""
   792  			}
   793  			t.registerTest("GOFIPS140="+version+" go test crypto/..."+suffix, &goTest{
   794  				variant:  "gofips140-" + version,
   795  				pkg:      "crypto/...",
   796  				runTests: run,
   797  				env:      []string{"GOFIPS140=" + version, "GOMODCACHE=" + filepath.Join(workdir, "fips-"+version)},
   798  			})
   799  		}
   800  	}
   801  
   802  	// Test GOEXPERIMENT=nojsonv2.
   803  	if !strings.Contains(goexperiment, "nojsonv2") {
   804  		t.registerTest("GOEXPERIMENT=nojsonv2 go test encoding/json/...", &goTest{
   805  			variant: "nojsonv2",
   806  			env:     []string{"GOEXPERIMENT=" + goexperiments("nojsonv2")},
   807  			pkg:     "encoding/json/...",
   808  		})
   809  	}
   810  
   811  	// Test GOEXPERIMENT=runtimesecret.
   812  	if !strings.Contains(goexperiment, "runtimesecret") {
   813  		t.registerTest("GOEXPERIMENT=runtimesecret go test runtime/secret/...", &goTest{
   814  			variant: "runtimesecret",
   815  			env:     []string{"GOEXPERIMENT=" + goexperiments("runtimesecret")},
   816  			pkg:     "runtime/secret/...",
   817  		})
   818  	}
   819  
   820  	// Test GOEXPERIMENT=simd.
   821  	if !slices.Contains(strings.Split(goexperiment, ","), "simd") {
   822  		// simd package is portable.
   823  		t.registerTest("GOEXPERIMENT=simd go test simd", &goTest{
   824  			variant: "simd",
   825  			env:     []string{"GOEXPERIMENT=" + goexperiments("simd")},
   826  			pkg:     "simd",
   827  		})
   828  		// simd/archsimd supports amd64, arm64, and wasm.
   829  		archsimdSupported := goarch == "amd64" || goarch == "arm64" || goarch == "wasm"
   830  		if archsimdSupported {
   831  			t.registerTest("GOEXPERIMENT=simd go test simd/archsimd/...", &goTest{
   832  				variant: "simd",
   833  				env:     []string{"GOEXPERIMENT=" + goexperiments("simd")},
   834  				pkg:     "simd/archsimd/...",
   835  			})
   836  		}
   837  	}
   838  	// Test the other implementations of the simd package that this
   839  	// machine can run. This runs the test binary to find out what they
   840  	// are.
   841  	if !t.compileOnly {
   842  		t.registerSimdGODEBUGTests()
   843  	}
   844  
   845  	// Test ios/amd64 for the iOS simulator.
   846  	if goos == "darwin" && goarch == "amd64" && t.cgoEnabled {
   847  		t.registerTest("GOOS=ios on darwin/amd64",
   848  			&goTest{
   849  				variant:  "amd64ios",
   850  				runTests: "SystemRoots",
   851  				env:      []string{"GOOS=ios", "CGO_ENABLED=1"},
   852  				pkg:      "crypto/x509",
   853  			})
   854  	}
   855  
   856  	// GC debug mode tests. We only run these in long-test mode
   857  	// (with GO_TEST_SHORT=0) because this is just testing a
   858  	// non-critical debug setting.
   859  	if !t.compileOnly && !t.short {
   860  		t.registerTest("GODEBUG=gcstoptheworld=2 archive/zip",
   861  			&goTest{
   862  				variant: "gcstoptheworld2",
   863  				short:   true,
   864  				env:     []string{"GODEBUG=gcstoptheworld=2"},
   865  				pkg:     "archive/zip",
   866  			})
   867  		t.registerTest("GODEBUG=gccheckmark=1 runtime",
   868  			&goTest{
   869  				variant: "gccheckmark",
   870  				short:   true,
   871  				env:     []string{"GODEBUG=gccheckmark=1"},
   872  				pkg:     "runtime",
   873  			})
   874  	}
   875  
   876  	// Spectre mitigation smoke test.
   877  	if goos == "linux" && goarch == "amd64" && !(gogcflags == "-spectre=all" && t.asmflags == "all=-spectre=all") {
   878  		// Pick a bunch of packages known to have some assembly.
   879  		pkgs := []string{"internal/runtime/...", "reflect", "crypto/..."}
   880  		if !t.short {
   881  			pkgs = append(pkgs, "runtime")
   882  		}
   883  		t.registerTest("spectre",
   884  			&goTest{
   885  				variant: "spectre",
   886  				short:   true,
   887  				env:     []string{"GOFLAGS=-gcflags=all=-spectre=all -asmflags=all=-spectre=all"},
   888  				pkgs:    pkgs,
   889  			})
   890  	}
   891  
   892  	// morestack tests. We only run these in long-test mode
   893  	// (with GO_TEST_SHORT=0) because the runtime test is
   894  	// already quite long and mayMoreStackMove makes it about
   895  	// twice as slow.
   896  	if !t.compileOnly && !t.short {
   897  		// hooks is the set of maymorestack hooks to test with.
   898  		hooks := []string{"mayMoreStackPreempt", "mayMoreStackMove"}
   899  		// hookPkgs is the set of package patterns to apply
   900  		// the maymorestack hook to.
   901  		hookPkgs := []string{"runtime/...", "reflect", "sync"}
   902  		// unhookPkgs is the set of package patterns to
   903  		// exclude from hookPkgs.
   904  		unhookPkgs := []string{"runtime/testdata/..."}
   905  		for _, hook := range hooks {
   906  			// Construct the build flags to use the
   907  			// maymorestack hook in the compiler and
   908  			// assembler. We pass this via the GOFLAGS
   909  			// environment variable so that it applies to
   910  			// both the test itself and to binaries built
   911  			// by the test.
   912  			goFlagsList := []string{}
   913  			for _, flag := range []string{"-gcflags", "-asmflags"} {
   914  				for _, hookPkg := range hookPkgs {
   915  					goFlagsList = append(goFlagsList, flag+"="+hookPkg+"=-d=maymorestack=runtime."+hook)
   916  				}
   917  				for _, unhookPkg := range unhookPkgs {
   918  					goFlagsList = append(goFlagsList, flag+"="+unhookPkg+"=")
   919  				}
   920  			}
   921  			goFlags := strings.Join(goFlagsList, " ")
   922  
   923  			t.registerTest("maymorestack="+hook,
   924  				&goTest{
   925  					variant: hook,
   926  					short:   true,
   927  					env:     []string{"GOFLAGS=" + goFlags},
   928  					pkgs:    []string{"runtime", "reflect", "sync"},
   929  				})
   930  		}
   931  	}
   932  
   933  	// Test that internal linking of standard packages does not
   934  	// require libgcc. This ensures that we can install a Go
   935  	// release on a system that does not have a C compiler
   936  	// installed and still build Go programs (that don't use cgo).
   937  	for _, pkg := range cgoPackages {
   938  		if !t.internalLink() {
   939  			break
   940  		}
   941  
   942  		// ARM libgcc may be Thumb, which internal linking does not support.
   943  		if goarch == "arm" {
   944  			break
   945  		}
   946  
   947  		// What matters is that the tests build and start up.
   948  		// Skip expensive tests, especially x509 TestSystemRoots.
   949  		run := "^Test[^CS]"
   950  		if pkg == "net" {
   951  			run = "TestTCPStress"
   952  		}
   953  		t.registerTest("Testing without libgcc.",
   954  			&goTest{
   955  				variant:  "nolibgcc",
   956  				ldflags:  "-linkmode=internal -libgcc=none",
   957  				runTests: run,
   958  				pkg:      pkg,
   959  			})
   960  	}
   961  
   962  	// Stub out following test on alpine until 54354 resolved.
   963  	builderName := os.Getenv("GO_BUILDER_NAME")
   964  	disablePIE := strings.HasSuffix(builderName, "-alpine")
   965  
   966  	// Test internal linking of PIE binaries where it is supported.
   967  	if t.internalLinkPIE() && !disablePIE {
   968  		t.registerTest("internal linking, -buildmode=pie",
   969  			&goTest{
   970  				variant:   "pie_internal",
   971  				buildmode: "pie",
   972  				ldflags:   "-linkmode=internal",
   973  				env:       []string{"CGO_ENABLED=0"},
   974  				pkg:       "reflect",
   975  			})
   976  		t.registerTest("internal linking, -buildmode=pie",
   977  			&goTest{
   978  				variant:   "pie_internal",
   979  				buildmode: "pie",
   980  				ldflags:   "-linkmode=internal",
   981  				env:       []string{"CGO_ENABLED=0"},
   982  				pkg:       "crypto/internal/fips140test",
   983  				runTests:  "TestFIPSCheck",
   984  			})
   985  		// Also test a cgo package.
   986  		if t.cgoEnabled && t.internalLink() && !disablePIE {
   987  			t.registerTest("internal linking, -buildmode=pie",
   988  				&goTest{
   989  					variant:   "pie_internal",
   990  					buildmode: "pie",
   991  					ldflags:   "-linkmode=internal",
   992  					pkg:       "os/user",
   993  				})
   994  		}
   995  	}
   996  
   997  	if t.extLink() && !t.compileOnly {
   998  		if goos != "android" { // Android does not support non-PIE linking
   999  			t.registerTest("external linking, -buildmode=exe",
  1000  				&goTest{
  1001  					variant:   "exe_external",
  1002  					buildmode: "exe",
  1003  					ldflags:   "-linkmode=external",
  1004  					env:       []string{"CGO_ENABLED=1"},
  1005  					pkg:       "crypto/internal/fips140test",
  1006  					runTests:  "TestFIPSCheck",
  1007  				})
  1008  		}
  1009  		if t.externalLinkPIE() && !disablePIE {
  1010  			t.registerTest("external linking, -buildmode=pie",
  1011  				&goTest{
  1012  					variant:   "pie_external",
  1013  					buildmode: "pie",
  1014  					ldflags:   "-linkmode=external",
  1015  					env:       []string{"CGO_ENABLED=1"},
  1016  					pkg:       "crypto/internal/fips140test",
  1017  					runTests:  "TestFIPSCheck",
  1018  				})
  1019  		}
  1020  	}
  1021  
  1022  	// sync tests
  1023  	if !t.compileOnly && t.hasParallelism() {
  1024  		t.registerTest("sync -cpu=10",
  1025  			&goTest{
  1026  				variant: "cpu10",
  1027  				cpu:     "10",
  1028  				pkg:     "sync",
  1029  			})
  1030  	}
  1031  
  1032  	const cgoHeading = "Testing cgo"
  1033  	if t.cgoEnabled {
  1034  		t.registerCgoTests(cgoHeading)
  1035  	}
  1036  
  1037  	if goos == "wasip1" {
  1038  		t.registerTest("wasip1 host tests",
  1039  			&goTest{
  1040  				variant:   "host",
  1041  				pkg:       "internal/runtime/wasitest",
  1042  				runOnHost: true,
  1043  			})
  1044  	}
  1045  
  1046  	// Runtime CPU tests.
  1047  	if !t.compileOnly && t.hasParallelism() {
  1048  		for i := 1; i <= 4; i *= 2 {
  1049  			t.registerTest(fmt.Sprintf("GOMAXPROCS=2 runtime -cpu=%d -quick", i),
  1050  				&goTest{
  1051  					variant:   "cpu" + strconv.Itoa(i),
  1052  					cpu:       strconv.Itoa(i),
  1053  					gcflags:   gogcflags,
  1054  					short:     true,
  1055  					testFlags: []string{"-quick"},
  1056  					// We set GOMAXPROCS=2 in addition to -cpu=1,2,4 in order to test runtime bootstrap code,
  1057  					// creation of first goroutines and first garbage collections in the parallel setting.
  1058  					env: []string{"GOMAXPROCS=2"},
  1059  					pkg: "runtime",
  1060  				})
  1061  		}
  1062  	}
  1063  
  1064  	if t.raceDetectorSupported() && !t.msan && !t.asan {
  1065  		// N.B. -race is incompatible with -msan and -asan.
  1066  		t.registerRaceTests()
  1067  	}
  1068  
  1069  	// These tests will be skipped as part of the initial go test std cmd invocation for
  1070  	// js and wasip1 and need to be run on the host. Register them specially here.
  1071  	if goos == "js" || goos == "wasip1" {
  1072  		t.registerTest("../test",
  1073  			&goTest{
  1074  				variant:   "host",
  1075  				pkg:       "cmd/internal/testdir",
  1076  				runOnHost: true,
  1077  			},
  1078  		)
  1079  	}
  1080  }
  1081  
  1082  type simdGODEBUGList struct {
  1083  	env     []string
  1084  	heading string
  1085  	cmd     *exec.Cmd
  1086  	out     []byte
  1087  	err     error
  1088  }
  1089  
  1090  // registerSimdGODEBUGTests registers a test of the simd package under each
  1091  // GODEBUG setting that the simd test binary's -list-godebugs flag prints,
  1092  // named like "simd:GODEBUG=simd=128".
  1093  //
  1094  // The simd package selects an implementation based on the CPU, such as the
  1095  // largest vector size the CPU supports, so by default its tests only test
  1096  // that one. Each of these settings selects another implementation that this
  1097  // CPU can run, such as a smaller vector size, which is what programs use on
  1098  // CPUs with fewer features. Which settings work depends on the CPU, so dist
  1099  // asks for the possible settings from the test binary itself.
  1100  func (t *tester) registerSimdGODEBUGTests() {
  1101  	const prefix = "simd:GODEBUG="
  1102  	if len(t.runNames) > 0 && !slices.ContainsFunc(t.runNames, func(name string) bool { return strings.HasPrefix(name, prefix) }) {
  1103  		// The caller named the tests to run, as the builders do, and
  1104  		// none of them is one of these, so don't spend time finding
  1105  		// out what they are.
  1106  		return
  1107  	}
  1108  	if t.listMode || len(t.runNames) > 0 {
  1109  		t.addSimdGODEBUGTests(t.listSimdGODEBUGs(false))
  1110  		return
  1111  	}
  1112  	// Defer discovery so building and running the simd test binary overlaps
  1113  	// with go test std cmd instead of blocking startup.
  1114  	t.deferSimdGODEBUGs = true
  1115  	t.simdGODEBUGInsertAt = len(t.tests)
  1116  }
  1117  
  1118  func (t *tester) listSimdGODEBUGs(background bool) simdGODEBUGList {
  1119  	// Like the simd tests above, turn on the simd experiment if it isn't
  1120  	// on already.
  1121  	var env []string
  1122  	heading := "go test simd"
  1123  	if !slices.Contains(strings.Split(goexperiment, ","), "simd") {
  1124  		env = []string{"GOEXPERIMENT=" + goexperiments("simd")}
  1125  		heading = "GOEXPERIMENT=simd " + heading
  1126  	}
  1127  	// go test only shows what the test binary prints if it fails or if
  1128  	// -v is set.
  1129  	args := []string{"test", "-v"}
  1130  	throttle := background && len(stdMatches) > 0 && runtime.GOMAXPROCS(0) > 4
  1131  	if throttle {
  1132  		// Limit background discovery concurrency so it does not compete
  1133  		// with go test std cmd's build phase.
  1134  		args = append(args, "-p=4")
  1135  	}
  1136  	args = append(args, "simd", "-list-godebugs")
  1137  	cmd := exec.Command(gorootBinGo, args...)
  1138  	setDir(cmd, filepath.Join(goroot, "src"))
  1139  	for _, kv := range env {
  1140  		k, v, _ := strings.Cut(kv, "=")
  1141  		setEnv(cmd, k, v)
  1142  	}
  1143  	if throttle && t.hasParallelism() {
  1144  		setEnv(cmd, "GOMAXPROCS", "4")
  1145  	}
  1146  	out, err := cmd.CombinedOutput()
  1147  	return simdGODEBUGList{
  1148  		env:     env,
  1149  		heading: heading,
  1150  		cmd:     cmd,
  1151  		out:     out,
  1152  		err:     err,
  1153  	}
  1154  }
  1155  
  1156  func (t *tester) addSimdGODEBUGTests(res simdGODEBUGList) {
  1157  	if res.err != nil {
  1158  		// Most likely the simd tests don't build. Report that as a
  1159  		// failing test, rather than failing to register any tests.
  1160  		t.addTest("simd:list-godebugs", res.heading+" -list-godebugs", func(*distTest) error {
  1161  			return fmt.Errorf("%v: %v\n%s", res.cmd, res.err, res.out)
  1162  		})
  1163  		return
  1164  	}
  1165  	// Each setting is a line of the form GODEBUG=something. The other
  1166  	// lines are from go test.
  1167  	for _, line := range strings.Split(string(res.out), "\n") {
  1168  		setting := strings.TrimSpace(line)
  1169  		if !strings.HasPrefix(setting, "GODEBUG=") {
  1170  			continue
  1171  		}
  1172  		t.registerTest(setting+" "+res.heading, &goTest{
  1173  			variant: setting,
  1174  			env:     append(res.env[:len(res.env):len(res.env)], setting),
  1175  			pkg:     "simd",
  1176  		})
  1177  	}
  1178  }
  1179  
  1180  // addTest adds an arbitrary test callback to the test list.
  1181  //
  1182  // name must uniquely identify the test and heading must be non-empty.
  1183  func (t *tester) addTest(name, heading string, fn func(*distTest) error) {
  1184  	if t.testNames[name] {
  1185  		panic("duplicate registered test name " + name)
  1186  	}
  1187  	if heading == "" {
  1188  		panic("empty heading")
  1189  	}
  1190  	// Two simple checks for cases that would conflict with the fast path in registerTests.
  1191  	if !strings.Contains(name, ":") && heading != "Testing packages." {
  1192  		panic("empty variant is reserved exclusively for registerStdTest")
  1193  	} else if strings.HasSuffix(name, ":racebench") && heading != "Running benchmarks briefly." {
  1194  		panic("racebench variant is reserved exclusively for registerRaceBenchTest")
  1195  	}
  1196  	if t.testNames == nil {
  1197  		t.testNames = make(map[string]bool)
  1198  	}
  1199  	t.testNames[name] = true
  1200  	t.tests = append(t.tests, distTest{
  1201  		name:    name,
  1202  		heading: heading,
  1203  		fn:      fn,
  1204  	})
  1205  }
  1206  
  1207  type registerTestOpt interface {
  1208  	isRegisterTestOpt()
  1209  }
  1210  
  1211  // rtSkipFunc is a registerTest option that runs a skip check function before
  1212  // running the test.
  1213  type rtSkipFunc struct {
  1214  	skip func(*distTest) (string, bool) // Return message, true to skip the test
  1215  }
  1216  
  1217  func (rtSkipFunc) isRegisterTestOpt() {}
  1218  
  1219  // registerTest registers a test that runs the given goTest.
  1220  //
  1221  // Each Go package in goTest will have a corresponding test
  1222  // "<pkg>:<variant>", which must uniquely identify the test.
  1223  //
  1224  // heading and test.variant must be non-empty.
  1225  func (t *tester) registerTest(heading string, test *goTest, opts ...registerTestOpt) {
  1226  	var skipFunc func(*distTest) (string, bool)
  1227  	for _, opt := range opts {
  1228  		switch opt := opt.(type) {
  1229  		case rtSkipFunc:
  1230  			skipFunc = opt.skip
  1231  		}
  1232  	}
  1233  	// Register each test package as a separate test.
  1234  	register1 := func(test *goTest) {
  1235  		if test.variant == "" {
  1236  			panic("empty variant")
  1237  		}
  1238  		name := testName(test.pkg, test.variant)
  1239  		t.addTest(name, heading, func(dt *distTest) error {
  1240  			if skipFunc != nil {
  1241  				msg, skip := skipFunc(dt)
  1242  				if skip {
  1243  					test.printSkip(t, msg)
  1244  					return nil
  1245  				}
  1246  			}
  1247  			w := &work{dt: dt}
  1248  			w.cmd, w.flush = test.bgCommand(t, &w.out, &w.out)
  1249  			t.worklist = append(t.worklist, w)
  1250  			return nil
  1251  		})
  1252  	}
  1253  	if test.pkg != "" && len(test.pkgs) == 0 {
  1254  		// Common case. Avoid copying.
  1255  		register1(test)
  1256  		return
  1257  	}
  1258  	// TODO(dmitshur,austin): It might be better to unify the execution of 'go test pkg'
  1259  	// invocations for the same variant to be done with a single 'go test pkg1 pkg2 pkg3'
  1260  	// command, just like it's already done in registerStdTest and registerRaceBenchTest.
  1261  	// Those methods accumulate matched packages in stdMatches and benchMatches slices,
  1262  	// and we can extend that mechanism to work for all other equal variant registrations.
  1263  	// Do the simple thing to start with.
  1264  	for _, pkg := range test.packages() {
  1265  		test1 := *test
  1266  		test1.pkg, test1.pkgs = pkg, nil
  1267  		register1(&test1)
  1268  	}
  1269  }
  1270  
  1271  // dirCmd constructs a Cmd intended to be run in the foreground.
  1272  // The command will be run in dir, and Stdout and Stderr will go to os.Stdout
  1273  // and os.Stderr.
  1274  func (t *tester) dirCmd(dir string, cmdline ...any) *exec.Cmd {
  1275  	bin, args := flattenCmdline(cmdline)
  1276  	cmd := exec.Command(bin, args...)
  1277  	if filepath.IsAbs(dir) {
  1278  		setDir(cmd, dir)
  1279  	} else {
  1280  		setDir(cmd, filepath.Join(goroot, dir))
  1281  	}
  1282  	cmd.Stdout = os.Stdout
  1283  	cmd.Stderr = os.Stderr
  1284  	if vflag > 1 {
  1285  		errprintf("%#q\n", cmd)
  1286  	}
  1287  	return cmd
  1288  }
  1289  
  1290  // flattenCmdline flattens a mixture of string and []string as single list
  1291  // and then interprets it as a command line: first element is binary, then args.
  1292  func flattenCmdline(cmdline []any) (bin string, args []string) {
  1293  	var list []string
  1294  	for _, x := range cmdline {
  1295  		switch x := x.(type) {
  1296  		case string:
  1297  			list = append(list, x)
  1298  		case []string:
  1299  			list = append(list, x...)
  1300  		default:
  1301  			panic("invalid dirCmd argument type: " + reflect.TypeOf(x).String())
  1302  		}
  1303  	}
  1304  
  1305  	bin = list[0]
  1306  	if !filepath.IsAbs(bin) {
  1307  		panic("command is not absolute: " + bin)
  1308  	}
  1309  	return bin, list[1:]
  1310  }
  1311  
  1312  func (t *tester) iOS() bool {
  1313  	return goos == "ios"
  1314  }
  1315  
  1316  func (t *tester) out(v string) {
  1317  	if t.json {
  1318  		return
  1319  	}
  1320  	if t.banner == "" {
  1321  		return
  1322  	}
  1323  	fmt.Println("\n" + t.banner + v)
  1324  }
  1325  
  1326  // extLink reports whether the current goos/goarch supports
  1327  // external linking.
  1328  func (t *tester) extLink() bool {
  1329  	if !cgoEnabled[goos+"/"+goarch] {
  1330  		return false
  1331  	}
  1332  	if goarch == "ppc64" && goos != "aix" && goos != "linux" {
  1333  		return false
  1334  	}
  1335  	return true
  1336  }
  1337  
  1338  func (t *tester) internalLink() bool {
  1339  	if gohostos == "dragonfly" {
  1340  		// linkmode=internal fails on dragonfly since errno is a TLS relocation.
  1341  		return false
  1342  	}
  1343  	if goos == "android" {
  1344  		return false
  1345  	}
  1346  	if goos == "ios" {
  1347  		return false
  1348  	}
  1349  	// Internally linking cgo is incomplete on some architectures.
  1350  	// https://golang.org/issue/10373
  1351  	// https://golang.org/issue/14449
  1352  	if goarch == "mips64" || goarch == "mips64le" || goarch == "mips" || goarch == "mipsle" || goarch == "riscv64" {
  1353  		return false
  1354  	}
  1355  	if goos == "aix" {
  1356  		// linkmode=internal isn't supported.
  1357  		return false
  1358  	}
  1359  	if t.msan || t.asan {
  1360  		// linkmode=internal isn't supported by msan or asan.
  1361  		return false
  1362  	}
  1363  	return true
  1364  }
  1365  
  1366  func (t *tester) internalLinkPIE() bool {
  1367  	if t.msan || t.asan {
  1368  		// linkmode=internal isn't supported by msan or asan.
  1369  		return false
  1370  	}
  1371  	switch goos + "-" + goarch {
  1372  	case "darwin-amd64", "darwin-arm64",
  1373  		"freebsd-amd64",
  1374  		"linux-amd64", "linux-arm64", "linux-loong64", "linux-ppc64", "linux-ppc64le", "linux-s390x",
  1375  		"android-arm64",
  1376  		"windows-amd64", "windows-386", "windows-arm64":
  1377  		return true
  1378  	}
  1379  	return false
  1380  }
  1381  
  1382  func (t *tester) externalLinkPIE() bool {
  1383  	// General rule is if -buildmode=pie and -linkmode=external both work, then they work together.
  1384  	return t.internalLinkPIE() && t.extLink()
  1385  }
  1386  
  1387  // supportedBuildmode reports whether the given build mode is supported.
  1388  func (t *tester) supportedBuildmode(mode string) bool {
  1389  	switch mode {
  1390  	case "c-archive", "c-shared", "shared", "plugin", "pie":
  1391  	default:
  1392  		fatalf("internal error: unknown buildmode %s", mode)
  1393  		return false
  1394  	}
  1395  
  1396  	return buildModeSupported("gc", mode, goos, goarch)
  1397  }
  1398  
  1399  func (t *tester) registerCgoTests(heading string) {
  1400  	cgoTest := func(variant string, subdir, linkmode, buildmode string, opts ...registerTestOpt) *goTest {
  1401  		gt := &goTest{
  1402  			variant:   variant,
  1403  			pkg:       "cmd/cgo/internal/" + subdir,
  1404  			buildmode: buildmode,
  1405  		}
  1406  		var ldflags []string
  1407  		if linkmode != "auto" {
  1408  			// "auto" is the default, so avoid cluttering the command line for "auto"
  1409  			ldflags = append(ldflags, "-linkmode="+linkmode)
  1410  		}
  1411  
  1412  		if linkmode == "internal" {
  1413  			gt.tags = append(gt.tags, "internal")
  1414  			if buildmode == "pie" {
  1415  				gt.tags = append(gt.tags, "internal_pie")
  1416  			}
  1417  		}
  1418  		if buildmode == "static" {
  1419  			// This isn't actually a Go buildmode, just a convenient way to tell
  1420  			// cgoTest we want static linking.
  1421  			gt.buildmode = ""
  1422  			switch linkmode {
  1423  			case "external":
  1424  				ldflags = append(ldflags, `-extldflags "-static -pthread"`)
  1425  			case "auto":
  1426  				gt.env = append(gt.env, "CGO_LDFLAGS=-static -pthread")
  1427  			default:
  1428  				panic("unknown linkmode with static build: " + linkmode)
  1429  			}
  1430  			gt.tags = append(gt.tags, "static")
  1431  		}
  1432  		gt.ldflags = strings.Join(ldflags, " ")
  1433  
  1434  		t.registerTest(heading, gt, opts...)
  1435  		return gt
  1436  	}
  1437  
  1438  	// test, testtls, and testnocgo are run with linkmode="auto", buildmode=""
  1439  	// as part of go test cmd. Here we only have to register the non-default
  1440  	// build modes of these tests.
  1441  
  1442  	// Stub out various buildmode=pie tests  on alpine until 54354 resolved.
  1443  	builderName := os.Getenv("GO_BUILDER_NAME")
  1444  	disablePIE := strings.HasSuffix(builderName, "-alpine")
  1445  
  1446  	if t.internalLink() {
  1447  		cgoTest("internal", "test", "internal", "")
  1448  	}
  1449  
  1450  	os := gohostos
  1451  	p := gohostos + "/" + goarch
  1452  	switch os {
  1453  	case "darwin", "windows":
  1454  		if !t.extLink() {
  1455  			break
  1456  		}
  1457  		// test linkmode=external, but __thread not supported, so skip testtls.
  1458  		cgoTest("external", "test", "external", "")
  1459  
  1460  		gt := cgoTest("external-s", "test", "external", "")
  1461  		gt.ldflags += " -s"
  1462  
  1463  		if t.supportedBuildmode("pie") && !disablePIE {
  1464  			cgoTest("auto-pie", "test", "auto", "pie")
  1465  			if t.internalLink() && t.internalLinkPIE() {
  1466  				cgoTest("internal-pie", "test", "internal", "pie")
  1467  			}
  1468  		}
  1469  
  1470  	case "aix", "android", "dragonfly", "freebsd", "linux", "netbsd", "openbsd":
  1471  		gt := cgoTest("external-g0", "test", "external", "")
  1472  		gt.env = append(gt.env, "CGO_CFLAGS=-g0 -fdiagnostics-color")
  1473  
  1474  		cgoTest("external", "testtls", "external", "")
  1475  		switch {
  1476  		case os == "aix":
  1477  			// no static linking
  1478  		case p == "freebsd/arm":
  1479  			// -fPIC compiled tls code will use __tls_get_addr instead
  1480  			// of __aeabi_read_tp, however, on FreeBSD/ARM, __tls_get_addr
  1481  			// is implemented in rtld-elf, so -fPIC isn't compatible with
  1482  			// static linking on FreeBSD/ARM with clang. (cgo depends on
  1483  			// -fPIC fundamentally.)
  1484  		default:
  1485  			// Check for static linking support
  1486  			var staticCheck rtSkipFunc
  1487  			ccName := compilerEnvLookup("CC", defaultcc, goos, goarch)
  1488  			cc, err := exec.LookPath(ccName)
  1489  			if err != nil {
  1490  				staticCheck.skip = func(*distTest) (string, bool) {
  1491  					return fmt.Sprintf("$CC (%q) not found, skip cgo static linking test.", ccName), true
  1492  				}
  1493  			} else {
  1494  				cmd := t.dirCmd("src/cmd/cgo/internal/test", cc, "-xc", "-o", "/dev/null", "-static", "-")
  1495  				cmd.Stdin = strings.NewReader("int main() {}")
  1496  				cmd.Stdout, cmd.Stderr = nil, nil // Discard output
  1497  				if err := cmd.Run(); err != nil {
  1498  					// Skip these tests
  1499  					staticCheck.skip = func(*distTest) (string, bool) {
  1500  						return "No support for static linking found (lacks libc.a?), skip cgo static linking test.", true
  1501  					}
  1502  				}
  1503  			}
  1504  
  1505  			// Doing a static link with boringcrypto gets
  1506  			// a C linker warning on Linux.
  1507  			// in function `bio_ip_and_port_to_socket_and_addr':
  1508  			// warning: Using 'getaddrinfo' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
  1509  			if staticCheck.skip == nil && goos == "linux" && strings.Contains(goexperiment, "boringcrypto") {
  1510  				staticCheck.skip = func(*distTest) (string, bool) {
  1511  					return "skipping static linking check on Linux when using boringcrypto to avoid C linker warning about getaddrinfo", true
  1512  				}
  1513  			}
  1514  
  1515  			// Static linking tests
  1516  			if goos != "android" && p != "netbsd/arm" && !t.msan && !t.asan {
  1517  				// TODO(#56629): Why does this fail on netbsd-arm?
  1518  				// TODO(#70080): Why does this fail with msan?
  1519  				// asan doesn't support static linking (this is an explicit build error on the C side).
  1520  				cgoTest("static", "testtls", "external", "static", staticCheck)
  1521  			}
  1522  			cgoTest("external", "testnocgo", "external", "", staticCheck)
  1523  			if goos != "android" && !t.msan && !t.asan {
  1524  				// TODO(#70080): Why does this fail with msan?
  1525  				// asan doesn't support static linking (this is an explicit build error on the C side).
  1526  				cgoTest("static", "testnocgo", "external", "static", staticCheck)
  1527  				cgoTest("static", "test", "external", "static", staticCheck)
  1528  				// -static in CGO_LDFLAGS triggers a different code path
  1529  				// than -static in -extldflags, so test both.
  1530  				// See issue #16651.
  1531  				if goarch != "loong64" && !t.msan && !t.asan {
  1532  					// TODO(#56623): Why does this fail on loong64?
  1533  					cgoTest("auto-static", "test", "auto", "static", staticCheck)
  1534  				}
  1535  			}
  1536  
  1537  			// PIE linking tests
  1538  			if t.supportedBuildmode("pie") && !disablePIE {
  1539  				cgoTest("auto-pie", "test", "auto", "pie")
  1540  				if t.internalLink() && t.internalLinkPIE() {
  1541  					cgoTest("internal-pie", "test", "internal", "pie")
  1542  				}
  1543  				cgoTest("auto-pie", "testtls", "auto", "pie")
  1544  				cgoTest("auto-pie", "testnocgo", "auto", "pie")
  1545  			}
  1546  		}
  1547  	}
  1548  }
  1549  
  1550  // runPending runs pending test commands, in parallel, emitting headers as appropriate.
  1551  // When finished, it emits header for nextTest, which is going to run after the
  1552  // pending commands are done (and runPending returns).
  1553  // A test should call runPending if it wants to make sure that it is not
  1554  // running in parallel with earlier tests, or if it has some other reason
  1555  // for needing the earlier tests to be done.
  1556  func (t *tester) runPending(nextTest *distTest) {
  1557  	worklist := t.worklist
  1558  	t.worklist = nil
  1559  	var pendingSpan span
  1560  	if len(worklist) > 0 {
  1561  		pendingSpan = startSpan("runPending")
  1562  	}
  1563  	maxbg := runtime.GOMAXPROCS(0)
  1564  	capProcs := len(worklist) > 1 && t.hasParallelism() && !isEnvSet("GOMAXPROCS") && maxbg > maxTestGOMAXPROCS
  1565  	for i, w := range worklist {
  1566  		if capProcs && !slices.ContainsFunc(w.cmd.Env, func(kv string) bool { return strings.HasPrefix(kv, "GOMAXPROCS=") }) {
  1567  			setEnv(w.cmd, "GOMAXPROCS", strconv.Itoa(maxTestGOMAXPROCS))
  1568  		}
  1569  		w.start = make(chan bool)
  1570  		w.end = make(chan struct{})
  1571  		// w.cmd must be set up to write to w.out. We can't check that, but we
  1572  		// can check for easy mistakes.
  1573  		if w.cmd.Stdout == nil || w.cmd.Stdout == os.Stdout || w.cmd.Stderr == nil || w.cmd.Stderr == os.Stderr {
  1574  			panic("work.cmd.Stdout/Stderr must be redirected")
  1575  		}
  1576  		go func(w *work) {
  1577  			if !<-w.start {
  1578  				timelog("skip", w.dt.name)
  1579  				w.printSkip(t, "skipped due to earlier error")
  1580  			} else {
  1581  				timelog("start", w.dt.name)
  1582  				s := startSpanTID(w.dt.name, uint64(i%maxbg+1))
  1583  				w.err = w.cmd.Run()
  1584  				if w.flush != nil {
  1585  					w.flush()
  1586  				}
  1587  				s.done()
  1588  				if w.err != nil {
  1589  					if isUnsupportedVMASize(w) {
  1590  						timelog("skip", w.dt.name)
  1591  						w.out.Reset()
  1592  						w.printSkip(t, "skipped due to unsupported VMA")
  1593  						w.err = nil
  1594  					}
  1595  				}
  1596  			}
  1597  			timelog("end", w.dt.name)
  1598  			w.end <- struct{}{}
  1599  		}(w)
  1600  	}
  1601  
  1602  	started := 0
  1603  	ended := 0
  1604  	var last *distTest
  1605  	for ended < len(worklist) {
  1606  		for started < len(worklist) && started-ended < maxbg {
  1607  			w := worklist[started]
  1608  			started++
  1609  			w.start <- !t.failed || t.keepGoing
  1610  		}
  1611  		w := worklist[ended]
  1612  		dt := w.dt
  1613  		if t.lastHeading != dt.heading {
  1614  			t.lastHeading = dt.heading
  1615  			t.out(dt.heading)
  1616  		}
  1617  		if dt != last {
  1618  			// Assumes all the entries for a single dt are in one worklist.
  1619  			last = w.dt
  1620  			if vflag > 0 {
  1621  				fmt.Printf("# go tool dist test -run=^%s$\n", dt.name)
  1622  			}
  1623  		}
  1624  		if vflag > 1 {
  1625  			errprintf("%#q\n", w.cmd)
  1626  		}
  1627  		ended++
  1628  		<-w.end
  1629  		os.Stdout.Write(w.out.Bytes())
  1630  		// We no longer need the output, so drop the buffer.
  1631  		w.out = bytes.Buffer{}
  1632  		if w.err != nil {
  1633  			log.Printf("Failed: %v", w.err)
  1634  			t.failed = true
  1635  		}
  1636  	}
  1637  	pendingSpan.done()
  1638  	if t.failed && !t.keepGoing {
  1639  		fatalf("FAILED")
  1640  	}
  1641  
  1642  	if dt := nextTest; dt != nil {
  1643  		if t.lastHeading != dt.heading {
  1644  			t.lastHeading = dt.heading
  1645  			t.out(dt.heading)
  1646  		}
  1647  		if vflag > 0 {
  1648  			fmt.Printf("# go tool dist test -run=^%s$\n", dt.name)
  1649  		}
  1650  	}
  1651  }
  1652  
  1653  // hasParallelism is a copy of the function
  1654  // internal/testenv.HasParallelism, which can't be used here
  1655  // because cmd/dist can not import internal packages during bootstrap.
  1656  func (t *tester) hasParallelism() bool {
  1657  	switch goos {
  1658  	case "js", "wasip1":
  1659  		return false
  1660  	}
  1661  	return true
  1662  }
  1663  
  1664  func (t *tester) raceDetectorSupported() bool {
  1665  	if gohostos != goos {
  1666  		return false
  1667  	}
  1668  	if !t.cgoEnabled {
  1669  		return false
  1670  	}
  1671  	if !raceDetectorSupported(goos, goarch) {
  1672  		return false
  1673  	}
  1674  	// The race detector doesn't work on Alpine Linux:
  1675  	// golang.org/issue/14481
  1676  	if isAlpineLinux() {
  1677  		return false
  1678  	}
  1679  	// NetBSD support is unfinished.
  1680  	// golang.org/issue/26403
  1681  	if goos == "netbsd" {
  1682  		return false
  1683  	}
  1684  	return true
  1685  }
  1686  
  1687  func isAlpineLinux() bool {
  1688  	if runtime.GOOS != "linux" {
  1689  		return false
  1690  	}
  1691  	fi, err := os.Lstat("/etc/alpine-release")
  1692  	return err == nil && fi.Mode().IsRegular()
  1693  }
  1694  
  1695  func (t *tester) registerRaceTests() {
  1696  	hdr := "Testing race detector"
  1697  	t.registerTest(hdr,
  1698  		&goTest{
  1699  			variant:  "race",
  1700  			race:     true,
  1701  			runTests: "Output",
  1702  			pkg:      "runtime/race",
  1703  		})
  1704  	t.registerTest(hdr,
  1705  		&goTest{
  1706  			variant:  "race",
  1707  			race:     true,
  1708  			runTests: "TestParse|TestEcho|TestStdinCloseRace|TestClosedPipeRace|TestTypeRace|TestFdRace|TestFdReadRace|TestFileCloseRace",
  1709  			pkgs:     []string{"flag", "net", "os", "os/exec", "encoding/gob"},
  1710  		})
  1711  	// We don't want the following line, because it
  1712  	// slows down all.bash (by 10 seconds on my laptop).
  1713  	// The race builder should catch any error here, but doesn't.
  1714  	// TODO(iant): Figure out how to catch this.
  1715  	// t.registerTest(hdr, &goTest{variant: "race", race: true, runTests: "TestParallelTest", pkg: "cmd/go"})
  1716  	if t.cgoEnabled {
  1717  		// Building cmd/cgo/internal/test takes a long time.
  1718  		// There are already cgo-enabled packages being tested with the race detector.
  1719  		// We shouldn't need to redo all of cmd/cgo/internal/test too.
  1720  		// The race builder will take care of this.
  1721  		// t.registerTest(hdr, &goTest{variant: "race", race: true, env: []string{"GOTRACEBACK=2"}, pkg: "cmd/cgo/internal/test"})
  1722  	}
  1723  	if t.extLink() {
  1724  		// Test with external linking; see issue 9133.
  1725  		t.registerTest(hdr,
  1726  			&goTest{
  1727  				variant:  "race-external",
  1728  				race:     true,
  1729  				ldflags:  "-linkmode=external",
  1730  				runTests: "TestParse|TestEcho|TestStdinCloseRace",
  1731  				pkgs:     []string{"flag", "os/exec"},
  1732  			})
  1733  	}
  1734  }
  1735  
  1736  // cgoPackages is the standard packages that use cgo.
  1737  var cgoPackages = []string{
  1738  	"net",
  1739  	"os/user",
  1740  }
  1741  
  1742  var funcBenchmark = []byte("\nfunc Benchmark")
  1743  
  1744  // packageHasBenchmarks reports whether pkg has benchmarks.
  1745  // On any error, it conservatively returns true.
  1746  //
  1747  // This exists just to eliminate work on the builders, since compiling
  1748  // a test in race mode just to discover it has no benchmarks costs a
  1749  // second or two per package, and this function returns false for
  1750  // about 100 packages.
  1751  func (t *tester) packageHasBenchmarks(pkg string) bool {
  1752  	pkgDir := filepath.Join(goroot, "src", pkg)
  1753  	d, err := os.Open(pkgDir)
  1754  	if err != nil {
  1755  		return true // conservatively
  1756  	}
  1757  	defer d.Close()
  1758  	names, err := d.Readdirnames(-1)
  1759  	if err != nil {
  1760  		return true // conservatively
  1761  	}
  1762  	for _, name := range names {
  1763  		if !strings.HasSuffix(name, "_test.go") {
  1764  			continue
  1765  		}
  1766  		slurp, err := os.ReadFile(filepath.Join(pkgDir, name))
  1767  		if err != nil {
  1768  			return true // conservatively
  1769  		}
  1770  		if bytes.Contains(slurp, funcBenchmark) {
  1771  			return true
  1772  		}
  1773  	}
  1774  	return false
  1775  }
  1776  
  1777  // makeGOROOTUnwritable makes all $GOROOT files & directories non-writable to
  1778  // check that no tests accidentally write to $GOROOT.
  1779  func (t *tester) makeGOROOTUnwritable() (undo func()) {
  1780  	dir := os.Getenv("GOROOT")
  1781  	if dir == "" {
  1782  		panic("GOROOT not set")
  1783  	}
  1784  
  1785  	type pathMode struct {
  1786  		path string
  1787  		mode os.FileMode
  1788  	}
  1789  	var dirs []pathMode // in lexical order
  1790  
  1791  	undo = func() {
  1792  		for i := range dirs {
  1793  			os.Chmod(dirs[i].path, dirs[i].mode) // best effort
  1794  		}
  1795  	}
  1796  
  1797  	filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
  1798  		if suffix := strings.TrimPrefix(path, dir+string(filepath.Separator)); suffix != "" {
  1799  			if suffix == ".git" {
  1800  				// Leave Git metadata in whatever state it was in. It may contain a lot
  1801  				// of files, and it is highly unlikely that a test will try to modify
  1802  				// anything within that directory.
  1803  				return filepath.SkipDir
  1804  			}
  1805  		}
  1806  		if err != nil {
  1807  			return nil
  1808  		}
  1809  
  1810  		info, err := d.Info()
  1811  		if err != nil {
  1812  			return nil
  1813  		}
  1814  
  1815  		mode := info.Mode()
  1816  		if mode&0222 != 0 && (mode.IsDir() || mode.IsRegular()) {
  1817  			dirs = append(dirs, pathMode{path, mode})
  1818  		}
  1819  		return nil
  1820  	})
  1821  
  1822  	// Run over list backward to chmod children before parents.
  1823  	for i := len(dirs) - 1; i >= 0; i-- {
  1824  		err := os.Chmod(dirs[i].path, dirs[i].mode&^0222)
  1825  		if err != nil {
  1826  			dirs = dirs[i:] // Only undo what we did so far.
  1827  			undo()
  1828  			fatalf("failed to make GOROOT read-only: %v", err)
  1829  		}
  1830  	}
  1831  
  1832  	return undo
  1833  }
  1834  
  1835  // raceDetectorSupported is a copy of the function
  1836  // internal/platform.RaceDetectorSupported, which can't be used here
  1837  // because cmd/dist can not import internal packages during bootstrap.
  1838  // The race detector only supports 48-bit VMA on arm64. But we don't have
  1839  // a good solution to check VMA size (see https://go.dev/issue/29948).
  1840  // raceDetectorSupported will always return true for arm64. But race
  1841  // detector tests may abort on non 48-bit VMA configuration, the tests
  1842  // will be marked as "skipped" in this case.
  1843  func raceDetectorSupported(goos, goarch string) bool {
  1844  	switch goos {
  1845  	case "linux":
  1846  		return goarch == "amd64" || goarch == "arm64" || goarch == "loong64" || goarch == "ppc64le" || goarch == "riscv64" || goarch == "s390x"
  1847  	case "darwin":
  1848  		return goarch == "amd64" || goarch == "arm64"
  1849  	case "freebsd", "netbsd", "windows":
  1850  		return goarch == "amd64"
  1851  	default:
  1852  		return false
  1853  	}
  1854  }
  1855  
  1856  // fips140Supported is a copy of the function
  1857  // internal/platform.FIPS140Supported, which can't be used here
  1858  // because cmd/dist can not import internal packages during bootstrap.
  1859  func fips140Supported(goos, goarch string) bool {
  1860  	switch {
  1861  	case goarch == "wasm",
  1862  		goos == "windows" && goarch == "386",
  1863  		goos == "openbsd",
  1864  		goos == "aix":
  1865  		return false
  1866  	}
  1867  	return true
  1868  }
  1869  
  1870  // buildModeSupported is a copy of the function
  1871  // internal/platform.BuildModeSupported, which can't be used here
  1872  // because cmd/dist can not import internal packages during bootstrap.
  1873  func buildModeSupported(compiler, buildmode, goos, goarch string) bool {
  1874  	if compiler == "gccgo" {
  1875  		return true
  1876  	}
  1877  
  1878  	platform := goos + "/" + goarch
  1879  
  1880  	switch buildmode {
  1881  	case "archive":
  1882  		return true
  1883  
  1884  	case "c-archive":
  1885  		switch goos {
  1886  		case "aix", "darwin", "ios", "windows":
  1887  			return true
  1888  		case "linux":
  1889  			switch goarch {
  1890  			case "386", "amd64", "arm", "armbe", "arm64", "arm64be", "loong64", "ppc64", "ppc64le", "riscv64", "s390x":
  1891  				return true
  1892  			default:
  1893  				// Other targets do not support -shared,
  1894  				// per ParseFlags in
  1895  				// cmd/compile/internal/base/flag.go.
  1896  				// For c-archive the Go tool passes -shared,
  1897  				// so that the result is suitable for inclusion
  1898  				// in a PIE or shared library.
  1899  				return false
  1900  			}
  1901  		case "freebsd":
  1902  			return goarch == "amd64"
  1903  		}
  1904  		return false
  1905  
  1906  	case "c-shared":
  1907  		switch platform {
  1908  		case "linux/amd64", "linux/arm", "linux/arm64", "linux/loong64", "linux/386", "linux/ppc64", "linux/ppc64le", "linux/riscv64", "linux/s390x",
  1909  			"android/amd64", "android/arm", "android/arm64", "android/386",
  1910  			"freebsd/amd64",
  1911  			"darwin/amd64", "darwin/arm64",
  1912  			"windows/amd64", "windows/386", "windows/arm64",
  1913  			"wasip1/wasm":
  1914  			return true
  1915  		}
  1916  		return false
  1917  
  1918  	case "default":
  1919  		return true
  1920  
  1921  	case "exe":
  1922  		return true
  1923  
  1924  	case "pie":
  1925  		switch platform {
  1926  		case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/loong64", "linux/ppc64", "linux/ppc64le", "linux/riscv64", "linux/s390x",
  1927  			"android/amd64", "android/arm", "android/arm64", "android/386",
  1928  			"freebsd/amd64",
  1929  			"darwin/amd64", "darwin/arm64",
  1930  			"ios/amd64", "ios/arm64",
  1931  			"aix/ppc64",
  1932  			"openbsd/amd64", "openbsd/arm64",
  1933  			"windows/386", "windows/amd64", "windows/arm64":
  1934  			return true
  1935  		}
  1936  		return false
  1937  
  1938  	case "shared":
  1939  		switch platform {
  1940  		case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64", "linux/ppc64le", "linux/s390x":
  1941  			return true
  1942  		}
  1943  		return false
  1944  
  1945  	case "plugin":
  1946  		switch platform {
  1947  		case "linux/amd64", "linux/arm", "linux/arm64", "linux/386", "linux/loong64", "linux/riscv64", "linux/s390x", "linux/ppc64", "linux/ppc64le",
  1948  			"android/amd64", "android/386",
  1949  			"darwin/amd64", "darwin/arm64",
  1950  			"freebsd/amd64":
  1951  			return true
  1952  		}
  1953  		return false
  1954  
  1955  	default:
  1956  		return false
  1957  	}
  1958  }
  1959  
  1960  // isUnsupportedVMASize reports whether the failure is caused by an unsupported
  1961  // VMA for the race detector (for example, running the race detector on an
  1962  // arm64 machine configured with 39-bit VMA).
  1963  func isUnsupportedVMASize(w *work) bool {
  1964  	unsupportedVMA := []byte("unsupported VMA range")
  1965  	return strings.Contains(w.dt.name, ":race") && bytes.Contains(w.out.Bytes(), unsupportedVMA)
  1966  }
  1967  
  1968  // isEnvSet reports whether the environment variable evar is
  1969  // set in the environment.
  1970  func isEnvSet(evar string) bool {
  1971  	evarEq := evar + "="
  1972  	for _, e := range os.Environ() {
  1973  		if strings.HasPrefix(e, evarEq) {
  1974  			return true
  1975  		}
  1976  	}
  1977  	return false
  1978  }
  1979  
  1980  func (t *tester) fips140Supported() bool {
  1981  	if !fips140Supported(goos, goarch) {
  1982  		return false
  1983  	}
  1984  
  1985  	// Keep the platform checks below in sync with crypto/internal/fips140.Supported.
  1986  	// We don't test with the purego tag, so no need to check it.
  1987  
  1988  	// Use GOFIPS140 or GOEXPERIMENT=boringcrypto, but not both.
  1989  	if strings.Contains(goexperiment, "boringcrypto") {
  1990  		return false
  1991  	}
  1992  
  1993  	// For now, FIPS+ASAN doesn't need to work.
  1994  	// If this is made to work, also re-enable the test in check_test.go.
  1995  	if t.asan {
  1996  		return false
  1997  	}
  1998  
  1999  	return true
  2000  }
  2001  
  2002  // fips140Versions returns the list of versions available in lib/fips140.
  2003  func fips140Versions() []string {
  2004  	var versions []string
  2005  	zips, err := filepath.Glob(filepath.Join(goroot, "lib/fips140/*.zip"))
  2006  	if err != nil {
  2007  		fatalf("%v", err)
  2008  	}
  2009  	for _, zip := range zips {
  2010  		versions = append(versions, strings.TrimSuffix(filepath.Base(zip), ".zip"))
  2011  	}
  2012  	return versions
  2013  }
  2014  
  2015  // goexperiments returns the GOEXPERIMENT value to use
  2016  // when running a test with the given experiments enabled.
  2017  //
  2018  // It preserves any existing GOEXPERIMENTs.
  2019  func goexperiments(exps ...string) string {
  2020  	if len(exps) == 0 {
  2021  		return goexperiment
  2022  	}
  2023  	existing := goexperiment
  2024  	if existing != "" {
  2025  		existing += ","
  2026  	}
  2027  	return existing + strings.Join(exps, ",")
  2028  
  2029  }
  2030  

View as plain text