3 // Copyright 2012 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
7 // Run runs tests in the test directory.
36 verbose = flag.Bool("v", false, "verbose. if set, parallelism is set to 1.")
37 keep = flag.Bool("k", false, "keep. keep temporary directory.")
38 numParallel = flag.Int("n", runtime.NumCPU(), "number of parallel tests to run")
39 summary = flag.Bool("summary", false, "show summary of results")
40 allCodegen = flag.Bool("all_codegen", defaultAllCodeGen(), "run all goos/goarch for codegen")
41 showSkips = flag.Bool("show_skips", false, "show skipped tests")
42 runSkips = flag.Bool("run_skips", false, "run skipped tests (ignore skip and build tags)")
43 linkshared = flag.Bool("linkshared", false, "")
44 updateErrors = flag.Bool("update_errors", false, "update error messages in test file based on compiler output")
45 runoutputLimit = flag.Int("l", defaultRunOutputLimit(), "number of parallel runoutput tests to run")
46 force = flag.Bool("f", false, "ignore expected-failure test lists")
47 generics = flag.String("G", defaultGLevels, "a comma-separated list of -G compiler flags to test with")
49 shard = flag.Int("shard", 0, "shard index to run. Only applicable if -shards is non-zero.")
50 shards = flag.Int("shards", 0, "number of shards. If 0, all tests are run. This is used by the continuous build.")
60 var env = func() (res envVars) {
61 cmd := exec.Command("go", "env", "-json")
62 stdout, err := cmd.StdoutPipe()
64 log.Fatal("StdoutPipe:", err)
66 if err := cmd.Start(); err != nil {
67 log.Fatal("Start:", err)
69 if err := json.NewDecoder(stdout).Decode(&res); err != nil {
70 log.Fatal("Decode:", err)
72 if err := cmd.Wait(); err != nil {
73 log.Fatal("Wait:", err)
78 var unifiedEnabled, defaultGLevels = func() (bool, string) {
79 // TODO(mdempsky): This will give false negatives if the unified
80 // experiment is enabled by default, but presumably at that point we
81 // won't need to disable tests for it anymore anyway.
82 enabled := strings.Contains(","+env.GOEXPERIMENT+",", ",unified,")
84 // Normal test runs should test with both -G=0 and -G=3 for types2
85 // coverage. But the unified experiment always uses types2, so
86 // testing with -G=3 is redundant.
92 return enabled, glevels
95 // defaultAllCodeGen returns the default value of the -all_codegen
96 // flag. By default, we prefer to be fast (returning false), except on
97 // the linux-amd64 builder that's already very fast, so we get more
98 // test coverage on trybots. See https://golang.org/issue/34297.
99 func defaultAllCodeGen() bool {
100 return os.Getenv("GO_BUILDER_NAME") == "linux-amd64"
106 cgoEnabled, _ = strconv.ParseBool(env.CGO_ENABLED)
108 // dirs are the directories to look for *.go files in.
109 // TODO(bradfitz): just use all directories?
110 dirs = []string{".", "ken", "chan", "interface", "syntax", "dwarf", "fixedbugs", "codegen", "runtime", "abi", "typeparam", "typeparam/mdempsky"}
112 // ratec controls the max number of tests running at a time.
115 // toRun is the channel of tests to run.
116 // It is nil until the first test is started.
119 // rungatec controls the max number of runoutput tests
120 // executed in parallel as they can each consume a lot of memory.
124 // maxTests is an upper bound on the total number of tests.
125 // It is used as a channel buffer size to make sure sends don't block.
126 const maxTests = 5000
132 for _, s := range strings.Split(*generics, ",") {
133 glevel, err := strconv.Atoi(s)
135 log.Fatalf("invalid -G flag: %v", err)
137 glevels = append(glevels, glevel)
142 // Disable parallelism if printing or if using a simulator.
143 if *verbose || len(findExecCmd()) > 0 {
148 ratec = make(chan bool, *numParallel)
149 rungatec = make(chan bool, *runoutputLimit)
153 for _, arg := range flag.Args() {
154 if arg == "-" || arg == "--" {
156 // $ go run run.go - env.go
157 // $ go run run.go -- env.go
158 // $ go run run.go - ./fixedbugs
159 // $ go run run.go -- ./fixedbugs
162 if fi, err := os.Stat(arg); err == nil && fi.IsDir() {
163 for _, baseGoFile := range goFiles(arg) {
164 tests = append(tests, startTests(arg, baseGoFile, glevels)...)
166 } else if strings.HasSuffix(arg, ".go") {
167 dir, file := filepath.Split(arg)
168 tests = append(tests, startTests(dir, file, glevels)...)
170 log.Fatalf("can't yet deal with non-directory and non-go file %q", arg)
174 for _, dir := range dirs {
175 for _, baseGoFile := range goFiles(dir) {
176 tests = append(tests, startTests(dir, baseGoFile, glevels)...)
182 resCount := map[string]int{}
183 for _, test := range tests {
187 if e, isSkip := test.err.(skipError); isSkip {
189 errStr = "unexpected skip for " + path.Join(test.dir, test.gofile) + ": " + string(e)
193 errStr = test.err.Error()
195 errStr += " (expected)"
199 } else if test.expectFail {
201 errStr = "unexpected success"
203 if status == "FAIL" {
207 dt := fmt.Sprintf("%.3fs", test.dt.Seconds())
208 if status == "FAIL" {
209 fmt.Printf("# go run run.go -G=%v %s\n%s\nFAIL\t%s\t%s\n",
211 path.Join(test.dir, test.gofile),
212 errStr, test.goFileName(), dt)
218 fmt.Printf("%s\t%s\t%s\n", status, test.goFileName(), dt)
222 for k, v := range resCount {
223 fmt.Printf("%5d %s\n", v, k)
232 // goTool reports the path of the go tool to use to run the tests.
233 // If possible, use the same Go used to run run.go, otherwise
234 // fallback to the go version found in the PATH.
235 func goTool() string {
237 if runtime.GOOS == "windows" {
240 path := filepath.Join(runtime.GOROOT(), "bin", "go"+exeSuffix)
241 if _, err := os.Stat(path); err == nil {
244 // Just run "go" from PATH
248 func shardMatch(name string) bool {
253 io.WriteString(h, name)
254 return int(h.Sum32()%uint32(*shards)) == *shard
257 func goFiles(dir string) []string {
258 f, err := os.Open(dir)
262 dirnames, err := f.Readdirnames(-1)
268 for _, name := range dirnames {
269 if !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") && shardMatch(name) {
270 names = append(names, name)
277 type runCmd func(...string) ([]byte, error)
279 func compileFile(runcmd runCmd, longname string, flags []string) (out []byte, err error) {
280 cmd := []string{goTool(), "tool", "compile", "-e"}
281 cmd = append(cmd, flags...)
283 cmd = append(cmd, "-dynlink", "-installsuffix=dynlink")
285 cmd = append(cmd, longname)
286 return runcmd(cmd...)
289 func compileInDir(runcmd runCmd, dir string, flags []string, localImports bool, names ...string) (out []byte, err error) {
290 cmd := []string{goTool(), "tool", "compile", "-e"}
292 // Set relative path for local imports and import search path to current dir.
293 cmd = append(cmd, "-D", ".", "-I", ".")
295 cmd = append(cmd, flags...)
297 cmd = append(cmd, "-dynlink", "-installsuffix=dynlink")
299 for _, name := range names {
300 cmd = append(cmd, filepath.Join(dir, name))
302 return runcmd(cmd...)
305 func linkFile(runcmd runCmd, goname string, ldflags []string) (err error) {
306 pfile := strings.Replace(goname, ".go", ".o", -1)
307 cmd := []string{goTool(), "tool", "link", "-w", "-o", "a.exe", "-L", "."}
309 cmd = append(cmd, "-linkshared", "-installsuffix=dynlink")
312 cmd = append(cmd, ldflags...)
314 cmd = append(cmd, pfile)
315 _, err = runcmd(cmd...)
319 // skipError describes why a test was skipped.
320 type skipError string
322 func (s skipError) Error() string { return string(s) }
324 // test holds the state of a test.
327 donec chan bool // closed when done
329 glevel int // what -G level this test should use
336 // expectFail indicates whether the (overall) test recipe is
337 // expected to fail under the current test configuration (e.g., -G=3
338 // or GOEXPERIMENT=unified).
342 // initExpectFail initializes t.expectFail based on the build+test
343 // configuration. It should only be called for tests known to use
345 func (t *test) initExpectFail() {
350 failureSets := []map[string]bool{types2Failures}
352 // Note: gccgo supports more 32-bit architectures than this, but
353 // hopefully the 32-bit failures are fixed before this matters.
355 case "386", "arm", "mips", "mipsle":
356 failureSets = append(failureSets, types2Failures32Bit)
360 failureSets = append(failureSets, unifiedFailures)
362 failureSets = append(failureSets, g3Failures)
365 filename := strings.Replace(t.goFileName(), "\\", "/", -1) // goFileName() uses \ on Windows
367 for _, set := range failureSets {
375 func startTests(dir, gofile string, glevels []int) []*test {
376 tests := make([]*test, len(glevels))
377 for i, glevel := range glevels {
382 donec: make(chan bool, 1),
385 toRun = make(chan *test, maxTests)
391 panic("toRun buffer size (maxTests) is too small")
398 // runTests runs tests in parallel, but respecting the order they
399 // were enqueued on the toRun channel.
411 var cwd, _ = os.Getwd()
413 func (t *test) goFileName() string {
414 return filepath.Join(t.dir, t.gofile)
417 func (t *test) goDirName() string {
418 return filepath.Join(t.dir, strings.Replace(t.gofile, ".go", ".dir", -1))
421 func goDirFiles(longdir string) (filter []os.FileInfo, err error) {
422 files, dirErr := ioutil.ReadDir(longdir)
426 for _, gofile := range files {
427 if filepath.Ext(gofile.Name()) == ".go" {
428 filter = append(filter, gofile)
434 var packageRE = regexp.MustCompile(`(?m)^package ([\p{Lu}\p{Ll}\w]+)`)
436 func getPackageNameFromSource(fn string) (string, error) {
437 data, err := ioutil.ReadFile(fn)
441 pkgname := packageRE.FindStringSubmatch(string(data))
443 return "", fmt.Errorf("cannot find package name in %s", fn)
445 return pkgname[1], nil
448 // If singlefilepkgs is set, each file is considered a separate package
449 // even if the package names are the same.
450 func goDirPackages(longdir string, singlefilepkgs bool) ([][]string, error) {
451 files, err := goDirFiles(longdir)
456 m := make(map[string]int)
457 for _, file := range files {
459 pkgname, err := getPackageNameFromSource(filepath.Join(longdir, name))
464 if singlefilepkgs || !ok {
466 pkgs = append(pkgs, nil)
469 pkgs[i] = append(pkgs[i], name)
474 type context struct {
481 // shouldTest looks for build tags in a source file and returns
482 // whether the file should be used according to the tags.
483 func shouldTest(src string, goos, goarch string) (ok bool, whyNot string) {
487 for _, line := range strings.Split(src, "\n") {
488 line = strings.TrimSpace(line)
489 if strings.HasPrefix(line, "//") {
494 line = strings.TrimSpace(line)
495 if len(line) == 0 || line[0] != '+' {
498 gcFlags := os.Getenv("GO_GCFLAGS")
502 cgoEnabled: cgoEnabled,
503 noOptEnv: strings.Contains(gcFlags, "-N") || strings.Contains(gcFlags, "-l"),
506 words := strings.Fields(line)
507 if words[0] == "+build" {
509 for _, word := range words[1:] {
510 if ctxt.match(word) {
516 // no matching tag found.
525 func (ctxt *context) match(name string) bool {
529 if i := strings.Index(name, ","); i >= 0 {
530 // comma-separated list
531 return ctxt.match(name[:i]) && ctxt.match(name[i+1:])
533 if strings.HasPrefix(name, "!!") { // bad syntax, reject always
536 if strings.HasPrefix(name, "!") { // negation
537 return len(name) > 1 && !ctxt.match(name[1:])
540 // Tags must be letters, digits, underscores or dots.
541 // Unlike in Go identifiers, all digits are fine (e.g., "386").
542 for _, c := range name {
543 if !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != '_' && c != '.' {
548 if strings.HasPrefix(name, "goexperiment.") {
549 for _, tag := range build.Default.ToolTags {
557 if name == "cgo" && ctxt.cgoEnabled {
561 if name == ctxt.GOOS || name == ctxt.GOARCH || name == "gc" {
565 if ctxt.noOptEnv && name == "gcflags_noopt" {
569 if name == "test_run" {
576 func init() { checkShouldTest() }
578 // goGcflags returns the -gcflags argument to use with go build / go run.
579 // This must match the flags used for building the standard library,
580 // or else the commands will rebuild any needed packages (like runtime)
582 func (t *test) goGcflags() string {
583 flags := os.Getenv("GO_GCFLAGS")
585 flags = fmt.Sprintf("%s -G=%v", flags, t.glevel)
587 return "-gcflags=all=" + flags
590 func (t *test) goGcflagsIsEmpty() bool {
591 return "" == os.Getenv("GO_GCFLAGS") && t.glevel == 0
594 var errTimeout = errors.New("command exceeded time limit")
597 func (t *test) run() {
600 t.dt = time.Since(start)
604 srcBytes, err := ioutil.ReadFile(t.goFileName())
609 t.src = string(srcBytes)
610 if t.src[0] == '\n' {
611 t.err = skipError("starts with newline")
615 // Execution recipe stops at first blank line.
616 pos := strings.Index(t.src, "\n\n")
618 t.err = fmt.Errorf("double newline ending execution recipe not found in %s", t.goFileName())
621 action := t.src[:pos]
622 if nl := strings.Index(action, "\n"); nl >= 0 && strings.Contains(action[:nl], "+build") {
624 action = action[nl+1:]
626 action = strings.TrimPrefix(action, "//")
628 // Check for build constraints only up to the actual code.
629 pkgPos := strings.Index(t.src, "\npackage")
631 pkgPos = pos // some files are intentionally malformed
633 if ok, why := shouldTest(t.src[:pkgPos], goos, goarch); !ok {
635 fmt.Printf("%-20s %-20s: %s\n", "skip", t.goFileName(), why)
640 var args, flags, runenv []string
644 singlefilepkgs := false
647 f, err := splitQuoted(action)
649 t.err = fmt.Errorf("invalid test recipe: %v", err)
657 // TODO: Clean up/simplify this switch statement.
659 case "compile", "compiledir", "build", "builddir", "buildrundir", "run", "buildrun", "runoutput", "rundir", "runindir", "asmcheck":
661 case "errorcheckandrundir":
662 wantError = false // should be no error if also will run
663 case "errorcheckwithauto":
664 action = "errorcheck"
667 case "errorcheck", "errorcheckdir", "errorcheckoutput":
675 t.err = skipError("skipped; unknown pattern: " + action)
679 goexp := env.GOEXPERIMENT
682 for len(args) > 0 && strings.HasPrefix(args[0], "-") {
689 singlefilepkgs = true
693 // Do not set relative path for local imports to current dir,
694 // e.g. do not pass -D . -I . to the compiler.
695 // Used in fixedbugs/bug345.go to allow compilation and import of local pkg.
696 // See golang.org/issue/25635
698 case "-t": // timeout in seconds
701 tim, err = strconv.Atoi(args[0])
703 t.err = fmt.Errorf("need number of seconds for -t timeout, got %s instead", args[0])
705 case "-goexperiment": // set GOEXPERIMENT environment
711 runenv = append(runenv, "GOEXPERIMENT="+goexp)
714 flags = append(flags, args[0])
718 if action == "errorcheck" {
720 for i, f := range flags {
721 if strings.HasPrefix(f, "-d=") {
722 flags[i] = f + ",ssa/check/on"
728 flags = append(flags, "-d=ssa/check/on")
742 // validForGLevel reports whether the current test is valid to run
743 // at the specified -G level. If so, it may update flags as
744 // necessary to test with -G.
745 validForGLevel := func(tool Tool) bool {
747 for _, flag := range flags {
748 if strings.Contains(flag, "-G") {
753 if hasGFlag && t.glevel != 0 {
754 // test provides explicit -G flag already; don't run again
756 fmt.Printf("excl\t%s\n", t.goFileName())
761 if t.glevel == 0 && !hasGFlag && !unifiedEnabled {
762 // tests should always pass when run w/o types2 (i.e., using the
763 // legacy typechecker).
771 // ok; handled in goGcflags
775 flags = append(flags, fmt.Sprintf("-G=%v", t.glevel))
779 // we don't know how to add -G for this test yet
781 fmt.Printf("excl\t%s\n", t.goFileName())
791 defer os.RemoveAll(t.tempDir)
794 err = ioutil.WriteFile(filepath.Join(t.tempDir, t.gofile), srcBytes, 0644)
799 // A few tests (of things like the environment) require these to be set.
800 if os.Getenv("GOOS") == "" {
801 os.Setenv("GOOS", runtime.GOOS)
803 if os.Getenv("GOARCH") == "" {
804 os.Setenv("GOARCH", runtime.GOARCH)
809 tempDirIsGOPATH = false
811 runcmd := func(args ...string) ([]byte, error) {
812 cmd := exec.Command(args[0], args[1:]...)
816 cmd.Env = append(os.Environ(), "GOENV=off", "GOFLAGS=")
819 // Set PWD to match Dir to speed up os.Getwd in the child process.
820 cmd.Env = append(cmd.Env, "PWD="+cmd.Dir)
823 cmd.Env = append(cmd.Env, "GOPATH="+t.tempDir)
825 cmd.Env = append(cmd.Env, runenv...)
831 // This command-timeout code adapted from cmd/go/test.go
833 tick := time.NewTimer(time.Duration(tim) * time.Second)
834 done := make(chan error)
842 cmd.Process.Signal(os.Interrupt)
843 time.Sleep(1 * time.Second)
853 if err != nil && err != errTimeout {
854 err = fmt.Errorf("%s\n%s", err, buf.Bytes())
856 return buf.Bytes(), err
859 long := filepath.Join(cwd, t.goFileName())
862 t.err = fmt.Errorf("unimplemented action %q", action)
865 if !validForGLevel(AsmCheck) {
869 // Compile Go file and match the generated assembly
870 // against a set of regexps in comments.
871 ops := t.wantedAsmOpcodes(long)
872 self := runtime.GOOS + "/" + runtime.GOARCH
873 for _, env := range ops.Envs() {
874 // Only run checks relevant to the current GOOS/GOARCH,
875 // to avoid triggering a cross-compile of the runtime.
876 if string(env) != self && !strings.HasPrefix(string(env), self+"/") && !*allCodegen {
879 // -S=2 forces outermost line numbers when disassembling inlined code.
880 cmdline := []string{"build", "-gcflags", "-S=2"}
882 // Append flags, but don't override -gcflags=-S=2; add to it instead.
883 for i := 0; i < len(flags); i++ {
886 case strings.HasPrefix(flag, "-gcflags="):
887 cmdline[2] += " " + strings.TrimPrefix(flag, "-gcflags=")
888 case strings.HasPrefix(flag, "--gcflags="):
889 cmdline[2] += " " + strings.TrimPrefix(flag, "--gcflags=")
890 case flag == "-gcflags", flag == "--gcflags":
893 cmdline[2] += " " + flags[i]
896 cmdline = append(cmdline, flag)
900 cmdline = append(cmdline, long)
901 cmd := exec.Command(goTool(), cmdline...)
902 cmd.Env = append(os.Environ(), env.Environ()...)
903 if len(flags) > 0 && flags[0] == "-race" {
904 cmd.Env = append(cmd.Env, "CGO_ENABLED=1")
908 cmd.Stdout, cmd.Stderr = &buf, &buf
909 if err := cmd.Run(); err != nil {
910 fmt.Println(env, "\n", cmd.Stderr)
915 t.err = t.asmCheck(buf.String(), long, env, ops[env])
923 if !validForGLevel(Compile) {
928 // Fail if wantError is true and compilation was successful and vice versa.
929 // Match errors produced by gc against errors in comments.
930 // TODO(gri) remove need for -C (disable printing of columns in error messages)
931 cmdline := []string{goTool(), "tool", "compile", "-d=panic", "-C", "-e", "-o", "a.o"}
932 // No need to add -dynlink even if linkshared if we're just checking for errors...
933 cmdline = append(cmdline, flags...)
934 cmdline = append(cmdline, long)
935 out, err := runcmd(cmdline...)
938 t.err = fmt.Errorf("compilation succeeded unexpectedly\n%s", out)
941 if err == errTimeout {
942 t.err = fmt.Errorf("compilation timed out")
952 t.updateErrors(string(out), long)
954 t.err = t.errorCheck(string(out), wantAuto, long, t.gofile)
957 if !validForGLevel(Compile) {
962 _, t.err = compileFile(runcmd, long, flags)
965 if !validForGLevel(Compile) {
969 // Compile all files in the directory as packages in lexicographic order.
970 longdir := filepath.Join(cwd, t.goDirName())
971 pkgs, err := goDirPackages(longdir, singlefilepkgs)
976 for _, gofiles := range pkgs {
977 _, t.err = compileInDir(runcmd, longdir, flags, localImports, gofiles...)
983 case "errorcheckdir", "errorcheckandrundir":
984 if !validForGLevel(Compile) {
988 flags = append(flags, "-d=panic")
989 // Compile and errorCheck all files in the directory as packages in lexicographic order.
990 // If errorcheckdir and wantError, compilation of the last package must fail.
991 // If errorcheckandrundir and wantError, compilation of the package prior the last must fail.
992 longdir := filepath.Join(cwd, t.goDirName())
993 pkgs, err := goDirPackages(longdir, singlefilepkgs)
998 errPkg := len(pkgs) - 1
999 if wantError && action == "errorcheckandrundir" {
1000 // The last pkg should compiled successfully and will be run in next case.
1001 // Preceding pkg must return an error from compileInDir.
1004 for i, gofiles := range pkgs {
1005 out, err := compileInDir(runcmd, longdir, flags, localImports, gofiles...)
1007 if wantError && err == nil {
1008 t.err = fmt.Errorf("compilation succeeded unexpectedly\n%s", out)
1010 } else if !wantError && err != nil {
1014 } else if err != nil {
1018 var fullshort []string
1019 for _, name := range gofiles {
1020 fullshort = append(fullshort, filepath.Join(longdir, name), name)
1022 t.err = t.errorCheck(string(out), wantAuto, fullshort...)
1027 if action == "errorcheckdir" {
1033 if !validForGLevel(Run) {
1037 // Compile all files in the directory as packages in lexicographic order.
1038 // In case of errorcheckandrundir, ignore failed compilation of the package before the last.
1039 // Link as if the last file is the main package, run it.
1040 // Verify the expected output.
1041 longdir := filepath.Join(cwd, t.goDirName())
1042 pkgs, err := goDirPackages(longdir, singlefilepkgs)
1047 // Split flags into gcflags and ldflags
1048 ldflags := []string{}
1049 for i, fl := range flags {
1050 if fl == "-ldflags" {
1051 ldflags = flags[i+1:]
1057 for i, gofiles := range pkgs {
1058 pflags := []string{}
1059 pflags = append(pflags, flags...)
1061 fp := filepath.Join(longdir, gofiles[0])
1062 pkgname, err := getPackageNameFromSource(fp)
1066 pflags = append(pflags, "-p", pkgname)
1068 _, err := compileInDir(runcmd, longdir, pflags, localImports, gofiles...)
1069 // Allow this package compilation fail based on conditions below;
1070 // its errors were checked in previous case.
1071 if err != nil && !(wantError && action == "errorcheckandrundir" && i == len(pkgs)-2) {
1075 if i == len(pkgs)-1 {
1076 err = linkFile(runcmd, gofiles[0], ldflags)
1082 cmd = append(cmd, findExecCmd()...)
1083 cmd = append(cmd, filepath.Join(t.tempDir, "a.exe"))
1084 cmd = append(cmd, args...)
1085 out, err := runcmd(cmd...)
1090 t.checkExpectedOutput(out)
1095 if !validForGLevel(Run) {
1099 // Make a shallow copy of t.goDirName() in its own module and GOPATH, and
1100 // run "go run ." in it. The module path (and hence import path prefix) of
1101 // the copy is equal to the basename of the source directory.
1103 // It's used when test a requires a full 'go build' in order to compile
1104 // the sources, such as when importing multiple packages (issue29612.dir)
1105 // or compiling a package containing assembly files (see issue15609.dir),
1106 // but still needs to be run to verify the expected output.
1107 tempDirIsGOPATH = true
1108 srcDir := t.goDirName()
1109 modName := filepath.Base(srcDir)
1110 gopathSrcDir := filepath.Join(t.tempDir, "src", modName)
1111 runInDir = gopathSrcDir
1113 if err := overlayDir(gopathSrcDir, srcDir); err != nil {
1118 modFile := fmt.Sprintf("module %s\ngo 1.14\n", modName)
1119 if err := ioutil.WriteFile(filepath.Join(gopathSrcDir, "go.mod"), []byte(modFile), 0666); err != nil {
1124 cmd := []string{goTool(), "run", t.goGcflags()}
1126 cmd = append(cmd, "-linkshared")
1128 cmd = append(cmd, flags...)
1129 cmd = append(cmd, ".")
1130 out, err := runcmd(cmd...)
1135 t.checkExpectedOutput(out)
1138 if !validForGLevel(Build) {
1143 _, err := runcmd(goTool(), "build", t.goGcflags(), "-o", "a.exe", long)
1148 case "builddir", "buildrundir":
1149 if !validForGLevel(Build) {
1153 // Build an executable from all the .go and .s files in a subdirectory.
1154 // Run it and verify its output in the buildrundir case.
1155 longdir := filepath.Join(cwd, t.goDirName())
1156 files, dirErr := ioutil.ReadDir(longdir)
1163 for _, file := range files {
1164 switch filepath.Ext(file.Name()) {
1166 gos = append(gos, filepath.Join(longdir, file.Name()))
1168 asms = append(asms, filepath.Join(longdir, file.Name()))
1173 emptyHdrFile := filepath.Join(t.tempDir, "go_asm.h")
1174 if err := ioutil.WriteFile(emptyHdrFile, nil, 0666); err != nil {
1175 t.err = fmt.Errorf("write empty go_asm.h: %s", err)
1178 cmd := []string{goTool(), "tool", "asm", "-gensymabis", "-o", "symabis"}
1179 cmd = append(cmd, asms...)
1180 _, err = runcmd(cmd...)
1187 cmd := []string{goTool(), "tool", "compile", "-e", "-D", ".", "-I", ".", "-o", "go.o"}
1189 cmd = append(cmd, "-asmhdr", "go_asm.h", "-symabis", "symabis")
1191 cmd = append(cmd, gos...)
1192 _, err := runcmd(cmd...)
1197 objs = append(objs, "go.o")
1199 cmd = []string{goTool(), "tool", "asm", "-e", "-I", ".", "-o", "asm.o"}
1200 cmd = append(cmd, asms...)
1201 _, err = runcmd(cmd...)
1206 objs = append(objs, "asm.o")
1208 cmd = []string{goTool(), "tool", "pack", "c", "all.a"}
1209 cmd = append(cmd, objs...)
1210 _, err = runcmd(cmd...)
1215 cmd = []string{goTool(), "tool", "link", "-o", "a.exe", "all.a"}
1216 _, err = runcmd(cmd...)
1221 if action == "buildrundir" {
1222 cmd = append(findExecCmd(), filepath.Join(t.tempDir, "a.exe"))
1223 out, err := runcmd(cmd...)
1228 t.checkExpectedOutput(out)
1232 if !validForGLevel(Build) {
1236 // Build an executable from Go file, then run it, verify its output.
1237 // Useful for timeout tests where failure mode is infinite loop.
1238 // TODO: not supported on NaCl
1239 cmd := []string{goTool(), "build", t.goGcflags(), "-o", "a.exe"}
1241 cmd = append(cmd, "-linkshared")
1243 longdirgofile := filepath.Join(filepath.Join(cwd, t.dir), t.gofile)
1244 cmd = append(cmd, flags...)
1245 cmd = append(cmd, longdirgofile)
1246 _, err := runcmd(cmd...)
1251 cmd = []string{"./a.exe"}
1252 out, err := runcmd(append(cmd, args...)...)
1258 t.checkExpectedOutput(out)
1261 if !validForGLevel(Run) {
1265 // Run Go file if no special go command flags are provided;
1266 // otherwise build an executable and run it.
1267 // Verify the output.
1271 if len(flags)+len(args) == 0 && t.goGcflagsIsEmpty() && !*linkshared && goarch == runtime.GOARCH && goos == runtime.GOOS && goexp == env.GOEXPERIMENT {
1272 // If we're not using special go command flags,
1273 // skip all the go command machinery.
1274 // This avoids any time the go command would
1275 // spend checking whether, for example, the installed
1276 // package runtime is up to date.
1277 // Because we run lots of trivial test programs,
1278 // the time adds up.
1279 pkg := filepath.Join(t.tempDir, "pkg.a")
1280 if _, err := runcmd(goTool(), "tool", "compile", "-o", pkg, t.goFileName()); err != nil {
1284 exe := filepath.Join(t.tempDir, "test.exe")
1285 cmd := []string{goTool(), "tool", "link", "-s", "-w"}
1286 cmd = append(cmd, "-o", exe, pkg)
1287 if _, err := runcmd(cmd...); err != nil {
1291 out, err = runcmd(append([]string{exe}, args...)...)
1293 cmd := []string{goTool(), "run", t.goGcflags()}
1295 cmd = append(cmd, "-linkshared")
1297 cmd = append(cmd, flags...)
1298 cmd = append(cmd, t.goFileName())
1299 out, err = runcmd(append(cmd, args...)...)
1305 t.checkExpectedOutput(out)
1308 if !validForGLevel(Run) {
1312 // Run Go file and write its output into temporary Go file.
1313 // Run generated Go file and verify its output.
1319 cmd := []string{goTool(), "run", t.goGcflags()}
1321 cmd = append(cmd, "-linkshared")
1323 cmd = append(cmd, t.goFileName())
1324 out, err := runcmd(append(cmd, args...)...)
1329 tfile := filepath.Join(t.tempDir, "tmp__.go")
1330 if err := ioutil.WriteFile(tfile, out, 0666); err != nil {
1331 t.err = fmt.Errorf("write tempfile:%s", err)
1334 cmd = []string{goTool(), "run", t.goGcflags()}
1336 cmd = append(cmd, "-linkshared")
1338 cmd = append(cmd, tfile)
1339 out, err = runcmd(cmd...)
1344 t.checkExpectedOutput(out)
1346 case "errorcheckoutput":
1347 if !validForGLevel(Compile) {
1351 // Run Go file and write its output into temporary Go file.
1352 // Compile and errorCheck generated Go file.
1354 cmd := []string{goTool(), "run", t.goGcflags()}
1356 cmd = append(cmd, "-linkshared")
1358 cmd = append(cmd, t.goFileName())
1359 out, err := runcmd(append(cmd, args...)...)
1364 tfile := filepath.Join(t.tempDir, "tmp__.go")
1365 err = ioutil.WriteFile(tfile, out, 0666)
1367 t.err = fmt.Errorf("write tempfile:%s", err)
1370 cmdline := []string{goTool(), "tool", "compile", "-d=panic", "-e", "-o", "a.o"}
1371 cmdline = append(cmdline, flags...)
1372 cmdline = append(cmdline, tfile)
1373 out, err = runcmd(cmdline...)
1376 t.err = fmt.Errorf("compilation succeeded unexpectedly\n%s", out)
1385 t.err = t.errorCheck(string(out), false, tfile, "tmp__.go")
1390 var execCmd []string
1392 func findExecCmd() []string {
1396 execCmd = []string{} // avoid work the second time
1397 if goos == runtime.GOOS && goarch == runtime.GOARCH {
1400 path, err := exec.LookPath(fmt.Sprintf("go_%s_%s_exec", goos, goarch))
1402 execCmd = []string{path}
1407 func (t *test) String() string {
1408 return filepath.Join(t.dir, t.gofile)
1411 func (t *test) makeTempDir() {
1413 t.tempDir, err = ioutil.TempDir("", "")
1418 log.Printf("Temporary directory is %s", t.tempDir)
1422 // checkExpectedOutput compares the output from compiling and/or running with the contents
1423 // of the corresponding reference output file, if any (replace ".go" with ".out").
1424 // If they don't match, fail with an informative message.
1425 func (t *test) checkExpectedOutput(gotBytes []byte) {
1426 got := string(gotBytes)
1427 filename := filepath.Join(t.dir, t.gofile)
1428 filename = filename[:len(filename)-len(".go")]
1430 b, err := ioutil.ReadFile(filename)
1431 // File is allowed to be missing (err != nil) in which case output should be empty.
1432 got = strings.Replace(got, "\r\n", "\n", -1)
1433 if got != string(b) {
1435 t.err = fmt.Errorf("output does not match expected in %s. Instead saw\n%s", filename, got)
1437 t.err = fmt.Errorf("output should be empty when (optional) expected-output file %s is not present. Instead saw\n%s", filename, got)
1442 func splitOutput(out string, wantAuto bool) []string {
1443 // gc error messages continue onto additional lines with leading tabs.
1444 // Split the output at the beginning of each line that doesn't begin with a tab.
1445 // <autogenerated> lines are impossible to match so those are filtered out.
1447 for _, line := range strings.Split(out, "\n") {
1448 if strings.HasSuffix(line, "\r") { // remove '\r', output by compiler on windows
1449 line = line[:len(line)-1]
1451 if strings.HasPrefix(line, "\t") {
1452 res[len(res)-1] += "\n" + line
1453 } else if strings.HasPrefix(line, "go tool") || strings.HasPrefix(line, "#") || !wantAuto && strings.HasPrefix(line, "<autogenerated>") {
1455 } else if strings.TrimSpace(line) != "" {
1456 res = append(res, line)
1462 // errorCheck matches errors in outStr against comments in source files.
1463 // For each line of the source files which should generate an error,
1464 // there should be a comment of the form // ERROR "regexp".
1465 // If outStr has an error for a line which has no such comment,
1466 // this function will report an error.
1467 // Likewise if outStr does not have an error for a line which has a comment,
1468 // or if the error message does not match the <regexp>.
1469 // The <regexp> syntax is Perl but it's best to stick to egrep.
1471 // Sources files are supplied as fullshort slice.
1472 // It consists of pairs: full path to source file and its base name.
1473 func (t *test) errorCheck(outStr string, wantAuto bool, fullshort ...string) (err error) {
1475 if *verbose && err != nil {
1476 log.Printf("%s gc output:\n%s", t, outStr)
1480 out := splitOutput(outStr, wantAuto)
1482 // Cut directory name.
1483 for i := range out {
1484 for j := 0; j < len(fullshort); j += 2 {
1485 full, short := fullshort[j], fullshort[j+1]
1486 out[i] = strings.Replace(out[i], full, short, -1)
1490 var want []wantedError
1491 for j := 0; j < len(fullshort); j += 2 {
1492 full, short := fullshort[j], fullshort[j+1]
1493 want = append(want, t.wantedErrors(full, short)...)
1496 for _, we := range want {
1497 var errmsgs []string
1499 errmsgs, out = partitionStrings("<autogenerated>", out)
1501 errmsgs, out = partitionStrings(we.prefix, out)
1503 if len(errmsgs) == 0 {
1504 errs = append(errs, fmt.Errorf("%s:%d: missing error %q", we.file, we.lineNum, we.reStr))
1509 for _, errmsg := range errmsgs {
1510 // Assume errmsg says "file:line: foo".
1511 // Cut leading "file:line: " to avoid accidental matching of file name instead of message.
1513 if i := strings.Index(text, " "); i >= 0 {
1516 if we.re.MatchString(text) {
1519 out = append(out, errmsg)
1523 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")))
1529 errs = append(errs, fmt.Errorf("Unmatched Errors:"))
1530 for _, errLine := range out {
1531 errs = append(errs, fmt.Errorf("%s", errLine))
1541 var buf bytes.Buffer
1542 fmt.Fprintf(&buf, "\n")
1543 for _, err := range errs {
1544 fmt.Fprintf(&buf, "%s\n", err.Error())
1546 return errors.New(buf.String())
1549 func (t *test) updateErrors(out, file string) {
1550 base := path.Base(file)
1551 // Read in source file.
1552 src, err := ioutil.ReadFile(file)
1554 fmt.Fprintln(os.Stderr, err)
1557 lines := strings.Split(string(src), "\n")
1558 // Remove old errors.
1559 for i, ln := range lines {
1560 pos := strings.Index(ln, " // ERROR ")
1565 // Parse new errors.
1566 errors := make(map[int]map[string]bool)
1567 tmpRe := regexp.MustCompile(`autotmp_[0-9]+`)
1568 for _, errStr := range splitOutput(out, false) {
1569 colon1 := strings.Index(errStr, ":")
1570 if colon1 < 0 || errStr[:colon1] != file {
1573 colon2 := strings.Index(errStr[colon1+1:], ":")
1577 colon2 += colon1 + 1
1578 line, err := strconv.Atoi(errStr[colon1+1 : colon2])
1580 if err != nil || line < 0 || line >= len(lines) {
1583 msg := errStr[colon2+2:]
1584 msg = strings.Replace(msg, file, base, -1) // normalize file mentions in error itself
1585 msg = strings.TrimLeft(msg, " \t")
1586 for _, r := range []string{`\`, `*`, `+`, `?`, `[`, `]`, `(`, `)`} {
1587 msg = strings.Replace(msg, r, `\`+r, -1)
1589 msg = strings.Replace(msg, `"`, `.`, -1)
1590 msg = tmpRe.ReplaceAllLiteralString(msg, `autotmp_[0-9]+`)
1591 if errors[line] == nil {
1592 errors[line] = make(map[string]bool)
1594 errors[line][msg] = true
1597 for line, errs := range errors {
1599 for e := range errs {
1600 sorted = append(sorted, e)
1602 sort.Strings(sorted)
1603 lines[line] += " // ERROR"
1604 for _, e := range sorted {
1605 lines[line] += fmt.Sprintf(` "%s$"`, e)
1609 err = ioutil.WriteFile(file, []byte(strings.Join(lines, "\n")), 0640)
1611 fmt.Fprintln(os.Stderr, err)
1615 exec.Command(goTool(), "fmt", file).CombinedOutput()
1618 // matchPrefix reports whether s is of the form ^(.*/)?prefix(:|[),
1619 // That is, it needs the file name prefix followed by a : or a [,
1620 // and possibly preceded by a directory name.
1621 func matchPrefix(s, prefix string) bool {
1622 i := strings.Index(s, ":")
1626 j := strings.LastIndex(s[:i], "/")
1628 if len(s) <= len(prefix) || s[:len(prefix)] != prefix {
1631 switch s[len(prefix)] {
1638 func partitionStrings(prefix string, strs []string) (matched, unmatched []string) {
1639 for _, s := range strs {
1640 if matchPrefix(s, prefix) {
1641 matched = append(matched, s)
1643 unmatched = append(unmatched, s)
1649 type wantedError struct {
1653 auto bool // match <autogenerated> line
1659 errRx = regexp.MustCompile(`// (?:GC_)?ERROR (.*)`)
1660 errAutoRx = regexp.MustCompile(`// (?:GC_)?ERRORAUTO (.*)`)
1661 errQuotesRx = regexp.MustCompile(`"([^"]*)"`)
1662 lineRx = regexp.MustCompile(`LINE(([+-])([0-9]+))?`)
1665 func (t *test) wantedErrors(file, short string) (errs []wantedError) {
1666 cache := make(map[string]*regexp.Regexp)
1668 src, _ := ioutil.ReadFile(file)
1669 for i, line := range strings.Split(string(src), "\n") {
1671 if strings.Contains(line, "////") {
1672 // double comment disables ERROR
1676 m := errAutoRx.FindStringSubmatch(line)
1680 m = errRx.FindStringSubmatch(line)
1686 mm := errQuotesRx.FindAllStringSubmatch(all, -1)
1688 log.Fatalf("%s:%d: invalid errchk line: %s", t.goFileName(), lineNum, line)
1690 for _, m := range mm {
1691 rx := lineRx.ReplaceAllStringFunc(m[1], func(m string) string {
1693 if strings.HasPrefix(m, "LINE+") {
1694 delta, _ := strconv.Atoi(m[5:])
1696 } else if strings.HasPrefix(m, "LINE-") {
1697 delta, _ := strconv.Atoi(m[5:])
1700 return fmt.Sprintf("%s:%d", short, n)
1705 re, err = regexp.Compile(rx)
1707 log.Fatalf("%s:%d: invalid regexp \"%s\" in ERROR line: %v", t.goFileName(), lineNum, rx, err)
1711 prefix := fmt.Sprintf("%s:%d", short, lineNum)
1712 errs = append(errs, wantedError{
1727 // Regexp to match a single opcode check: optionally begin with "-" (to indicate
1728 // a negative check), followed by a string literal enclosed in "" or ``. For "",
1729 // backslashes must be handled.
1730 reMatchCheck = `-?(?:\x60[^\x60]*\x60|"(?:[^"\\]|\\.)*")`
1734 // Regexp to split a line in code and comment, trimming spaces
1735 rxAsmComment = regexp.MustCompile(`^\s*(.*?)\s*(?://\s*(.+)\s*)?$`)
1737 // Regexp to extract an architecture check: architecture name (or triplet),
1738 // followed by semi-colon, followed by a comma-separated list of opcode checks.
1739 // Extraneous spaces are ignored.
1740 rxAsmPlatform = regexp.MustCompile(`(\w+)(/\w+)?(/\w*)?\s*:\s*(` + reMatchCheck + `(?:\s*,\s*` + reMatchCheck + `)*)`)
1742 // Regexp to extract a single opcoded check
1743 rxAsmCheck = regexp.MustCompile(reMatchCheck)
1745 // List of all architecture variants. Key is the GOARCH architecture,
1746 // value[0] is the variant-changing environment variable, and values[1:]
1747 // are the supported variants.
1748 archVariants = map[string][]string{
1749 "386": {"GO386", "sse2", "softfloat"},
1751 "arm": {"GOARM", "5", "6", "7"},
1753 "mips": {"GOMIPS", "hardfloat", "softfloat"},
1754 "mips64": {"GOMIPS64", "hardfloat", "softfloat"},
1755 "ppc64": {"GOPPC64", "power8", "power9"},
1756 "ppc64le": {"GOPPC64", "power8", "power9"},
1762 // wantedAsmOpcode is a single asmcheck check
1763 type wantedAsmOpcode struct {
1764 fileline string // original source file/line (eg: "/path/foo.go:45")
1765 line int // original source line
1766 opcode *regexp.Regexp // opcode check to be performed on assembly output
1767 negative bool // true if the check is supposed to fail rather than pass
1768 found bool // true if the opcode check matched at least one in the output
1771 // A build environment triplet separated by slashes (eg: linux/386/sse2).
1772 // The third field can be empty if the arch does not support variants (eg: "plan9/amd64/")
1773 type buildEnv string
1775 // Environ returns the environment it represents in cmd.Environ() "key=val" format
1776 // For instance, "linux/386/sse2".Environ() returns {"GOOS=linux", "GOARCH=386", "GO386=sse2"}
1777 func (b buildEnv) Environ() []string {
1778 fields := strings.Split(string(b), "/")
1779 if len(fields) != 3 {
1780 panic("invalid buildEnv string: " + string(b))
1782 env := []string{"GOOS=" + fields[0], "GOARCH=" + fields[1]}
1783 if fields[2] != "" {
1784 env = append(env, archVariants[fields[1]][0]+"="+fields[2])
1789 // asmChecks represents all the asmcheck checks present in a test file
1790 // The outer map key is the build triplet in which the checks must be performed.
1791 // The inner map key represent the source file line ("filename.go:1234") at which the
1792 // checks must be performed.
1793 type asmChecks map[buildEnv]map[string][]wantedAsmOpcode
1795 // Envs returns all the buildEnv in which at least one check is present
1796 func (a asmChecks) Envs() []buildEnv {
1799 envs = append(envs, e)
1801 sort.Slice(envs, func(i, j int) bool {
1802 return string(envs[i]) < string(envs[j])
1807 func (t *test) wantedAsmOpcodes(fn string) asmChecks {
1808 ops := make(asmChecks)
1811 src, _ := ioutil.ReadFile(fn)
1812 for i, line := range strings.Split(string(src), "\n") {
1813 matches := rxAsmComment.FindStringSubmatch(line)
1814 code, cmt := matches[1], matches[2]
1816 // Keep comments pending in the comment variable until
1817 // we find a line that contains some code.
1818 comment += " " + cmt
1823 // Parse and extract any architecture check from comments,
1824 // made by one architecture name and multiple checks.
1825 lnum := fn + ":" + strconv.Itoa(i+1)
1826 for _, ac := range rxAsmPlatform.FindAllStringSubmatch(comment, -1) {
1827 archspec, allchecks := ac[1:4], ac[4]
1829 var arch, subarch, os string
1831 case archspec[2] != "": // 3 components: "linux/386/sse2"
1832 os, arch, subarch = archspec[0], archspec[1][1:], archspec[2][1:]
1833 case archspec[1] != "": // 2 components: "386/sse2"
1834 os, arch, subarch = "linux", archspec[0], archspec[1][1:]
1835 default: // 1 component: "386"
1836 os, arch, subarch = "linux", archspec[0], ""
1842 if _, ok := archVariants[arch]; !ok {
1843 log.Fatalf("%s:%d: unsupported architecture: %v", t.goFileName(), i+1, arch)
1846 // Create the build environments corresponding the above specifiers
1847 envs := make([]buildEnv, 0, 4)
1849 envs = append(envs, buildEnv(os+"/"+arch+"/"+subarch))
1851 subarchs := archVariants[arch]
1852 if len(subarchs) == 0 {
1853 envs = append(envs, buildEnv(os+"/"+arch+"/"))
1855 for _, sa := range archVariants[arch][1:] {
1856 envs = append(envs, buildEnv(os+"/"+arch+"/"+sa))
1861 for _, m := range rxAsmCheck.FindAllString(allchecks, -1) {
1868 rxsrc, err := strconv.Unquote(m)
1870 log.Fatalf("%s:%d: error unquoting string: %v", t.goFileName(), i+1, err)
1873 // Compile the checks as regular expressions. Notice that we
1874 // consider checks as matching from the beginning of the actual
1875 // assembler source (that is, what is left on each line of the
1876 // compile -S output after we strip file/line info) to avoid
1877 // trivial bugs such as "ADD" matching "FADD". This
1878 // doesn't remove genericity: it's still possible to write
1879 // something like "F?ADD", but we make common cases simpler
1881 oprx, err := regexp.Compile("^" + rxsrc)
1883 log.Fatalf("%s:%d: %v", t.goFileName(), i+1, err)
1886 for _, env := range envs {
1887 if ops[env] == nil {
1888 ops[env] = make(map[string][]wantedAsmOpcode)
1890 ops[env][lnum] = append(ops[env][lnum], wantedAsmOpcode{
1905 func (t *test) asmCheck(outStr string, fn string, env buildEnv, fullops map[string][]wantedAsmOpcode) (err error) {
1906 // The assembly output contains the concatenated dump of multiple functions.
1907 // the first line of each function begins at column 0, while the rest is
1908 // indented by a tabulation. These data structures help us index the
1909 // output by function.
1910 functionMarkers := make([]int, 1)
1911 lineFuncMap := make(map[string]int)
1913 lines := strings.Split(outStr, "\n")
1914 rxLine := regexp.MustCompile(fmt.Sprintf(`\((%s:\d+)\)\s+(.*)`, regexp.QuoteMeta(fn)))
1916 for nl, line := range lines {
1917 // Check if this line begins a function
1918 if len(line) > 0 && line[0] != '\t' {
1919 functionMarkers = append(functionMarkers, nl)
1922 // Search if this line contains a assembly opcode (which is prefixed by the
1923 // original source file/line in parenthesis)
1924 matches := rxLine.FindStringSubmatch(line)
1925 if len(matches) == 0 {
1928 srcFileLine, asm := matches[1], matches[2]
1930 // Associate the original file/line information to the current
1931 // function in the output; it will be useful to dump it in case
1933 lineFuncMap[srcFileLine] = len(functionMarkers) - 1
1935 // If there are opcode checks associated to this source file/line,
1937 if ops, found := fullops[srcFileLine]; found {
1938 for i := range ops {
1939 if !ops[i].found && ops[i].opcode.FindString(asm) != "" {
1945 functionMarkers = append(functionMarkers, len(lines))
1947 var failed []wantedAsmOpcode
1948 for _, ops := range fullops {
1949 for _, o := range ops {
1950 // There's a failure if a negative match was found,
1951 // or a positive match was not found.
1952 if o.negative == o.found {
1953 failed = append(failed, o)
1957 if len(failed) == 0 {
1961 // At least one asmcheck failed; report them
1962 sort.Slice(failed, func(i, j int) bool {
1963 return failed[i].line < failed[j].line
1967 var errbuf bytes.Buffer
1968 fmt.Fprintln(&errbuf)
1969 for _, o := range failed {
1970 // Dump the function in which this opcode check was supposed to
1972 funcIdx := lineFuncMap[o.fileline]
1973 if funcIdx != 0 && funcIdx != lastFunction {
1974 funcLines := lines[functionMarkers[funcIdx]:functionMarkers[funcIdx+1]]
1975 log.Println(strings.Join(funcLines, "\n"))
1976 lastFunction = funcIdx // avoid printing same function twice
1980 fmt.Fprintf(&errbuf, "%s:%d: %s: wrong opcode found: %q\n", t.goFileName(), o.line, env, o.opcode.String())
1982 fmt.Fprintf(&errbuf, "%s:%d: %s: opcode not found: %q\n", t.goFileName(), o.line, env, o.opcode.String())
1985 err = errors.New(errbuf.String())
1989 // defaultRunOutputLimit returns the number of runoutput tests that
1990 // can be executed in parallel.
1991 func defaultRunOutputLimit() int {
1994 cpu := runtime.NumCPU()
1995 if runtime.GOARCH == "arm" && cpu > maxArmCPU {
2001 // checkShouldTest runs sanity checks on the shouldTest function.
2002 func checkShouldTest() {
2003 assert := func(ok bool, _ string) {
2008 assertNot := func(ok bool, _ string) { assert(!ok, "") }
2011 assert(shouldTest("// +build linux", "linux", "arm"))
2012 assert(shouldTest("// +build !windows", "linux", "arm"))
2013 assertNot(shouldTest("// +build !windows", "windows", "amd64"))
2015 // A file with no build tags will always be tested.
2016 assert(shouldTest("// This is a test.", "os", "arch"))
2018 // Build tags separated by a space are OR-ed together.
2019 assertNot(shouldTest("// +build arm 386", "linux", "amd64"))
2021 // Build tags separated by a comma are AND-ed together.
2022 assertNot(shouldTest("// +build !windows,!plan9", "windows", "amd64"))
2023 assertNot(shouldTest("// +build !windows,!plan9", "plan9", "386"))
2025 // Build tags on multiple lines are AND-ed together.
2026 assert(shouldTest("// +build !windows\n// +build amd64", "linux", "amd64"))
2027 assertNot(shouldTest("// +build !windows\n// +build amd64", "windows", "amd64"))
2029 // Test that (!a OR !b) matches anything.
2030 assert(shouldTest("// +build !windows !plan9", "windows", "amd64"))
2033 func getenv(key, def string) string {
2034 value := os.Getenv(key)
2041 // overlayDir makes a minimal-overhead copy of srcRoot in which new files may be added.
2042 func overlayDir(dstRoot, srcRoot string) error {
2043 dstRoot = filepath.Clean(dstRoot)
2044 if err := os.MkdirAll(dstRoot, 0777); err != nil {
2048 srcRoot, err := filepath.Abs(srcRoot)
2053 return filepath.WalkDir(srcRoot, func(srcPath string, d fs.DirEntry, err error) error {
2054 if err != nil || srcPath == srcRoot {
2058 suffix := strings.TrimPrefix(srcPath, srcRoot)
2059 for len(suffix) > 0 && suffix[0] == filepath.Separator {
2062 dstPath := filepath.Join(dstRoot, suffix)
2064 var info fs.FileInfo
2065 if d.Type()&os.ModeSymlink != 0 {
2066 info, err = os.Stat(srcPath)
2068 info, err = d.Info()
2073 perm := info.Mode() & os.ModePerm
2075 // Always copy directories (don't symlink them).
2076 // If we add a file in the overlay, we don't want to add it in the original.
2078 return os.MkdirAll(dstPath, perm|0200)
2081 // If the OS supports symlinks, use them instead of copying bytes.
2082 if err := os.Symlink(srcPath, dstPath); err == nil {
2086 // Otherwise, copy the bytes.
2087 src, err := os.Open(srcPath)
2093 dst, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm)
2098 _, err = io.Copy(dst, src)
2099 if closeErr := dst.Close(); err == nil {
2106 // The following is temporary scaffolding to get types2 typechecker
2107 // up and running against the existing test cases. The explicitly
2108 // listed files don't pass yet, usually because the error messages
2109 // are slightly different (this list is not complete). Any errorcheck
2110 // tests that require output from analysis phases past initial type-
2111 // checking are also excluded since these phases are not running yet.
2112 // We can get rid of this code once types2 is fully plugged in.
2114 // List of files that the compiler cannot errorcheck with the new typechecker (compiler -G option).
2115 // Temporary scaffolding until we pass all the tests at which point this map can be removed.
2116 var types2Failures = setOf(
2117 "directive.go", // misplaced compiler directive checks
2118 "float_lit3.go", // types2 reports extra errors
2119 "import1.go", // types2 reports extra errors
2120 "import6.go", // issue #43109
2121 "initializerr.go", // types2 reports extra errors
2122 "linkname2.go", // error reported by noder (not running for types2 errorcheck test)
2123 "notinheap.go", // types2 doesn't report errors about conversions that are invalid due to //go:notinheap
2124 "shift1.go", // issue #42989
2125 "typecheck.go", // invalid function is not causing errors when called
2127 "interface/private.go", // types2 phrases errors differently (doesn't use non-spec "private" term)
2129 "fixedbugs/bug176.go", // types2 reports all errors (pref: types2)
2130 "fixedbugs/bug195.go", // types2 reports slightly different (but correct) bugs
2131 "fixedbugs/bug228.go", // types2 doesn't run when there are syntax errors
2132 "fixedbugs/bug231.go", // types2 bug? (same error reported twice)
2133 "fixedbugs/bug255.go", // types2 reports extra errors
2134 "fixedbugs/bug374.go", // types2 reports extra errors
2135 "fixedbugs/bug388.go", // types2 not run due to syntax errors
2136 "fixedbugs/bug412.go", // types2 produces a follow-on error
2138 "fixedbugs/issue10700.go", // types2 reports ok hint, but does not match regexp
2139 "fixedbugs/issue11590.go", // types2 doesn't report a follow-on error (pref: types2)
2140 "fixedbugs/issue11610.go", // types2 not run after syntax errors
2141 "fixedbugs/issue11614.go", // types2 reports an extra error
2142 "fixedbugs/issue14520.go", // missing import path error by types2
2143 "fixedbugs/issue16428.go", // types2 reports two instead of one error
2144 "fixedbugs/issue17038.go", // types2 doesn't report a follow-on error (pref: types2)
2145 "fixedbugs/issue17645.go", // multiple errors on same line
2146 "fixedbugs/issue18331.go", // missing error about misuse of //go:noescape (irgen needs code from noder)
2147 "fixedbugs/issue18419.go", // types2 reports
2148 "fixedbugs/issue19012.go", // multiple errors on same line
2149 "fixedbugs/issue20233.go", // types2 reports two instead of one error (pref: compiler)
2150 "fixedbugs/issue20245.go", // types2 reports two instead of one error (pref: compiler)
2151 "fixedbugs/issue21979.go", // types2 doesn't report a follow-on error (pref: types2)
2152 "fixedbugs/issue23732.go", // types2 reports different (but ok) line numbers
2153 "fixedbugs/issue25958.go", // types2 doesn't report a follow-on error (pref: types2)
2154 "fixedbugs/issue28079b.go", // types2 reports follow-on errors
2155 "fixedbugs/issue28268.go", // types2 reports follow-on errors
2156 "fixedbugs/issue31053.go", // types2 reports "unknown field" instead of "cannot refer to unexported field"
2157 "fixedbugs/issue33460.go", // types2 reports alternative positions in separate error
2158 "fixedbugs/issue42058a.go", // types2 doesn't report "channel element type too large"
2159 "fixedbugs/issue42058b.go", // types2 doesn't report "channel element type too large"
2160 "fixedbugs/issue4232.go", // types2 reports (correct) extra errors
2161 "fixedbugs/issue4452.go", // types2 reports (correct) extra errors
2162 "fixedbugs/issue4510.go", // types2 reports different (but ok) line numbers
2163 "fixedbugs/issue47201.go", // types2 spells the error message differently
2164 "fixedbugs/issue5609.go", // types2 needs a better error message
2165 "fixedbugs/issue7525b.go", // types2 reports init cycle error on different line - ok otherwise
2166 "fixedbugs/issue7525c.go", // types2 reports init cycle error on different line - ok otherwise
2167 "fixedbugs/issue7525d.go", // types2 reports init cycle error on different line - ok otherwise
2168 "fixedbugs/issue7525e.go", // types2 reports init cycle error on different line - ok otherwise
2169 "fixedbugs/issue7525.go", // types2 reports init cycle error on different line - ok otherwise
2172 var types2Failures32Bit = setOf(
2173 "printbig.go", // large untyped int passed to print (32-bit)
2174 "fixedbugs/bug114.go", // large untyped int passed to println (32-bit)
2175 "fixedbugs/issue23305.go", // large untyped int passed to println (32-bit)
2176 "fixedbugs/bug385_32.go", // types2 doesn't produce missing error "type .* too large" (32-bit specific)
2179 var g3Failures = setOf(
2180 "writebarrier.go", // correct diagnostics, but different lines (probably irgen's fault)
2182 "fixedbugs/issue30862.go", // -G=3 doesn't handle //go:nointerface
2184 "typeparam/nested.go", // -G=3 doesn't support function-local types with generics
2186 "typeparam/mdempsky/4.go", // -G=3 can't export functions with labeled breaks in loops
2187 "typeparam/mdempsky/13.go", // problem with interface as as a type arg.
2188 "typeparam/mdempsky/15.go", // ICE in (*irgen).buildClosure
2191 var unifiedFailures = setOf(
2192 "closure3.go", // unified IR numbers closures differently than -d=inlfuncswithclosures
2193 "escape4.go", // unified IR can inline f5 and f6; test doesn't expect this
2194 "inline.go", // unified IR reports function literal diagnostics on different lines than -d=inlfuncswithclosures
2196 "fixedbugs/issue42284.go", // prints "T(0) does not escape", but test expects "a.I(a.T(0)) does not escape"
2197 "fixedbugs/issue7921.go", // prints "… escapes to heap", but test expects "string(…) escapes to heap"
2200 func setOf(keys ...string) map[string]bool {
2201 m := make(map[string]bool, len(keys))
2202 for _, key := range keys {
2208 // splitQuoted splits the string s around each instance of one or more consecutive
2209 // white space characters while taking into account quotes and escaping, and
2210 // returns an array of substrings of s or an empty list if s contains only white space.
2211 // Single quotes and double quotes are recognized to prevent splitting within the
2212 // quoted region, and are removed from the resulting substrings. If a quote in s
2213 // isn't closed err will be set and r will have the unclosed argument as the
2214 // last element. The backslash is used for escaping.
2216 // For example, the following string:
2218 // a b:"c d" 'e''f' "g\""
2220 // Would be parsed as:
2222 // []string{"a", "b:c d", "ef", `g"`}
2224 // [copied from src/go/build/build.go]
2225 func splitQuoted(s string) (r []string, err error) {
2227 arg := make([]rune, len(s))
2232 for _, rune := range s {
2239 case quote != '\x00':
2244 case rune == '"' || rune == '\'':
2248 case unicode.IsSpace(rune):
2249 if quoted || i > 0 {
2251 args = append(args, string(arg[:i]))
2259 if quoted || i > 0 {
2260 args = append(args, string(arg[:i]))
2263 err = errors.New("unclosed quote")
2265 err = errors.New("unfinished escaping")