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

View as plain text