Source file src/cmd/internal/testdir/testdir_test.go

     1  // Copyright 2012 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 testdir_test runs tests in the GOROOT/test directory.
     6  package testdir_test
     7  
     8  import (
     9  	"bytes"
    10  	"encoding/json"
    11  	"errors"
    12  	"flag"
    13  	"fmt"
    14  	"go/build"
    15  	"go/build/constraint"
    16  	"hash/fnv"
    17  	"internal/testenv"
    18  	"io"
    19  	"io/fs"
    20  	"log"
    21  	"os"
    22  	"os/exec"
    23  	"path"
    24  	"path/filepath"
    25  	"regexp"
    26  	"runtime"
    27  	"slices"
    28  	"sort"
    29  	"strconv"
    30  	"strings"
    31  	"sync"
    32  	"testing"
    33  	"time"
    34  	"unicode"
    35  )
    36  
    37  var (
    38  	allCodegen     = flag.Bool("all_codegen", defaultAllCodeGen(), "run all goos/goarch for codegen")
    39  	runSkips       = flag.Bool("run_skips", false, "run skipped tests (ignore skip and build tags)")
    40  	linkshared     = flag.Bool("linkshared", false, "")
    41  	updateErrors   = flag.Bool("update_errors", false, "update error messages in test file based on compiler output")
    42  	runoutputLimit = flag.Int("l", defaultRunOutputLimit(), "number of parallel runoutput tests to run")
    43  	force          = flag.Bool("f", false, "ignore expected-failure test lists")
    44  	target         = flag.String("target", "", "cross-compile tests for `goos/goarch`")
    45  
    46  	shard  = flag.Int("shard", 0, "shard index to run. Only applicable if -shards is non-zero.")
    47  	shards = flag.Int("shards", 0, "number of shards. If 0, all tests are run. This is used by the continuous build.")
    48  )
    49  
    50  // defaultAllCodeGen returns the default value of the -all_codegen
    51  // flag. By default, we prefer to be fast (returning false), except on
    52  // the linux-amd64 builder that's already very fast, so we get more
    53  // test coverage on trybots. See https://go.dev/issue/34297.
    54  func defaultAllCodeGen() bool {
    55  	return os.Getenv("GO_BUILDER_NAME") == "linux-amd64"
    56  }
    57  
    58  var (
    59  	// Package-scoped variables that are initialized at the start of Test.
    60  	goTool       string
    61  	goos         string // Target GOOS
    62  	goarch       string // Target GOARCH
    63  	cgoEnabled   bool
    64  	goExperiment string
    65  
    66  	// dirs are the directories to look for *.go files in.
    67  	// TODO(bradfitz): just use all directories?
    68  	dirs = []string{".", "ken", "chan", "interface", "syntax", "dwarf", "fixedbugs", "codegen", "runtime", "abi", "typeparam", "typeparam/mdempsky", "arenas"}
    69  )
    70  
    71  // Test is the main entrypoint that runs tests in the GOROOT/test directory.
    72  //
    73  // Each .go file test case in GOROOT/test is registered as a subtest with a
    74  // a full name like "Test/fixedbugs/bug000.go" ('/'-separated relative path).
    75  func Test(t *testing.T) {
    76  	if *target != "" {
    77  		// When -target is set, propagate it to GOOS/GOARCH in our environment
    78  		// so that all commands run with the target GOOS/GOARCH.
    79  		//
    80  		// We do this before even calling "go env", because GOOS/GOARCH can
    81  		// affect other settings we get from go env (notably CGO_ENABLED).
    82  		goos, goarch, ok := strings.Cut(*target, "/")
    83  		if !ok {
    84  			t.Fatalf("bad -target flag %q, expected goos/goarch", *target)
    85  		}
    86  		t.Setenv("GOOS", goos)
    87  		t.Setenv("GOARCH", goarch)
    88  	}
    89  
    90  	goTool = testenv.GoToolPath(t)
    91  	cmd := exec.Command(goTool, "env", "-json")
    92  	stdout, err := cmd.StdoutPipe()
    93  	if err != nil {
    94  		t.Fatal("StdoutPipe:", err)
    95  	}
    96  	if err := cmd.Start(); err != nil {
    97  		t.Fatal("Start:", err)
    98  	}
    99  	var env struct {
   100  		GOOS         string
   101  		GOARCH       string
   102  		GOEXPERIMENT string
   103  		CGO_ENABLED  string
   104  	}
   105  	if err := json.NewDecoder(stdout).Decode(&env); err != nil {
   106  		t.Fatal("Decode:", err)
   107  	}
   108  	if err := cmd.Wait(); err != nil {
   109  		t.Fatal("Wait:", err)
   110  	}
   111  	goos = env.GOOS
   112  	goarch = env.GOARCH
   113  	cgoEnabled, _ = strconv.ParseBool(env.CGO_ENABLED)
   114  	goExperiment = env.GOEXPERIMENT
   115  
   116  	common := testCommon{
   117  		gorootTestDir: filepath.Join(testenv.GOROOT(t), "test"),
   118  		runoutputGate: make(chan bool, *runoutputLimit),
   119  	}
   120  
   121  	// cmd/distpack deletes GOROOT/test, so skip the test if it isn't present.
   122  	// cmd/distpack also requires GOROOT/VERSION to exist, so use that to
   123  	// suppress false-positive skips.
   124  	if _, err := os.Stat(common.gorootTestDir); os.IsNotExist(err) {
   125  		if _, err := os.Stat(filepath.Join(testenv.GOROOT(t), "VERSION")); err == nil {
   126  			t.Skipf("skipping: GOROOT/test not present")
   127  		}
   128  	}
   129  
   130  	for _, dir := range dirs {
   131  		for _, goFile := range goFiles(t, dir) {
   132  			test := test{testCommon: common, dir: dir, goFile: goFile}
   133  			t.Run(path.Join(dir, goFile), func(t *testing.T) {
   134  				t.Parallel()
   135  				test.T = t
   136  				testError := test.run()
   137  				wantError := test.expectFail() && !*force
   138  				if testError != nil {
   139  					if wantError {
   140  						t.Log(testError.Error() + " (expected)")
   141  					} else {
   142  						t.Fatal(testError)
   143  					}
   144  				} else if wantError {
   145  					t.Fatal("unexpected success")
   146  				}
   147  			})
   148  		}
   149  	}
   150  }
   151  
   152  func shardMatch(name string) bool {
   153  	if *shards <= 1 {
   154  		return true
   155  	}
   156  	h := fnv.New32()
   157  	io.WriteString(h, name)
   158  	return int(h.Sum32()%uint32(*shards)) == *shard
   159  }
   160  
   161  func goFiles(t *testing.T, dir string) []string {
   162  	f, err := os.Open(filepath.Join(testenv.GOROOT(t), "test", dir))
   163  	if err != nil {
   164  		t.Fatal(err)
   165  	}
   166  	dirnames, err := f.Readdirnames(-1)
   167  	f.Close()
   168  	if err != nil {
   169  		t.Fatal(err)
   170  	}
   171  	names := []string{}
   172  	for _, name := range dirnames {
   173  		if !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") && shardMatch(name) {
   174  			names = append(names, name)
   175  		}
   176  	}
   177  	sort.Strings(names)
   178  	return names
   179  }
   180  
   181  type runCmd func(...string) ([]byte, error)
   182  
   183  func compileFile(runcmd runCmd, longname string, flags []string) (out []byte, err error) {
   184  	cmd := []string{goTool, "tool", "compile", "-e", "-p=p", "-importcfg=" + stdlibImportcfgFile()}
   185  	cmd = append(cmd, flags...)
   186  	if *linkshared {
   187  		cmd = append(cmd, "-dynlink", "-installsuffix=dynlink")
   188  	}
   189  	cmd = append(cmd, longname)
   190  	return runcmd(cmd...)
   191  }
   192  
   193  func compileInDir(runcmd runCmd, dir string, flags []string, importcfg string, pkgname string, names ...string) (out []byte, err error) {
   194  	if importcfg == "" {
   195  		importcfg = stdlibImportcfgFile()
   196  	}
   197  	cmd := []string{goTool, "tool", "compile", "-e", "-D", "test", "-importcfg=" + importcfg}
   198  	if pkgname == "main" {
   199  		cmd = append(cmd, "-p=main")
   200  	} else {
   201  		pkgname = path.Join("test", strings.TrimSuffix(names[0], ".go"))
   202  		cmd = append(cmd, "-o", pkgname+".a", "-p", pkgname)
   203  	}
   204  	cmd = append(cmd, flags...)
   205  	if *linkshared {
   206  		cmd = append(cmd, "-dynlink", "-installsuffix=dynlink")
   207  	}
   208  	for _, name := range names {
   209  		cmd = append(cmd, filepath.Join(dir, name))
   210  	}
   211  	return runcmd(cmd...)
   212  }
   213  
   214  var stdlibImportcfgStringOnce sync.Once // TODO(#56102): Use sync.OnceValue once available. Also below.
   215  var stdlibImportcfgString string
   216  
   217  func stdlibImportcfg() string {
   218  	stdlibImportcfgStringOnce.Do(func() {
   219  		output, err := exec.Command(goTool, "list", "-export", "-f", "{{if .Export}}packagefile {{.ImportPath}}={{.Export}}{{end}}", "std").Output()
   220  		if err != nil {
   221  			log.Fatal(err)
   222  		}
   223  		stdlibImportcfgString = string(output)
   224  	})
   225  	return stdlibImportcfgString
   226  }
   227  
   228  var stdlibImportcfgFilenameOnce sync.Once
   229  var stdlibImportcfgFilename string
   230  
   231  func stdlibImportcfgFile() string {
   232  	stdlibImportcfgFilenameOnce.Do(func() {
   233  		tmpdir, err := os.MkdirTemp("", "importcfg")
   234  		if err != nil {
   235  			log.Fatal(err)
   236  		}
   237  		filename := filepath.Join(tmpdir, "importcfg")
   238  		err = os.WriteFile(filename, []byte(stdlibImportcfg()), 0644)
   239  		if err != nil {
   240  			log.Fatal(err)
   241  		}
   242  		stdlibImportcfgFilename = filename
   243  	})
   244  	return stdlibImportcfgFilename
   245  }
   246  
   247  func linkFile(runcmd runCmd, goname string, importcfg string, ldflags []string) (err error) {
   248  	if importcfg == "" {
   249  		importcfg = stdlibImportcfgFile()
   250  	}
   251  	pfile := strings.Replace(goname, ".go", ".o", -1)
   252  	cmd := []string{goTool, "tool", "link", "-w", "-o", "a.exe", "-importcfg=" + importcfg}
   253  	if *linkshared {
   254  		cmd = append(cmd, "-linkshared", "-installsuffix=dynlink")
   255  	}
   256  	if ldflags != nil {
   257  		cmd = append(cmd, ldflags...)
   258  	}
   259  	cmd = append(cmd, pfile)
   260  	_, err = runcmd(cmd...)
   261  	return
   262  }
   263  
   264  type testCommon struct {
   265  	// gorootTestDir is the GOROOT/test directory path.
   266  	gorootTestDir string
   267  
   268  	// runoutputGate controls the max number of runoutput tests
   269  	// executed in parallel as they can each consume a lot of memory.
   270  	runoutputGate chan bool
   271  }
   272  
   273  // test is a single test case in the GOROOT/test directory.
   274  type test struct {
   275  	testCommon
   276  	*testing.T
   277  	// dir and goFile identify the test case.
   278  	// For example, "fixedbugs", "bug000.go".
   279  	dir, goFile string
   280  }
   281  
   282  // expectFail reports whether the (overall) test recipe is
   283  // expected to fail under the current build+test configuration.
   284  func (t test) expectFail() bool {
   285  	failureSets := []map[string]bool{types2Failures}
   286  
   287  	// Note: gccgo supports more 32-bit architectures than this, but
   288  	// hopefully the 32-bit failures are fixed before this matters.
   289  	switch goarch {
   290  	case "386", "arm", "mips", "mipsle":
   291  		failureSets = append(failureSets, types2Failures32Bit)
   292  	}
   293  
   294  	testName := path.Join(t.dir, t.goFile) // Test name is '/'-separated.
   295  
   296  	for _, set := range failureSets {
   297  		if set[testName] {
   298  			return true
   299  		}
   300  	}
   301  	return false
   302  }
   303  
   304  func (t test) goFileName() string {
   305  	return filepath.Join(t.dir, t.goFile)
   306  }
   307  
   308  func (t test) goDirName() string {
   309  	return filepath.Join(t.dir, strings.Replace(t.goFile, ".go", ".dir", -1))
   310  }
   311  
   312  // goDirFiles returns .go files in dir.
   313  func goDirFiles(dir string) (filter []fs.DirEntry, _ error) {
   314  	files, err := os.ReadDir(dir)
   315  	if err != nil {
   316  		return nil, err
   317  	}
   318  	for _, goFile := range files {
   319  		if filepath.Ext(goFile.Name()) == ".go" {
   320  			filter = append(filter, goFile)
   321  		}
   322  	}
   323  	return filter, nil
   324  }
   325  
   326  var packageRE = regexp.MustCompile(`(?m)^package ([\p{Lu}\p{Ll}\w]+)`)
   327  
   328  func getPackageNameFromSource(fn string) (string, error) {
   329  	data, err := os.ReadFile(fn)
   330  	if err != nil {
   331  		return "", err
   332  	}
   333  	pkgname := packageRE.FindStringSubmatch(string(data))
   334  	if pkgname == nil {
   335  		return "", fmt.Errorf("cannot find package name in %s", fn)
   336  	}
   337  	return pkgname[1], nil
   338  }
   339  
   340  // goDirPkg represents a Go package in some directory.
   341  type goDirPkg struct {
   342  	name  string
   343  	files []string
   344  }
   345  
   346  // goDirPackages returns distinct Go packages in dir.
   347  // If singlefilepkgs is set, each file is considered a separate package
   348  // even if the package names are the same.
   349  func goDirPackages(t *testing.T, dir string, singlefilepkgs bool) []*goDirPkg {
   350  	files, err := goDirFiles(dir)
   351  	if err != nil {
   352  		t.Fatal(err)
   353  	}
   354  	var pkgs []*goDirPkg
   355  	m := make(map[string]*goDirPkg)
   356  	for _, file := range files {
   357  		name := file.Name()
   358  		pkgname, err := getPackageNameFromSource(filepath.Join(dir, name))
   359  		if err != nil {
   360  			t.Fatal(err)
   361  		}
   362  		p, ok := m[pkgname]
   363  		if singlefilepkgs || !ok {
   364  			p = &goDirPkg{name: pkgname}
   365  			pkgs = append(pkgs, p)
   366  			m[pkgname] = p
   367  		}
   368  		p.files = append(p.files, name)
   369  	}
   370  	return pkgs
   371  }
   372  
   373  type context struct {
   374  	GOOS       string
   375  	GOARCH     string
   376  	cgoEnabled bool
   377  	noOptEnv   bool
   378  }
   379  
   380  // shouldTest looks for build tags in a source file and returns
   381  // whether the file should be used according to the tags.
   382  func shouldTest(src string, goos, goarch string) (ok bool, whyNot string) {
   383  	if *runSkips {
   384  		return true, ""
   385  	}
   386  	for _, line := range strings.Split(src, "\n") {
   387  		if strings.HasPrefix(line, "package ") {
   388  			break
   389  		}
   390  
   391  		if expr, err := constraint.Parse(line); err == nil {
   392  			gcFlags := os.Getenv("GO_GCFLAGS")
   393  			ctxt := &context{
   394  				GOOS:       goos,
   395  				GOARCH:     goarch,
   396  				cgoEnabled: cgoEnabled,
   397  				noOptEnv:   strings.Contains(gcFlags, "-N") || strings.Contains(gcFlags, "-l"),
   398  			}
   399  
   400  			if !expr.Eval(ctxt.match) {
   401  				return false, line
   402  			}
   403  		}
   404  	}
   405  	return true, ""
   406  }
   407  
   408  func (ctxt *context) match(name string) bool {
   409  	if name == "" {
   410  		return false
   411  	}
   412  
   413  	// Tags must be letters, digits, underscores or dots.
   414  	// Unlike in Go identifiers, all digits are fine (e.g., "386").
   415  	for _, c := range name {
   416  		if !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != '_' && c != '.' {
   417  			return false
   418  		}
   419  	}
   420  
   421  	if slices.Contains(build.Default.ReleaseTags, name) {
   422  		return true
   423  	}
   424  
   425  	if strings.HasPrefix(name, "goexperiment.") {
   426  		return slices.Contains(build.Default.ToolTags, name)
   427  	}
   428  
   429  	if name == "cgo" && ctxt.cgoEnabled {
   430  		return true
   431  	}
   432  
   433  	if name == ctxt.GOOS || name == ctxt.GOARCH || name == "gc" {
   434  		return true
   435  	}
   436  
   437  	if ctxt.noOptEnv && name == "gcflags_noopt" {
   438  		return true
   439  	}
   440  
   441  	if name == "test_run" {
   442  		return true
   443  	}
   444  
   445  	return false
   446  }
   447  
   448  // goGcflags returns the -gcflags argument to use with go build / go run.
   449  // This must match the flags used for building the standard library,
   450  // or else the commands will rebuild any needed packages (like runtime)
   451  // over and over.
   452  func (test) goGcflags() string {
   453  	return "-gcflags=all=" + os.Getenv("GO_GCFLAGS")
   454  }
   455  
   456  func (test) goGcflagsIsEmpty() bool {
   457  	return "" == os.Getenv("GO_GCFLAGS")
   458  }
   459  
   460  var errTimeout = errors.New("command exceeded time limit")
   461  
   462  // run runs the test case.
   463  //
   464  // When there is a problem, run uses t.Fatal to signify that it's an unskippable
   465  // infrastructure error (such as failing to read an input file or the test recipe
   466  // being malformed), or it returns a non-nil error to signify a test case error.
   467  //
   468  // t.Error isn't used here to give the caller the opportunity to decide whether
   469  // the test case failing is expected before promoting it to a real test failure.
   470  // See expectFail and -f flag.
   471  func (t test) run() error {
   472  	srcBytes, err := os.ReadFile(filepath.Join(t.gorootTestDir, t.goFileName()))
   473  	if err != nil {
   474  		t.Fatal("reading test case .go file:", err)
   475  	} else if bytes.HasPrefix(srcBytes, []byte{'\n'}) {
   476  		t.Fatal(".go file source starts with a newline")
   477  	}
   478  	src := string(srcBytes)
   479  
   480  	// Execution recipe is contained in a comment in
   481  	// the first non-empty line that is not a build constraint.
   482  	var action string
   483  	for actionSrc := src; action == "" && actionSrc != ""; {
   484  		var line string
   485  		line, actionSrc, _ = strings.Cut(actionSrc, "\n")
   486  		if constraint.IsGoBuild(line) || constraint.IsPlusBuild(line) {
   487  			continue
   488  		}
   489  		action = strings.TrimSpace(strings.TrimPrefix(line, "//"))
   490  	}
   491  	if action == "" {
   492  		t.Fatalf("execution recipe not found in GOROOT/test/%s", t.goFileName())
   493  	}
   494  
   495  	// Check for build constraints only up to the actual code.
   496  	header, _, ok := strings.Cut(src, "\npackage")
   497  	if !ok {
   498  		header = action // some files are intentionally malformed
   499  	}
   500  	if ok, why := shouldTest(header, goos, goarch); !ok {
   501  		t.Skip(why)
   502  	}
   503  
   504  	var args, flags, runenv []string
   505  	var tim int
   506  	wantError := false
   507  	wantAuto := false
   508  	singlefilepkgs := false
   509  	f, err := splitQuoted(action)
   510  	if err != nil {
   511  		t.Fatal("invalid test recipe:", err)
   512  	}
   513  	if len(f) > 0 {
   514  		action = f[0]
   515  		args = f[1:]
   516  	}
   517  
   518  	// TODO: Clean up/simplify this switch statement.
   519  	switch action {
   520  	case "compile", "compiledir", "build", "builddir", "buildrundir", "run", "buildrun", "runoutput", "rundir", "runindir", "asmcheck":
   521  		// nothing to do
   522  	case "errorcheckandrundir":
   523  		wantError = false // should be no error if also will run
   524  	case "errorcheckwithauto":
   525  		action = "errorcheck"
   526  		wantAuto = true
   527  		wantError = true
   528  	case "errorcheck", "errorcheckdir", "errorcheckoutput":
   529  		wantError = true
   530  	case "skip":
   531  		if *runSkips {
   532  			break
   533  		}
   534  		t.Skip("skip")
   535  	default:
   536  		t.Fatalf("unknown pattern: %q", action)
   537  	}
   538  
   539  	goexp := goExperiment
   540  
   541  	// collect flags
   542  	for len(args) > 0 && strings.HasPrefix(args[0], "-") {
   543  		switch args[0] {
   544  		case "-1":
   545  			wantError = true
   546  		case "-0":
   547  			wantError = false
   548  		case "-s":
   549  			singlefilepkgs = true
   550  		case "-t": // timeout in seconds
   551  			args = args[1:]
   552  			var err error
   553  			tim, err = strconv.Atoi(args[0])
   554  			if err != nil {
   555  				t.Fatalf("need number of seconds for -t timeout, got %s instead", args[0])
   556  			}
   557  			if s := os.Getenv("GO_TEST_TIMEOUT_SCALE"); s != "" {
   558  				timeoutScale, err := strconv.Atoi(s)
   559  				if err != nil {
   560  					t.Fatalf("failed to parse $GO_TEST_TIMEOUT_SCALE = %q as integer: %v", s, err)
   561  				}
   562  				tim *= timeoutScale
   563  			}
   564  		case "-goexperiment": // set GOEXPERIMENT environment
   565  			args = args[1:]
   566  			if goexp != "" {
   567  				goexp += ","
   568  			}
   569  			goexp += args[0]
   570  			runenv = append(runenv, "GOEXPERIMENT="+goexp)
   571  
   572  		default:
   573  			flags = append(flags, args[0])
   574  		}
   575  		args = args[1:]
   576  	}
   577  	if action == "errorcheck" {
   578  		found := false
   579  		for i, f := range flags {
   580  			if strings.HasPrefix(f, "-d=") {
   581  				flags[i] = f + ",ssa/check/on"
   582  				found = true
   583  				break
   584  			}
   585  		}
   586  		if !found {
   587  			flags = append(flags, "-d=ssa/check/on")
   588  		}
   589  	}
   590  
   591  	tempDir := t.TempDir()
   592  	err = os.Mkdir(filepath.Join(tempDir, "test"), 0755)
   593  	if err != nil {
   594  		t.Fatal(err)
   595  	}
   596  
   597  	err = os.WriteFile(filepath.Join(tempDir, t.goFile), srcBytes, 0644)
   598  	if err != nil {
   599  		t.Fatal(err)
   600  	}
   601  
   602  	var (
   603  		runInDir        = tempDir
   604  		tempDirIsGOPATH = false
   605  	)
   606  	runcmd := func(args ...string) ([]byte, error) {
   607  		cmd := exec.Command(args[0], args[1:]...)
   608  		var buf bytes.Buffer
   609  		cmd.Stdout = &buf
   610  		cmd.Stderr = &buf
   611  		cmd.Env = append(os.Environ(), "GOENV=off", "GOFLAGS=")
   612  		if runInDir != "" {
   613  			cmd.Dir = runInDir
   614  			// Set PWD to match Dir to speed up os.Getwd in the child process.
   615  			cmd.Env = append(cmd.Env, "PWD="+cmd.Dir)
   616  		} else {
   617  			// Default to running in the GOROOT/test directory.
   618  			cmd.Dir = t.gorootTestDir
   619  			// Set PWD to match Dir to speed up os.Getwd in the child process.
   620  			cmd.Env = append(cmd.Env, "PWD="+cmd.Dir)
   621  		}
   622  		if tempDirIsGOPATH {
   623  			cmd.Env = append(cmd.Env, "GOPATH="+tempDir)
   624  		}
   625  		cmd.Env = append(cmd.Env, "STDLIB_IMPORTCFG="+stdlibImportcfgFile())
   626  		cmd.Env = append(cmd.Env, runenv...)
   627  
   628  		var err error
   629  
   630  		if tim != 0 {
   631  			err = cmd.Start()
   632  			// This command-timeout code adapted from cmd/go/test.go
   633  			// Note: the Go command uses a more sophisticated timeout
   634  			// strategy, first sending SIGQUIT (if appropriate for the
   635  			// OS in question) to try to trigger a stack trace, then
   636  			// finally much later SIGKILL. If timeouts prove to be a
   637  			// common problem here, it would be worth porting over
   638  			// that code as well. See https://do.dev/issue/50973
   639  			// for more discussion.
   640  			if err == nil {
   641  				tick := time.NewTimer(time.Duration(tim) * time.Second)
   642  				done := make(chan error)
   643  				go func() {
   644  					done <- cmd.Wait()
   645  				}()
   646  				select {
   647  				case err = <-done:
   648  					// ok
   649  				case <-tick.C:
   650  					cmd.Process.Signal(os.Interrupt)
   651  					time.Sleep(1 * time.Second)
   652  					cmd.Process.Kill()
   653  					<-done
   654  					err = errTimeout
   655  				}
   656  				tick.Stop()
   657  			}
   658  		} else {
   659  			err = cmd.Run()
   660  		}
   661  		if err != nil && err != errTimeout {
   662  			err = fmt.Errorf("%s\n%s", err, buf.Bytes())
   663  		}
   664  		return buf.Bytes(), err
   665  	}
   666  
   667  	importcfg := func(pkgs []*goDirPkg) string {
   668  		cfg := stdlibImportcfg()
   669  		for _, pkg := range pkgs {
   670  			pkgpath := path.Join("test", strings.TrimSuffix(pkg.files[0], ".go"))
   671  			cfg += "\npackagefile " + pkgpath + "=" + filepath.Join(tempDir, pkgpath+".a")
   672  		}
   673  		filename := filepath.Join(tempDir, "importcfg")
   674  		err := os.WriteFile(filename, []byte(cfg), 0644)
   675  		if err != nil {
   676  			t.Fatal(err)
   677  		}
   678  		return filename
   679  	}
   680  
   681  	long := filepath.Join(t.gorootTestDir, t.goFileName())
   682  	switch action {
   683  	default:
   684  		t.Fatalf("unimplemented action %q", action)
   685  		panic("unreachable")
   686  
   687  	case "asmcheck":
   688  		// Compile Go file and match the generated assembly
   689  		// against a set of regexps in comments.
   690  		ops := t.wantedAsmOpcodes(long)
   691  		self := runtime.GOOS + "/" + runtime.GOARCH
   692  		for _, env := range ops.Envs() {
   693  			// Only run checks relevant to the current GOOS/GOARCH,
   694  			// to avoid triggering a cross-compile of the runtime.
   695  			if string(env) != self && !strings.HasPrefix(string(env), self+"/") && !*allCodegen {
   696  				continue
   697  			}
   698  			// -S=2 forces outermost line numbers when disassembling inlined code.
   699  			cmdline := []string{"build", "-gcflags", "-S=2"}
   700  
   701  			// Append flags, but don't override -gcflags=-S=2; add to it instead.
   702  			for i := 0; i < len(flags); i++ {
   703  				flag := flags[i]
   704  				switch {
   705  				case strings.HasPrefix(flag, "-gcflags="):
   706  					cmdline[2] += " " + strings.TrimPrefix(flag, "-gcflags=")
   707  				case strings.HasPrefix(flag, "--gcflags="):
   708  					cmdline[2] += " " + strings.TrimPrefix(flag, "--gcflags=")
   709  				case flag == "-gcflags", flag == "--gcflags":
   710  					i++
   711  					if i < len(flags) {
   712  						cmdline[2] += " " + flags[i]
   713  					}
   714  				default:
   715  					cmdline = append(cmdline, flag)
   716  				}
   717  			}
   718  
   719  			cmdline = append(cmdline, long)
   720  			cmd := exec.Command(goTool, cmdline...)
   721  			cmd.Env = append(os.Environ(), env.Environ()...)
   722  			if len(flags) > 0 && flags[0] == "-race" {
   723  				cmd.Env = append(cmd.Env, "CGO_ENABLED=1")
   724  			}
   725  
   726  			var buf bytes.Buffer
   727  			cmd.Stdout, cmd.Stderr = &buf, &buf
   728  			if err := cmd.Run(); err != nil {
   729  				t.Log(env, "\n", cmd.Stderr)
   730  				return err
   731  			}
   732  
   733  			err := t.asmCheck(buf.String(), long, env, ops[env])
   734  			if err != nil {
   735  				return err
   736  			}
   737  		}
   738  		return nil
   739  
   740  	case "errorcheck":
   741  		// Compile Go file.
   742  		// Fail if wantError is true and compilation was successful and vice versa.
   743  		// Match errors produced by gc against errors in comments.
   744  		// TODO(gri) remove need for -C (disable printing of columns in error messages)
   745  		cmdline := []string{goTool, "tool", "compile", "-p=p", "-d=panic", "-C", "-e", "-importcfg=" + stdlibImportcfgFile(), "-o", "a.o"}
   746  		// No need to add -dynlink even if linkshared if we're just checking for errors...
   747  		cmdline = append(cmdline, flags...)
   748  		cmdline = append(cmdline, long)
   749  		out, err := runcmd(cmdline...)
   750  		if wantError {
   751  			if err == nil {
   752  				return fmt.Errorf("compilation succeeded unexpectedly\n%s", out)
   753  			}
   754  			if err == errTimeout {
   755  				return fmt.Errorf("compilation timed out")
   756  			}
   757  		} else {
   758  			if err != nil {
   759  				return err
   760  			}
   761  		}
   762  		if *updateErrors {
   763  			t.updateErrors(string(out), long)
   764  		}
   765  		return t.errorCheck(string(out), wantAuto, long, t.goFile)
   766  
   767  	case "compile":
   768  		// Compile Go file.
   769  		_, err := compileFile(runcmd, long, flags)
   770  		return err
   771  
   772  	case "compiledir":
   773  		// Compile all files in the directory as packages in lexicographic order.
   774  		longdir := filepath.Join(t.gorootTestDir, t.goDirName())
   775  		pkgs := goDirPackages(t.T, longdir, singlefilepkgs)
   776  		importcfgfile := importcfg(pkgs)
   777  
   778  		for _, pkg := range pkgs {
   779  			_, err := compileInDir(runcmd, longdir, flags, importcfgfile, pkg.name, pkg.files...)
   780  			if err != nil {
   781  				return err
   782  			}
   783  		}
   784  		return nil
   785  
   786  	case "errorcheckdir", "errorcheckandrundir":
   787  		flags = append(flags, "-d=panic")
   788  		// Compile and errorCheck all files in the directory as packages in lexicographic order.
   789  		// If errorcheckdir and wantError, compilation of the last package must fail.
   790  		// If errorcheckandrundir and wantError, compilation of the package prior the last must fail.
   791  		longdir := filepath.Join(t.gorootTestDir, t.goDirName())
   792  		pkgs := goDirPackages(t.T, longdir, singlefilepkgs)
   793  		errPkg := len(pkgs) - 1
   794  		if wantError && action == "errorcheckandrundir" {
   795  			// The last pkg should compiled successfully and will be run in next case.
   796  			// Preceding pkg must return an error from compileInDir.
   797  			errPkg--
   798  		}
   799  		importcfgfile := importcfg(pkgs)
   800  		for i, pkg := range pkgs {
   801  			out, err := compileInDir(runcmd, longdir, flags, importcfgfile, pkg.name, pkg.files...)
   802  			if i == errPkg {
   803  				if wantError && err == nil {
   804  					return fmt.Errorf("compilation succeeded unexpectedly\n%s", out)
   805  				} else if !wantError && err != nil {
   806  					return err
   807  				}
   808  			} else if err != nil {
   809  				return err
   810  			}
   811  			var fullshort []string
   812  			for _, name := range pkg.files {
   813  				fullshort = append(fullshort, filepath.Join(longdir, name), name)
   814  			}
   815  			err = t.errorCheck(string(out), wantAuto, fullshort...)
   816  			if err != nil {
   817  				return err
   818  			}
   819  		}
   820  		if action == "errorcheckdir" {
   821  			return nil
   822  		}
   823  		fallthrough
   824  
   825  	case "rundir":
   826  		// Compile all files in the directory as packages in lexicographic order.
   827  		// In case of errorcheckandrundir, ignore failed compilation of the package before the last.
   828  		// Link as if the last file is the main package, run it.
   829  		// Verify the expected output.
   830  		longdir := filepath.Join(t.gorootTestDir, t.goDirName())
   831  		pkgs := goDirPackages(t.T, longdir, singlefilepkgs)
   832  		// Split flags into gcflags and ldflags
   833  		ldflags := []string{}
   834  		for i, fl := range flags {
   835  			if fl == "-ldflags" {
   836  				ldflags = flags[i+1:]
   837  				flags = flags[0:i]
   838  				break
   839  			}
   840  		}
   841  
   842  		importcfgfile := importcfg(pkgs)
   843  
   844  		for i, pkg := range pkgs {
   845  			_, err := compileInDir(runcmd, longdir, flags, importcfgfile, pkg.name, pkg.files...)
   846  			// Allow this package compilation fail based on conditions below;
   847  			// its errors were checked in previous case.
   848  			if err != nil && !(wantError && action == "errorcheckandrundir" && i == len(pkgs)-2) {
   849  				return err
   850  			}
   851  
   852  			if i == len(pkgs)-1 {
   853  				err = linkFile(runcmd, pkg.files[0], importcfgfile, ldflags)
   854  				if err != nil {
   855  					return err
   856  				}
   857  				var cmd []string
   858  				cmd = append(cmd, findExecCmd()...)
   859  				cmd = append(cmd, filepath.Join(tempDir, "a.exe"))
   860  				cmd = append(cmd, args...)
   861  				out, err := runcmd(cmd...)
   862  				if err != nil {
   863  					return err
   864  				}
   865  				t.checkExpectedOutput(out)
   866  			}
   867  		}
   868  		return nil
   869  
   870  	case "runindir":
   871  		// Make a shallow copy of t.goDirName() in its own module and GOPATH, and
   872  		// run "go run ." in it. The module path (and hence import path prefix) of
   873  		// the copy is equal to the basename of the source directory.
   874  		//
   875  		// It's used when test a requires a full 'go build' in order to compile
   876  		// the sources, such as when importing multiple packages (issue29612.dir)
   877  		// or compiling a package containing assembly files (see issue15609.dir),
   878  		// but still needs to be run to verify the expected output.
   879  		tempDirIsGOPATH = true
   880  		srcDir := filepath.Join(t.gorootTestDir, t.goDirName())
   881  		modName := filepath.Base(srcDir)
   882  		gopathSrcDir := filepath.Join(tempDir, "src", modName)
   883  		runInDir = gopathSrcDir
   884  
   885  		if err := overlayDir(gopathSrcDir, srcDir); err != nil {
   886  			t.Fatal(err)
   887  		}
   888  
   889  		modFile := fmt.Sprintf("module %s\ngo 1.14\n", modName)
   890  		if err := os.WriteFile(filepath.Join(gopathSrcDir, "go.mod"), []byte(modFile), 0666); err != nil {
   891  			t.Fatal(err)
   892  		}
   893  
   894  		cmd := []string{goTool, "run", t.goGcflags()}
   895  		if *linkshared {
   896  			cmd = append(cmd, "-linkshared")
   897  		}
   898  		cmd = append(cmd, flags...)
   899  		cmd = append(cmd, ".")
   900  		out, err := runcmd(cmd...)
   901  		if err != nil {
   902  			return err
   903  		}
   904  		return t.checkExpectedOutput(out)
   905  
   906  	case "build":
   907  		// Build Go file.
   908  		cmd := []string{goTool, "build", t.goGcflags()}
   909  		cmd = append(cmd, flags...)
   910  		cmd = append(cmd, "-o", "a.exe", long)
   911  		_, err := runcmd(cmd...)
   912  		return err
   913  
   914  	case "builddir", "buildrundir":
   915  		// Build an executable from all the .go and .s files in a subdirectory.
   916  		// Run it and verify its output in the buildrundir case.
   917  		longdir := filepath.Join(t.gorootTestDir, t.goDirName())
   918  		files, err := os.ReadDir(longdir)
   919  		if err != nil {
   920  			t.Fatal(err)
   921  		}
   922  		var gos []string
   923  		var asms []string
   924  		for _, file := range files {
   925  			switch filepath.Ext(file.Name()) {
   926  			case ".go":
   927  				gos = append(gos, filepath.Join(longdir, file.Name()))
   928  			case ".s":
   929  				asms = append(asms, filepath.Join(longdir, file.Name()))
   930  			}
   931  
   932  		}
   933  		if len(asms) > 0 {
   934  			emptyHdrFile := filepath.Join(tempDir, "go_asm.h")
   935  			if err := os.WriteFile(emptyHdrFile, nil, 0666); err != nil {
   936  				t.Fatalf("write empty go_asm.h: %v", err)
   937  			}
   938  			cmd := []string{goTool, "tool", "asm", "-p=main", "-gensymabis", "-o", "symabis"}
   939  			cmd = append(cmd, asms...)
   940  			_, err = runcmd(cmd...)
   941  			if err != nil {
   942  				return err
   943  			}
   944  		}
   945  		var objs []string
   946  		cmd := []string{goTool, "tool", "compile", "-p=main", "-e", "-D", ".", "-importcfg=" + stdlibImportcfgFile(), "-o", "go.o"}
   947  		if len(asms) > 0 {
   948  			cmd = append(cmd, "-asmhdr", "go_asm.h", "-symabis", "symabis")
   949  		}
   950  		cmd = append(cmd, gos...)
   951  		_, err = runcmd(cmd...)
   952  		if err != nil {
   953  			return err
   954  		}
   955  		objs = append(objs, "go.o")
   956  		if len(asms) > 0 {
   957  			cmd = []string{goTool, "tool", "asm", "-p=main", "-e", "-I", ".", "-o", "asm.o"}
   958  			cmd = append(cmd, asms...)
   959  			_, err = runcmd(cmd...)
   960  			if err != nil {
   961  				return err
   962  			}
   963  			objs = append(objs, "asm.o")
   964  		}
   965  		cmd = []string{goTool, "tool", "pack", "c", "all.a"}
   966  		cmd = append(cmd, objs...)
   967  		_, err = runcmd(cmd...)
   968  		if err != nil {
   969  			return err
   970  		}
   971  		cmd = []string{goTool, "tool", "link", "-importcfg=" + stdlibImportcfgFile(), "-o", "a.exe", "all.a"}
   972  		_, err = runcmd(cmd...)
   973  		if err != nil {
   974  			return err
   975  		}
   976  
   977  		if action == "builddir" {
   978  			return nil
   979  		}
   980  		cmd = append(findExecCmd(), filepath.Join(tempDir, "a.exe"))
   981  		out, err := runcmd(cmd...)
   982  		if err != nil {
   983  			return err
   984  		}
   985  		return t.checkExpectedOutput(out)
   986  
   987  	case "buildrun":
   988  		// Build an executable from Go file, then run it, verify its output.
   989  		// Useful for timeout tests where failure mode is infinite loop.
   990  		// TODO: not supported on NaCl
   991  		cmd := []string{goTool, "build", t.goGcflags(), "-o", "a.exe"}
   992  		if *linkshared {
   993  			cmd = append(cmd, "-linkshared")
   994  		}
   995  		longDirGoFile := filepath.Join(filepath.Join(t.gorootTestDir, t.dir), t.goFile)
   996  		cmd = append(cmd, flags...)
   997  		cmd = append(cmd, longDirGoFile)
   998  		_, err := runcmd(cmd...)
   999  		if err != nil {
  1000  			return err
  1001  		}
  1002  		cmd = []string{"./a.exe"}
  1003  		out, err := runcmd(append(cmd, args...)...)
  1004  		if err != nil {
  1005  			return err
  1006  		}
  1007  
  1008  		return t.checkExpectedOutput(out)
  1009  
  1010  	case "run":
  1011  		// Run Go file if no special go command flags are provided;
  1012  		// otherwise build an executable and run it.
  1013  		// Verify the output.
  1014  		runInDir = ""
  1015  		var out []byte
  1016  		var err error
  1017  		if len(flags)+len(args) == 0 && t.goGcflagsIsEmpty() && !*linkshared && goarch == runtime.GOARCH && goos == runtime.GOOS && goexp == goExperiment {
  1018  			// If we're not using special go command flags,
  1019  			// skip all the go command machinery.
  1020  			// This avoids any time the go command would
  1021  			// spend checking whether, for example, the installed
  1022  			// package runtime is up to date.
  1023  			// Because we run lots of trivial test programs,
  1024  			// the time adds up.
  1025  			pkg := filepath.Join(tempDir, "pkg.a")
  1026  			if _, err := runcmd(goTool, "tool", "compile", "-p=main", "-importcfg="+stdlibImportcfgFile(), "-o", pkg, t.goFileName()); err != nil {
  1027  				return err
  1028  			}
  1029  			exe := filepath.Join(tempDir, "test.exe")
  1030  			cmd := []string{goTool, "tool", "link", "-s", "-w", "-importcfg=" + stdlibImportcfgFile()}
  1031  			cmd = append(cmd, "-o", exe, pkg)
  1032  			if _, err := runcmd(cmd...); err != nil {
  1033  				return err
  1034  			}
  1035  			out, err = runcmd(append([]string{exe}, args...)...)
  1036  		} else {
  1037  			cmd := []string{goTool, "run", t.goGcflags()}
  1038  			if *linkshared {
  1039  				cmd = append(cmd, "-linkshared")
  1040  			}
  1041  			cmd = append(cmd, flags...)
  1042  			cmd = append(cmd, t.goFileName())
  1043  			out, err = runcmd(append(cmd, args...)...)
  1044  		}
  1045  		if err != nil {
  1046  			return err
  1047  		}
  1048  		return t.checkExpectedOutput(out)
  1049  
  1050  	case "runoutput":
  1051  		// Run Go file and write its output into temporary Go file.
  1052  		// Run generated Go file and verify its output.
  1053  		t.runoutputGate <- true
  1054  		defer func() {
  1055  			<-t.runoutputGate
  1056  		}()
  1057  		runInDir = ""
  1058  		cmd := []string{goTool, "run", t.goGcflags()}
  1059  		if *linkshared {
  1060  			cmd = append(cmd, "-linkshared")
  1061  		}
  1062  		cmd = append(cmd, t.goFileName())
  1063  		out, err := runcmd(append(cmd, args...)...)
  1064  		if err != nil {
  1065  			return err
  1066  		}
  1067  		tfile := filepath.Join(tempDir, "tmp__.go")
  1068  		if err := os.WriteFile(tfile, out, 0666); err != nil {
  1069  			t.Fatalf("write tempfile: %v", err)
  1070  		}
  1071  		cmd = []string{goTool, "run", t.goGcflags()}
  1072  		if *linkshared {
  1073  			cmd = append(cmd, "-linkshared")
  1074  		}
  1075  		cmd = append(cmd, tfile)
  1076  		out, err = runcmd(cmd...)
  1077  		if err != nil {
  1078  			return err
  1079  		}
  1080  		return t.checkExpectedOutput(out)
  1081  
  1082  	case "errorcheckoutput":
  1083  		// Run Go file and write its output into temporary Go file.
  1084  		// Compile and errorCheck generated Go file.
  1085  		runInDir = ""
  1086  		cmd := []string{goTool, "run", t.goGcflags()}
  1087  		if *linkshared {
  1088  			cmd = append(cmd, "-linkshared")
  1089  		}
  1090  		cmd = append(cmd, t.goFileName())
  1091  		out, err := runcmd(append(cmd, args...)...)
  1092  		if err != nil {
  1093  			return err
  1094  		}
  1095  		tfile := filepath.Join(tempDir, "tmp__.go")
  1096  		err = os.WriteFile(tfile, out, 0666)
  1097  		if err != nil {
  1098  			t.Fatalf("write tempfile: %v", err)
  1099  		}
  1100  		cmdline := []string{goTool, "tool", "compile", "-importcfg=" + stdlibImportcfgFile(), "-p=p", "-d=panic", "-e", "-o", "a.o"}
  1101  		cmdline = append(cmdline, flags...)
  1102  		cmdline = append(cmdline, tfile)
  1103  		out, err = runcmd(cmdline...)
  1104  		if wantError {
  1105  			if err == nil {
  1106  				return fmt.Errorf("compilation succeeded unexpectedly\n%s", out)
  1107  			}
  1108  		} else {
  1109  			if err != nil {
  1110  				return err
  1111  			}
  1112  		}
  1113  		return t.errorCheck(string(out), false, tfile, "tmp__.go")
  1114  	}
  1115  }
  1116  
  1117  var execCmdOnce sync.Once
  1118  var execCmd []string
  1119  
  1120  func findExecCmd() []string {
  1121  	execCmdOnce.Do(func() {
  1122  		if goos == runtime.GOOS && goarch == runtime.GOARCH {
  1123  			// Do nothing.
  1124  		} else if path, err := exec.LookPath(fmt.Sprintf("go_%s_%s_exec", goos, goarch)); err == nil {
  1125  			execCmd = []string{path}
  1126  		}
  1127  	})
  1128  	return execCmd
  1129  }
  1130  
  1131  // checkExpectedOutput compares the output from compiling and/or running with the contents
  1132  // of the corresponding reference output file, if any (replace ".go" with ".out").
  1133  // If they don't match, fail with an informative message.
  1134  func (t test) checkExpectedOutput(gotBytes []byte) error {
  1135  	got := string(gotBytes)
  1136  	filename := filepath.Join(t.dir, t.goFile)
  1137  	filename = filename[:len(filename)-len(".go")]
  1138  	filename += ".out"
  1139  	b, err := os.ReadFile(filepath.Join(t.gorootTestDir, filename))
  1140  	if errors.Is(err, fs.ErrNotExist) {
  1141  		// File is allowed to be missing, in which case output should be empty.
  1142  		b = nil
  1143  	} else if err != nil {
  1144  		return err
  1145  	}
  1146  	got = strings.Replace(got, "\r\n", "\n", -1)
  1147  	if got != string(b) {
  1148  		if err == nil {
  1149  			return fmt.Errorf("output does not match expected in %s. Instead saw\n%s", filename, got)
  1150  		} else {
  1151  			return fmt.Errorf("output should be empty when (optional) expected-output file %s is not present. Instead saw\n%s", filename, got)
  1152  		}
  1153  	}
  1154  	return nil
  1155  }
  1156  
  1157  func splitOutput(out string, wantAuto bool) []string {
  1158  	// gc error messages continue onto additional lines with leading tabs.
  1159  	// Split the output at the beginning of each line that doesn't begin with a tab.
  1160  	// <autogenerated> lines are impossible to match so those are filtered out.
  1161  	var res []string
  1162  	for _, line := range strings.Split(out, "\n") {
  1163  		if strings.HasSuffix(line, "\r") { // remove '\r', output by compiler on windows
  1164  			line = line[:len(line)-1]
  1165  		}
  1166  		if strings.HasPrefix(line, "\t") {
  1167  			res[len(res)-1] += "\n" + line
  1168  		} else if strings.HasPrefix(line, "go tool") || strings.HasPrefix(line, "#") || !wantAuto && strings.HasPrefix(line, "<autogenerated>") {
  1169  			continue
  1170  		} else if strings.TrimSpace(line) != "" {
  1171  			res = append(res, line)
  1172  		}
  1173  	}
  1174  	return res
  1175  }
  1176  
  1177  // errorCheck matches errors in outStr against comments in source files.
  1178  // For each line of the source files which should generate an error,
  1179  // there should be a comment of the form // ERROR "regexp".
  1180  // If outStr has an error for a line which has no such comment,
  1181  // this function will report an error.
  1182  // Likewise if outStr does not have an error for a line which has a comment,
  1183  // or if the error message does not match the <regexp>.
  1184  // The <regexp> syntax is Perl but it's best to stick to egrep.
  1185  //
  1186  // Sources files are supplied as fullshort slice.
  1187  // It consists of pairs: full path to source file and its base name.
  1188  func (t test) errorCheck(outStr string, wantAuto bool, fullshort ...string) (err error) {
  1189  	defer func() {
  1190  		if testing.Verbose() && err != nil {
  1191  			t.Logf("gc output:\n%s", outStr)
  1192  		}
  1193  	}()
  1194  	var errs []error
  1195  	out := splitOutput(outStr, wantAuto)
  1196  
  1197  	// Cut directory name.
  1198  	for i := range out {
  1199  		for j := 0; j < len(fullshort); j += 2 {
  1200  			full, short := fullshort[j], fullshort[j+1]
  1201  			out[i] = strings.Replace(out[i], full, short, -1)
  1202  		}
  1203  	}
  1204  
  1205  	var want []wantedError
  1206  	for j := 0; j < len(fullshort); j += 2 {
  1207  		full, short := fullshort[j], fullshort[j+1]
  1208  		want = append(want, t.wantedErrors(full, short)...)
  1209  	}
  1210  
  1211  	for _, we := range want {
  1212  		var errmsgs []string
  1213  		if we.auto {
  1214  			errmsgs, out = partitionStrings("<autogenerated>", out)
  1215  		} else {
  1216  			errmsgs, out = partitionStrings(we.prefix, out)
  1217  		}
  1218  		if len(errmsgs) == 0 {
  1219  			errs = append(errs, fmt.Errorf("%s:%d: missing error %q", we.file, we.lineNum, we.reStr))
  1220  			continue
  1221  		}
  1222  		matched := false
  1223  		n := len(out)
  1224  		for _, errmsg := range errmsgs {
  1225  			// Assume errmsg says "file:line: foo".
  1226  			// Cut leading "file:line: " to avoid accidental matching of file name instead of message.
  1227  			text := errmsg
  1228  			if _, suffix, ok := strings.Cut(text, " "); ok {
  1229  				text = suffix
  1230  			}
  1231  			if we.re.MatchString(text) {
  1232  				matched = true
  1233  			} else {
  1234  				out = append(out, errmsg)
  1235  			}
  1236  		}
  1237  		if !matched {
  1238  			errs = append(errs, fmt.Errorf("%s:%d: no match for %#q in:\n\t%s", we.file, we.lineNum, we.reStr, strings.Join(out[n:], "\n\t")))
  1239  			continue
  1240  		}
  1241  	}
  1242  
  1243  	if len(out) > 0 {
  1244  		errs = append(errs, fmt.Errorf("Unmatched Errors:"))
  1245  		for _, errLine := range out {
  1246  			errs = append(errs, fmt.Errorf("%s", errLine))
  1247  		}
  1248  	}
  1249  
  1250  	if len(errs) == 0 {
  1251  		return nil
  1252  	}
  1253  	if len(errs) == 1 {
  1254  		return errs[0]
  1255  	}
  1256  	var buf bytes.Buffer
  1257  	fmt.Fprintf(&buf, "\n")
  1258  	for _, err := range errs {
  1259  		fmt.Fprintf(&buf, "%s\n", err.Error())
  1260  	}
  1261  	return errors.New(buf.String())
  1262  }
  1263  
  1264  func (test) updateErrors(out, file string) {
  1265  	base := path.Base(file)
  1266  	// Read in source file.
  1267  	src, err := os.ReadFile(file)
  1268  	if err != nil {
  1269  		fmt.Fprintln(os.Stderr, err)
  1270  		return
  1271  	}
  1272  	lines := strings.Split(string(src), "\n")
  1273  	// Remove old errors.
  1274  	for i := range lines {
  1275  		lines[i], _, _ = strings.Cut(lines[i], " // ERROR ")
  1276  	}
  1277  	// Parse new errors.
  1278  	errors := make(map[int]map[string]bool)
  1279  	tmpRe := regexp.MustCompile(`autotmp_\d+`)
  1280  	for _, errStr := range splitOutput(out, false) {
  1281  		errFile, rest, ok := strings.Cut(errStr, ":")
  1282  		if !ok || errFile != file {
  1283  			continue
  1284  		}
  1285  		lineStr, msg, ok := strings.Cut(rest, ":")
  1286  		if !ok {
  1287  			continue
  1288  		}
  1289  		line, err := strconv.Atoi(lineStr)
  1290  		line--
  1291  		if err != nil || line < 0 || line >= len(lines) {
  1292  			continue
  1293  		}
  1294  		msg = strings.Replace(msg, file, base, -1) // normalize file mentions in error itself
  1295  		msg = strings.TrimLeft(msg, " \t")
  1296  		for _, r := range []string{`\`, `*`, `+`, `?`, `[`, `]`, `(`, `)`} {
  1297  			msg = strings.Replace(msg, r, `\`+r, -1)
  1298  		}
  1299  		msg = strings.Replace(msg, `"`, `.`, -1)
  1300  		msg = tmpRe.ReplaceAllLiteralString(msg, `autotmp_[0-9]+`)
  1301  		if errors[line] == nil {
  1302  			errors[line] = make(map[string]bool)
  1303  		}
  1304  		errors[line][msg] = true
  1305  	}
  1306  	// Add new errors.
  1307  	for line, errs := range errors {
  1308  		var sorted []string
  1309  		for e := range errs {
  1310  			sorted = append(sorted, e)
  1311  		}
  1312  		sort.Strings(sorted)
  1313  		lines[line] += " // ERROR"
  1314  		for _, e := range sorted {
  1315  			lines[line] += fmt.Sprintf(` "%s$"`, e)
  1316  		}
  1317  	}
  1318  	// Write new file.
  1319  	err = os.WriteFile(file, []byte(strings.Join(lines, "\n")), 0640)
  1320  	if err != nil {
  1321  		fmt.Fprintln(os.Stderr, err)
  1322  		return
  1323  	}
  1324  	// Polish.
  1325  	exec.Command(goTool, "fmt", file).CombinedOutput()
  1326  }
  1327  
  1328  // matchPrefix reports whether s is of the form ^(.*/)?prefix(:|[),
  1329  // That is, it needs the file name prefix followed by a : or a [,
  1330  // and possibly preceded by a directory name.
  1331  func matchPrefix(s, prefix string) bool {
  1332  	i := strings.Index(s, ":")
  1333  	if i < 0 {
  1334  		return false
  1335  	}
  1336  	j := strings.LastIndex(s[:i], "/")
  1337  	s = s[j+1:]
  1338  	if len(s) <= len(prefix) || s[:len(prefix)] != prefix {
  1339  		return false
  1340  	}
  1341  	switch s[len(prefix)] {
  1342  	case '[', ':':
  1343  		return true
  1344  	}
  1345  	return false
  1346  }
  1347  
  1348  func partitionStrings(prefix string, strs []string) (matched, unmatched []string) {
  1349  	for _, s := range strs {
  1350  		if matchPrefix(s, prefix) {
  1351  			matched = append(matched, s)
  1352  		} else {
  1353  			unmatched = append(unmatched, s)
  1354  		}
  1355  	}
  1356  	return
  1357  }
  1358  
  1359  type wantedError struct {
  1360  	reStr   string
  1361  	re      *regexp.Regexp
  1362  	lineNum int
  1363  	auto    bool // match <autogenerated> line
  1364  	file    string
  1365  	prefix  string
  1366  }
  1367  
  1368  var (
  1369  	errRx       = regexp.MustCompile(`// (?:GC_)?ERROR (.*)`)
  1370  	errAutoRx   = regexp.MustCompile(`// (?:GC_)?ERRORAUTO (.*)`)
  1371  	errQuotesRx = regexp.MustCompile(`"([^"]*)"`)
  1372  	lineRx      = regexp.MustCompile(`LINE(([+-])(\d+))?`)
  1373  )
  1374  
  1375  func (t test) wantedErrors(file, short string) (errs []wantedError) {
  1376  	cache := make(map[string]*regexp.Regexp)
  1377  
  1378  	src, _ := os.ReadFile(file)
  1379  	for i, line := range strings.Split(string(src), "\n") {
  1380  		lineNum := i + 1
  1381  		if strings.Contains(line, "////") {
  1382  			// double comment disables ERROR
  1383  			continue
  1384  		}
  1385  		var auto bool
  1386  		m := errAutoRx.FindStringSubmatch(line)
  1387  		if m != nil {
  1388  			auto = true
  1389  		} else {
  1390  			m = errRx.FindStringSubmatch(line)
  1391  		}
  1392  		if m == nil {
  1393  			continue
  1394  		}
  1395  		all := m[1]
  1396  		mm := errQuotesRx.FindAllStringSubmatch(all, -1)
  1397  		if mm == nil {
  1398  			t.Fatalf("%s:%d: invalid errchk line: %s", t.goFileName(), lineNum, line)
  1399  		}
  1400  		for _, m := range mm {
  1401  			rx := lineRx.ReplaceAllStringFunc(m[1], func(m string) string {
  1402  				n := lineNum
  1403  				if strings.HasPrefix(m, "LINE+") {
  1404  					delta, _ := strconv.Atoi(m[5:])
  1405  					n += delta
  1406  				} else if strings.HasPrefix(m, "LINE-") {
  1407  					delta, _ := strconv.Atoi(m[5:])
  1408  					n -= delta
  1409  				}
  1410  				return fmt.Sprintf("%s:%d", short, n)
  1411  			})
  1412  			re := cache[rx]
  1413  			if re == nil {
  1414  				var err error
  1415  				re, err = regexp.Compile(rx)
  1416  				if err != nil {
  1417  					t.Fatalf("%s:%d: invalid regexp \"%s\" in ERROR line: %v", t.goFileName(), lineNum, rx, err)
  1418  				}
  1419  				cache[rx] = re
  1420  			}
  1421  			prefix := fmt.Sprintf("%s:%d", short, lineNum)
  1422  			errs = append(errs, wantedError{
  1423  				reStr:   rx,
  1424  				re:      re,
  1425  				prefix:  prefix,
  1426  				auto:    auto,
  1427  				lineNum: lineNum,
  1428  				file:    short,
  1429  			})
  1430  		}
  1431  	}
  1432  
  1433  	return
  1434  }
  1435  
  1436  const (
  1437  	// Regexp to match a single opcode check: optionally begin with "-" (to indicate
  1438  	// a negative check), followed by a string literal enclosed in "" or ``. For "",
  1439  	// backslashes must be handled.
  1440  	reMatchCheck = `-?(?:\x60[^\x60]*\x60|"(?:[^"\\]|\\.)*")`
  1441  )
  1442  
  1443  var (
  1444  	// Regexp to split a line in code and comment, trimming spaces
  1445  	rxAsmComment = regexp.MustCompile(`^\s*(.*?)\s*(?://\s*(.+)\s*)?$`)
  1446  
  1447  	// Regexp to extract an architecture check: architecture name (or triplet),
  1448  	// followed by semi-colon, followed by a comma-separated list of opcode checks.
  1449  	// Extraneous spaces are ignored.
  1450  	rxAsmPlatform = regexp.MustCompile(`(\w+)(/\w+)?(/\w*)?\s*:\s*(` + reMatchCheck + `(?:\s*,\s*` + reMatchCheck + `)*)`)
  1451  
  1452  	// Regexp to extract a single opcoded check
  1453  	rxAsmCheck = regexp.MustCompile(reMatchCheck)
  1454  
  1455  	// List of all architecture variants. Key is the GOARCH architecture,
  1456  	// value[0] is the variant-changing environment variable, and values[1:]
  1457  	// are the supported variants.
  1458  	archVariants = map[string][]string{
  1459  		"386":     {"GO386", "sse2", "softfloat"},
  1460  		"amd64":   {"GOAMD64", "v1", "v2", "v3", "v4"},
  1461  		"arm":     {"GOARM", "5", "6", "7", "7,softfloat"},
  1462  		"arm64":   {},
  1463  		"loong64": {},
  1464  		"mips":    {"GOMIPS", "hardfloat", "softfloat"},
  1465  		"mips64":  {"GOMIPS64", "hardfloat", "softfloat"},
  1466  		"ppc64":   {"GOPPC64", "power8", "power9", "power10"},
  1467  		"ppc64le": {"GOPPC64", "power8", "power9", "power10"},
  1468  		"ppc64x":  {}, // A pseudo-arch representing both ppc64 and ppc64le
  1469  		"s390x":   {},
  1470  		"wasm":    {},
  1471  		"riscv64": {},
  1472  	}
  1473  )
  1474  
  1475  // wantedAsmOpcode is a single asmcheck check
  1476  type wantedAsmOpcode struct {
  1477  	fileline string         // original source file/line (eg: "/path/foo.go:45")
  1478  	line     int            // original source line
  1479  	opcode   *regexp.Regexp // opcode check to be performed on assembly output
  1480  	negative bool           // true if the check is supposed to fail rather than pass
  1481  	found    bool           // true if the opcode check matched at least one in the output
  1482  }
  1483  
  1484  // A build environment triplet separated by slashes (eg: linux/386/sse2).
  1485  // The third field can be empty if the arch does not support variants (eg: "plan9/amd64/")
  1486  type buildEnv string
  1487  
  1488  // Environ returns the environment it represents in cmd.Environ() "key=val" format
  1489  // For instance, "linux/386/sse2".Environ() returns {"GOOS=linux", "GOARCH=386", "GO386=sse2"}
  1490  func (b buildEnv) Environ() []string {
  1491  	fields := strings.Split(string(b), "/")
  1492  	if len(fields) != 3 {
  1493  		panic("invalid buildEnv string: " + string(b))
  1494  	}
  1495  	env := []string{"GOOS=" + fields[0], "GOARCH=" + fields[1]}
  1496  	if fields[2] != "" {
  1497  		env = append(env, archVariants[fields[1]][0]+"="+fields[2])
  1498  	}
  1499  	return env
  1500  }
  1501  
  1502  // asmChecks represents all the asmcheck checks present in a test file
  1503  // The outer map key is the build triplet in which the checks must be performed.
  1504  // The inner map key represent the source file line ("filename.go:1234") at which the
  1505  // checks must be performed.
  1506  type asmChecks map[buildEnv]map[string][]wantedAsmOpcode
  1507  
  1508  // Envs returns all the buildEnv in which at least one check is present
  1509  func (a asmChecks) Envs() []buildEnv {
  1510  	var envs []buildEnv
  1511  	for e := range a {
  1512  		envs = append(envs, e)
  1513  	}
  1514  	sort.Slice(envs, func(i, j int) bool {
  1515  		return string(envs[i]) < string(envs[j])
  1516  	})
  1517  	return envs
  1518  }
  1519  
  1520  func (t test) wantedAsmOpcodes(fn string) asmChecks {
  1521  	ops := make(asmChecks)
  1522  
  1523  	comment := ""
  1524  	src, err := os.ReadFile(fn)
  1525  	if err != nil {
  1526  		t.Fatal(err)
  1527  	}
  1528  	for i, line := range strings.Split(string(src), "\n") {
  1529  		matches := rxAsmComment.FindStringSubmatch(line)
  1530  		code, cmt := matches[1], matches[2]
  1531  
  1532  		// Keep comments pending in the comment variable until
  1533  		// we find a line that contains some code.
  1534  		comment += " " + cmt
  1535  		if code == "" {
  1536  			continue
  1537  		}
  1538  
  1539  		// Parse and extract any architecture check from comments,
  1540  		// made by one architecture name and multiple checks.
  1541  		lnum := fn + ":" + strconv.Itoa(i+1)
  1542  		for _, ac := range rxAsmPlatform.FindAllStringSubmatch(comment, -1) {
  1543  			archspec, allchecks := ac[1:4], ac[4]
  1544  
  1545  			var arch, subarch, os string
  1546  			switch {
  1547  			case archspec[2] != "": // 3 components: "linux/386/sse2"
  1548  				os, arch, subarch = archspec[0], archspec[1][1:], archspec[2][1:]
  1549  			case archspec[1] != "": // 2 components: "386/sse2"
  1550  				os, arch, subarch = "linux", archspec[0], archspec[1][1:]
  1551  			default: // 1 component: "386"
  1552  				os, arch, subarch = "linux", archspec[0], ""
  1553  				if arch == "wasm" {
  1554  					os = "js"
  1555  				}
  1556  			}
  1557  
  1558  			if _, ok := archVariants[arch]; !ok {
  1559  				t.Fatalf("%s:%d: unsupported architecture: %v", t.goFileName(), i+1, arch)
  1560  			}
  1561  
  1562  			// Create the build environments corresponding the above specifiers
  1563  			envs := make([]buildEnv, 0, 4)
  1564  			arches := []string{arch}
  1565  			// ppc64x is a pseudo-arch, generate tests for both endian variants.
  1566  			if arch == "ppc64x" {
  1567  				arches = []string{"ppc64", "ppc64le"}
  1568  			}
  1569  			for _, arch := range arches {
  1570  				if subarch != "" {
  1571  					envs = append(envs, buildEnv(os+"/"+arch+"/"+subarch))
  1572  				} else {
  1573  					subarchs := archVariants[arch]
  1574  					if len(subarchs) == 0 {
  1575  						envs = append(envs, buildEnv(os+"/"+arch+"/"))
  1576  					} else {
  1577  						for _, sa := range archVariants[arch][1:] {
  1578  							envs = append(envs, buildEnv(os+"/"+arch+"/"+sa))
  1579  						}
  1580  					}
  1581  				}
  1582  			}
  1583  
  1584  			for _, m := range rxAsmCheck.FindAllString(allchecks, -1) {
  1585  				negative := false
  1586  				if m[0] == '-' {
  1587  					negative = true
  1588  					m = m[1:]
  1589  				}
  1590  
  1591  				rxsrc, err := strconv.Unquote(m)
  1592  				if err != nil {
  1593  					t.Fatalf("%s:%d: error unquoting string: %v", t.goFileName(), i+1, err)
  1594  				}
  1595  
  1596  				// Compile the checks as regular expressions. Notice that we
  1597  				// consider checks as matching from the beginning of the actual
  1598  				// assembler source (that is, what is left on each line of the
  1599  				// compile -S output after we strip file/line info) to avoid
  1600  				// trivial bugs such as "ADD" matching "FADD". This
  1601  				// doesn't remove genericity: it's still possible to write
  1602  				// something like "F?ADD", but we make common cases simpler
  1603  				// to get right.
  1604  				oprx, err := regexp.Compile("^" + rxsrc)
  1605  				if err != nil {
  1606  					t.Fatalf("%s:%d: %v", t.goFileName(), i+1, err)
  1607  				}
  1608  
  1609  				for _, env := range envs {
  1610  					if ops[env] == nil {
  1611  						ops[env] = make(map[string][]wantedAsmOpcode)
  1612  					}
  1613  					ops[env][lnum] = append(ops[env][lnum], wantedAsmOpcode{
  1614  						negative: negative,
  1615  						fileline: lnum,
  1616  						line:     i + 1,
  1617  						opcode:   oprx,
  1618  					})
  1619  				}
  1620  			}
  1621  		}
  1622  		comment = ""
  1623  	}
  1624  
  1625  	return ops
  1626  }
  1627  
  1628  func (t test) asmCheck(outStr string, fn string, env buildEnv, fullops map[string][]wantedAsmOpcode) error {
  1629  	// The assembly output contains the concatenated dump of multiple functions.
  1630  	// the first line of each function begins at column 0, while the rest is
  1631  	// indented by a tabulation. These data structures help us index the
  1632  	// output by function.
  1633  	functionMarkers := make([]int, 1)
  1634  	lineFuncMap := make(map[string]int)
  1635  
  1636  	lines := strings.Split(outStr, "\n")
  1637  	rxLine := regexp.MustCompile(fmt.Sprintf(`\((%s:\d+)\)\s+(.*)`, regexp.QuoteMeta(fn)))
  1638  
  1639  	for nl, line := range lines {
  1640  		// Check if this line begins a function
  1641  		if len(line) > 0 && line[0] != '\t' {
  1642  			functionMarkers = append(functionMarkers, nl)
  1643  		}
  1644  
  1645  		// Search if this line contains a assembly opcode (which is prefixed by the
  1646  		// original source file/line in parenthesis)
  1647  		matches := rxLine.FindStringSubmatch(line)
  1648  		if len(matches) == 0 {
  1649  			continue
  1650  		}
  1651  		srcFileLine, asm := matches[1], matches[2]
  1652  
  1653  		// Associate the original file/line information to the current
  1654  		// function in the output; it will be useful to dump it in case
  1655  		// of error.
  1656  		lineFuncMap[srcFileLine] = len(functionMarkers) - 1
  1657  
  1658  		// If there are opcode checks associated to this source file/line,
  1659  		// run the checks.
  1660  		if ops, found := fullops[srcFileLine]; found {
  1661  			for i := range ops {
  1662  				if !ops[i].found && ops[i].opcode.FindString(asm) != "" {
  1663  					ops[i].found = true
  1664  				}
  1665  			}
  1666  		}
  1667  	}
  1668  	functionMarkers = append(functionMarkers, len(lines))
  1669  
  1670  	var failed []wantedAsmOpcode
  1671  	for _, ops := range fullops {
  1672  		for _, o := range ops {
  1673  			// There's a failure if a negative match was found,
  1674  			// or a positive match was not found.
  1675  			if o.negative == o.found {
  1676  				failed = append(failed, o)
  1677  			}
  1678  		}
  1679  	}
  1680  	if len(failed) == 0 {
  1681  		return nil
  1682  	}
  1683  
  1684  	// At least one asmcheck failed; report them.
  1685  	lastFunction := -1
  1686  	var errbuf bytes.Buffer
  1687  	fmt.Fprintln(&errbuf)
  1688  	sort.Slice(failed, func(i, j int) bool { return failed[i].line < failed[j].line })
  1689  	for _, o := range failed {
  1690  		// Dump the function in which this opcode check was supposed to
  1691  		// pass but failed.
  1692  		funcIdx := lineFuncMap[o.fileline]
  1693  		if funcIdx != 0 && funcIdx != lastFunction {
  1694  			funcLines := lines[functionMarkers[funcIdx]:functionMarkers[funcIdx+1]]
  1695  			t.Log(strings.Join(funcLines, "\n"))
  1696  			lastFunction = funcIdx // avoid printing same function twice
  1697  		}
  1698  
  1699  		if o.negative {
  1700  			fmt.Fprintf(&errbuf, "%s:%d: %s: wrong opcode found: %q\n", t.goFileName(), o.line, env, o.opcode.String())
  1701  		} else {
  1702  			fmt.Fprintf(&errbuf, "%s:%d: %s: opcode not found: %q\n", t.goFileName(), o.line, env, o.opcode.String())
  1703  		}
  1704  	}
  1705  	return errors.New(errbuf.String())
  1706  }
  1707  
  1708  // defaultRunOutputLimit returns the number of runoutput tests that
  1709  // can be executed in parallel.
  1710  func defaultRunOutputLimit() int {
  1711  	const maxArmCPU = 2
  1712  
  1713  	cpu := runtime.NumCPU()
  1714  	if runtime.GOARCH == "arm" && cpu > maxArmCPU {
  1715  		cpu = maxArmCPU
  1716  	}
  1717  	return cpu
  1718  }
  1719  
  1720  func TestShouldTest(t *testing.T) {
  1721  	if *shard != 0 {
  1722  		t.Skipf("nothing to test on shard index %d", *shard)
  1723  	}
  1724  
  1725  	assert := func(ok bool, _ string) {
  1726  		t.Helper()
  1727  		if !ok {
  1728  			t.Error("test case failed")
  1729  		}
  1730  	}
  1731  	assertNot := func(ok bool, _ string) { t.Helper(); assert(!ok, "") }
  1732  
  1733  	// Simple tests.
  1734  	assert(shouldTest("// +build linux", "linux", "arm"))
  1735  	assert(shouldTest("// +build !windows", "linux", "arm"))
  1736  	assertNot(shouldTest("// +build !windows", "windows", "amd64"))
  1737  
  1738  	// A file with no build tags will always be tested.
  1739  	assert(shouldTest("// This is a test.", "os", "arch"))
  1740  
  1741  	// Build tags separated by a space are OR-ed together.
  1742  	assertNot(shouldTest("// +build arm 386", "linux", "amd64"))
  1743  
  1744  	// Build tags separated by a comma are AND-ed together.
  1745  	assertNot(shouldTest("// +build !windows,!plan9", "windows", "amd64"))
  1746  	assertNot(shouldTest("// +build !windows,!plan9", "plan9", "386"))
  1747  
  1748  	// Build tags on multiple lines are AND-ed together.
  1749  	assert(shouldTest("// +build !windows\n// +build amd64", "linux", "amd64"))
  1750  	assertNot(shouldTest("// +build !windows\n// +build amd64", "windows", "amd64"))
  1751  
  1752  	// Test that (!a OR !b) matches anything.
  1753  	assert(shouldTest("// +build !windows !plan9", "windows", "amd64"))
  1754  
  1755  	// Test that //go:build tag match.
  1756  	assert(shouldTest("//go:build go1.4", "linux", "amd64"))
  1757  }
  1758  
  1759  // overlayDir makes a minimal-overhead copy of srcRoot in which new files may be added.
  1760  func overlayDir(dstRoot, srcRoot string) error {
  1761  	dstRoot = filepath.Clean(dstRoot)
  1762  	if err := os.MkdirAll(dstRoot, 0777); err != nil {
  1763  		return err
  1764  	}
  1765  
  1766  	srcRoot, err := filepath.Abs(srcRoot)
  1767  	if err != nil {
  1768  		return err
  1769  	}
  1770  
  1771  	return filepath.WalkDir(srcRoot, func(srcPath string, d fs.DirEntry, err error) error {
  1772  		if err != nil || srcPath == srcRoot {
  1773  			return err
  1774  		}
  1775  
  1776  		suffix := strings.TrimPrefix(srcPath, srcRoot)
  1777  		for len(suffix) > 0 && suffix[0] == filepath.Separator {
  1778  			suffix = suffix[1:]
  1779  		}
  1780  		dstPath := filepath.Join(dstRoot, suffix)
  1781  
  1782  		var info fs.FileInfo
  1783  		if d.Type()&os.ModeSymlink != 0 {
  1784  			info, err = os.Stat(srcPath)
  1785  		} else {
  1786  			info, err = d.Info()
  1787  		}
  1788  		if err != nil {
  1789  			return err
  1790  		}
  1791  		perm := info.Mode() & os.ModePerm
  1792  
  1793  		// Always copy directories (don't symlink them).
  1794  		// If we add a file in the overlay, we don't want to add it in the original.
  1795  		if info.IsDir() {
  1796  			return os.MkdirAll(dstPath, perm|0200)
  1797  		}
  1798  
  1799  		// If the OS supports symlinks, use them instead of copying bytes.
  1800  		if err := os.Symlink(srcPath, dstPath); err == nil {
  1801  			return nil
  1802  		}
  1803  
  1804  		// Otherwise, copy the bytes.
  1805  		src, err := os.Open(srcPath)
  1806  		if err != nil {
  1807  			return err
  1808  		}
  1809  		defer src.Close()
  1810  
  1811  		dst, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm)
  1812  		if err != nil {
  1813  			return err
  1814  		}
  1815  
  1816  		_, err = io.Copy(dst, src)
  1817  		if closeErr := dst.Close(); err == nil {
  1818  			err = closeErr
  1819  		}
  1820  		return err
  1821  	})
  1822  }
  1823  
  1824  // The following sets of files are excluded from testing depending on configuration.
  1825  // The types2Failures(32Bit) files pass with the 1.17 compiler but don't pass with
  1826  // the 1.18 compiler using the new types2 type checker, or pass with sub-optimal
  1827  // error(s).
  1828  
  1829  // List of files that the compiler cannot errorcheck with the new typechecker (types2).
  1830  var types2Failures = setOf(
  1831  	"shift1.go",               // types2 reports two new errors which are probably not right
  1832  	"fixedbugs/issue10700.go", // types2 should give hint about ptr to interface
  1833  	"fixedbugs/issue18331.go", // missing error about misuse of //go:noescape (irgen needs code from noder)
  1834  	"fixedbugs/issue18419.go", // types2 reports no field or method member, but should say unexported
  1835  	"fixedbugs/issue20233.go", // types2 reports two instead of one error (preference: 1.17 compiler)
  1836  	"fixedbugs/issue20245.go", // types2 reports two instead of one error (preference: 1.17 compiler)
  1837  	"fixedbugs/issue31053.go", // types2 reports "unknown field" instead of "cannot refer to unexported field"
  1838  	"fixedbugs/notinheap.go",  // types2 doesn't report errors about conversions that are invalid due to //go:notinheap
  1839  )
  1840  
  1841  var types2Failures32Bit = setOf(
  1842  	"printbig.go",             // large untyped int passed to print (32-bit)
  1843  	"fixedbugs/bug114.go",     // large untyped int passed to println (32-bit)
  1844  	"fixedbugs/issue23305.go", // large untyped int passed to println (32-bit)
  1845  )
  1846  
  1847  // In all of these cases, the 1.17 compiler reports reasonable errors, but either the
  1848  // 1.17 or 1.18 compiler report extra errors, so we can't match correctly on both. We
  1849  // now set the patterns to match correctly on all the 1.18 errors.
  1850  // This list remains here just as a reference and for comparison - these files all pass.
  1851  var _ = setOf(
  1852  	"import1.go",      // types2 reports extra errors
  1853  	"initializerr.go", // types2 reports extra error
  1854  	"typecheck.go",    // types2 reports extra error at function call
  1855  
  1856  	"fixedbugs/bug176.go", // types2 reports all errors (pref: types2)
  1857  	"fixedbugs/bug195.go", // types2 reports slight different errors, and an extra error
  1858  	"fixedbugs/bug412.go", // types2 produces a follow-on error
  1859  
  1860  	"fixedbugs/issue11614.go", // types2 reports an extra error
  1861  	"fixedbugs/issue17038.go", // types2 doesn't report a follow-on error (pref: types2)
  1862  	"fixedbugs/issue23732.go", // types2 reports different (but ok) line numbers
  1863  	"fixedbugs/issue4510.go",  // types2 reports different (but ok) line numbers
  1864  	"fixedbugs/issue7525b.go", // types2 reports init cycle error on different line - ok otherwise
  1865  	"fixedbugs/issue7525c.go", // types2 reports init cycle error on different line - ok otherwise
  1866  	"fixedbugs/issue7525d.go", // types2 reports init cycle error on different line - ok otherwise
  1867  	"fixedbugs/issue7525e.go", // types2 reports init cycle error on different line - ok otherwise
  1868  	"fixedbugs/issue7525.go",  // types2 reports init cycle error on different line - ok otherwise
  1869  )
  1870  
  1871  func setOf(keys ...string) map[string]bool {
  1872  	m := make(map[string]bool, len(keys))
  1873  	for _, key := range keys {
  1874  		m[key] = true
  1875  	}
  1876  	return m
  1877  }
  1878  
  1879  // splitQuoted splits the string s around each instance of one or more consecutive
  1880  // white space characters while taking into account quotes and escaping, and
  1881  // returns an array of substrings of s or an empty list if s contains only white space.
  1882  // Single quotes and double quotes are recognized to prevent splitting within the
  1883  // quoted region, and are removed from the resulting substrings. If a quote in s
  1884  // isn't closed err will be set and r will have the unclosed argument as the
  1885  // last element. The backslash is used for escaping.
  1886  //
  1887  // For example, the following string:
  1888  //
  1889  //	a b:"c d" 'e''f'  "g\""
  1890  //
  1891  // Would be parsed as:
  1892  //
  1893  //	[]string{"a", "b:c d", "ef", `g"`}
  1894  //
  1895  // [copied from src/go/build/build.go]
  1896  func splitQuoted(s string) (r []string, err error) {
  1897  	var args []string
  1898  	arg := make([]rune, len(s))
  1899  	escaped := false
  1900  	quoted := false
  1901  	quote := '\x00'
  1902  	i := 0
  1903  	for _, rune := range s {
  1904  		switch {
  1905  		case escaped:
  1906  			escaped = false
  1907  		case rune == '\\':
  1908  			escaped = true
  1909  			continue
  1910  		case quote != '\x00':
  1911  			if rune == quote {
  1912  				quote = '\x00'
  1913  				continue
  1914  			}
  1915  		case rune == '"' || rune == '\'':
  1916  			quoted = true
  1917  			quote = rune
  1918  			continue
  1919  		case unicode.IsSpace(rune):
  1920  			if quoted || i > 0 {
  1921  				quoted = false
  1922  				args = append(args, string(arg[:i]))
  1923  				i = 0
  1924  			}
  1925  			continue
  1926  		}
  1927  		arg[i] = rune
  1928  		i++
  1929  	}
  1930  	if quoted || i > 0 {
  1931  		args = append(args, string(arg[:i]))
  1932  	}
  1933  	if quote != 0 {
  1934  		err = errors.New("unclosed quote")
  1935  	} else if escaped {
  1936  		err = errors.New("unfinished escaping")
  1937  	}
  1938  	return args, err
  1939  }
  1940  

View as plain text