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

View as plain text