1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
56
57
58
59 func defaultAllCodeGen() bool {
60
61
62
63
64 return strings.HasPrefix(testenv.Builder(), "gotip-linux-amd64")
65 }
66
67 var (
68
69 goTool string
70 goos string
71 goarch string
72 cgoEnabled bool
73 goExperiment string
74 goDebug string
75 tmpDir string
76
77
78
79 dirs = []string{".", "ken", "chan", "interface", "internal/runtime/sys", "syntax", "dwarf", "fixedbugs", "codegen", "abi", "typeparam", "typeparam/mdempsky", "arenas", "simd"}
80 )
81
82
83
84
85
86 func Test(t *testing.T) {
87 if *target != "" {
88
89
90
91
92
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
136
137
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
237
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
259 gorootTestDir string
260
261
262
263 runoutputGate chan bool
264 }
265
266
267 type test struct {
268 testCommon
269 *testing.T
270
271
272 dir, goFile string
273 }
274
275
276
277 func (t test) expectFail() bool {
278 failureSets := []map[string]bool{types2Failures}
279
280
281
282 switch goarch {
283 case "386", "arm", "mips", "mipsle":
284 failureSets = append(failureSets, types2Failures32Bit)
285 }
286
287 testName := path.Join(t.dir, t.goFile)
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
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
334 type goDirPkg struct {
335 name string
336 files []string
337 }
338
339
340
341
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
375
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
389
390
391
392
393
394
395
396
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
423
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
467
468
469
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
481
482
483
484
485
486
487
488
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
499
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
514 header, _, ok := strings.Cut(src, "\npackage")
515 if !ok {
516 header = action
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
537 switch action {
538 case "compile", "compiledir", "build", "builddir", "buildrundir", "run", "buildrun", "runoutput", "rundir", "runindir", "asmcheck":
539
540 case "errorcheckandrundir":
541 wantError = false
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
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":
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":
585 args = args[1:]
586 if goexp != "" {
587 goexp += ","
588 }
589 goexp += args[0]
590 runenv = append(runenv, "GOEXPERIMENT="+goexp)
591
592 case "-godebug":
593 args = args[1:]
594 if godebug != "" {
595 godebug += ","
596 }
597 godebug += args[0]
598 runenv = append(runenv, "GODEBUG="+godebug)
599
600 case "-gomodversion":
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
644 cmd.Env = append(os.Environ(), "GOENV=off", "GOFLAGS=", "TESTGO_EXPORT_ARCHIVE=1")
645 if runInDir != "" {
646 cmd.Dir = runInDir
647
648 cmd.Env = append(cmd.Env, "PWD="+cmd.Dir)
649 } else {
650
651 cmd.Dir = t.gorootTestDir
652
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
666
667
668
669
670
671
672
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
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
722
723 ops := t.wantedAsmOpcodes(long)
724 self := runtime.GOOS + "/" + runtime.GOARCH
725 var lastErr error
726 for _, env := range ops.Envs() {
727
728
729 if string(env) != self && !strings.HasPrefix(string(env), self+"/") && !*allCodegen {
730 continue
731 }
732
733 cmdline := []string{"build", "-gcflags", "-S=2"}
734
735
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
767 if err := t.asmCheck(buf.String(), long, env, ops[env]); err != nil {
768 lastErr = err
769 t.Log(err)
770 }
771 }
772 }
773
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
781
782
783
784 cmdline := []string{goTool, "tool", "compile", "-p=p", "-d=panic", "-C", "-e", "-importcfg=" + stdlibImportcfgFile(), "-o", "a.o"}
785
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
808 _, err := compileFile(runcmd, long, flags)
809 return err
810
811 case "compiledir":
812
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
828
829
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
835
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
866
867
868
869 longdir := filepath.Join(t.gorootTestDir, t.goDirName())
870 pkgs := goDirPackages(t.T, longdir, singlefilepkgs)
871
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
886
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
911
912
913
914
915
916
917
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
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
959
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
1030
1031
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
1053
1054
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
1060
1061
1062
1063
1064
1065
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
1091
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
1123
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
1167
1168
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
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
1194
1195
1196 var res []string
1197 for _, line := range strings.Split(out, "\n") {
1198 if strings.HasSuffix(line, "\r") {
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
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
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
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
1261
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
1280
1281
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
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
1327 for i := range lines {
1328 lines[i], _, _ = strings.Cut(lines[i], " // ERROR ")
1329 }
1330
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
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)
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
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
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
1385 exec.Command(goTool, "fmt", file).CombinedOutput()
1386 }
1387
1388
1389
1390
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
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))`)
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
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
1500
1501
1502
1503 reMatchCheck = `(-|[1-9]\d*)?(?:\x60[^\x60]*\x60|"(?:[^"\\]|\\.)*")`
1504 )
1505
1506 var (
1507
1508 rxAsmComment = regexp.MustCompile(`^\s*(.*?)\s*(?://\s*(.+)\s*)?$`)
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525 rxAsmPlatform = regexp.MustCompile(`(\w+)(/[\w.]+)?(/\w*)?\s*:\s*(` + reMatchCheck + `(?:[\s,]+` + reMatchCheck + `)*)`)
1526
1527
1528 rxAsmCheck = regexp.MustCompile(reMatchCheck)
1529
1530
1531
1532
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": {},
1544 "s390x": {},
1545 "wasm": {},
1546 "riscv64": {"GORISCV64", "rva20u64", "rva22u64", "rva23u64"},
1547 }
1548 )
1549
1550
1551 type wantedAsmOpcode struct {
1552 fileline string
1553 line int
1554 opcode *regexp.Regexp
1555 expected int
1556 actual int
1557 negative bool
1558 found bool
1559 }
1560
1561
1562
1563 type buildEnv string
1564
1565
1566
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
1580
1581
1582
1583 type asmChecks map[buildEnv]map[string][]wantedAsmOpcode
1584
1585
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
1610
1611 comment += " " + cmt
1612 if code == "" {
1613 continue
1614 }
1615
1616
1617
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] != "":
1626 os, arch, subarch = archspec[0], archspec[1][1:], archspec[2][1:]
1627 case archspec[1] != "":
1628 os, arch, subarch = "linux", archspec[0], archspec[1][1:]
1629 default:
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
1641 envs := make([]buildEnv, 0, 4)
1642 arches := []string{arch}
1643
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
1682
1683
1684
1685
1686
1687
1688
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
1710
1711
1712
1713
1714
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
1732
1733
1734
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
1743 if len(line) > 0 && line[0] != '\t' {
1744 functionMarkers = append(functionMarkers, nl)
1745 }
1746
1747
1748
1749 matches := rxLine.FindStringSubmatch(line)
1750 if len(matches) == 0 {
1751 continue
1752 }
1753 srcFileLine, asm := matches[1], matches[2]
1754
1755
1756 asm = strings.ReplaceAll(asm, "\t", " ")
1757
1758
1759
1760
1761 lineFuncMap[srcFileLine] = len(functionMarkers) - 1
1762
1763
1764
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
1780
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
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
1800
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
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
1820
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
1841 assert(shouldTest("// +build linux", "linux", "arm"))
1842 assert(shouldTest("// +build !windows", "linux", "arm"))
1843 assertNot(shouldTest("// +build !windows", "windows", "amd64"))
1844
1845
1846 assert(shouldTest("// This is a test.", "os", "arch"))
1847
1848
1849 assertNot(shouldTest("// +build arm 386", "linux", "amd64"))
1850
1851
1852 assertNot(shouldTest("// +build !windows,!plan9", "windows", "amd64"))
1853 assertNot(shouldTest("// +build !windows,!plan9", "plan9", "386"))
1854
1855
1856 assert(shouldTest("// +build !windows\n// +build amd64", "linux", "amd64"))
1857 assertNot(shouldTest("// +build !windows\n// +build amd64", "windows", "amd64"))
1858
1859
1860 assert(shouldTest("// +build !windows !plan9", "windows", "amd64"))
1861
1862
1863 assert(shouldTest("//go:build go1.4", "linux", "amd64"))
1864 }
1865
1866
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
1901
1902 if info.IsDir() {
1903 return os.MkdirAll(dstPath, perm|0200)
1904 }
1905
1906
1907 if err := os.Symlink(srcPath, dstPath); err == nil {
1908 return nil
1909 }
1910
1911
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
1932
1933
1934
1935
1936
1937 var types2Failures = setOf(
1938 "shift1.go",
1939 "fixedbugs/issue10700.go",
1940 "fixedbugs/issue18331.go",
1941 "fixedbugs/issue18419.go",
1942 "fixedbugs/issue20233.go",
1943 "fixedbugs/issue20245.go",
1944 "fixedbugs/issue31053.go",
1945 )
1946
1947 var types2Failures32Bit = setOf(
1948 "printbig.go",
1949 "fixedbugs/bug114.go",
1950 "fixedbugs/issue23305.go",
1951 )
1952
1953
1954
1955
1956
1957 var _ = setOf(
1958 "import1.go",
1959 "initializerr.go",
1960 "typecheck.go",
1961
1962 "fixedbugs/bug176.go",
1963 "fixedbugs/bug195.go",
1964 "fixedbugs/bug412.go",
1965
1966 "fixedbugs/issue11614.go",
1967 "fixedbugs/issue17038.go",
1968 "fixedbugs/issue23732.go",
1969 "fixedbugs/issue4510.go",
1970 "fixedbugs/issue7525b.go",
1971 "fixedbugs/issue7525c.go",
1972 "fixedbugs/issue7525d.go",
1973 "fixedbugs/issue7525e.go",
1974 "fixedbugs/issue7525.go",
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
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
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
2048
2049
2050
2051
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