run.go 44.7 KB
Newer Older
1
// skip
2

3
// Copyright 2012 The Go Authors. All rights reserved.
4 5 6 7 8 9 10 11 12 13 14
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Run runs tests in the test directory.
package main

import (
	"bytes"
	"errors"
	"flag"
	"fmt"
15 16
	"hash/fnv"
	"io"
17 18 19 20
	"io/ioutil"
	"log"
	"os"
	"os/exec"
21
	"path"
22 23 24 25 26 27
	"path/filepath"
	"regexp"
	"runtime"
	"sort"
	"strconv"
	"strings"
28
	"time"
29
	"unicode"
30 31 32
)

var (
33
	verbose        = flag.Bool("v", false, "verbose. if set, parallelism is set to 1.")
34
	keep           = flag.Bool("k", false, "keep. keep temporary directory.")
35 36 37
	numParallel    = flag.Int("n", runtime.NumCPU(), "number of parallel tests to run")
	summary        = flag.Bool("summary", false, "show summary of results")
	showSkips      = flag.Bool("show_skips", false, "show skipped tests")
38
	runSkips       = flag.Bool("run_skips", false, "run skipped tests (ignore skip and build tags)")
39
	linkshared     = flag.Bool("linkshared", false, "")
40
	updateErrors   = flag.Bool("update_errors", false, "update error messages in test file based on compiler output")
41
	runoutputLimit = flag.Int("l", defaultRunOutputLimit(), "number of parallel runoutput tests to run")
42 43 44

	shard  = flag.Int("shard", 0, "shard index to run. Only applicable if -shards is non-zero.")
	shards = flag.Int("shards", 0, "number of shards. If 0, all tests are run. This is used by the continuous build.")
45 46 47
)

var (
48
	goos, goarch string
49 50 51

	// dirs are the directories to look for *.go files in.
	// TODO(bradfitz): just use all directories?
52
	dirs = []string{".", "ken", "chan", "interface", "syntax", "dwarf", "fixedbugs", "codegen"}
53 54 55 56 57 58 59

	// ratec controls the max number of tests running at a time.
	ratec chan bool

	// toRun is the channel of tests to run.
	// It is nil until the first test is started.
	toRun chan *test
60 61 62 63

	// rungatec controls the max number of runoutput tests
	// executed in parallel as they can each consume a lot of memory.
	rungatec chan bool
64 65 66 67 68 69 70 71
)

// maxTests is an upper bound on the total number of tests.
// It is used as a channel buffer size to make sure sends don't block.
const maxTests = 5000

func main() {
	flag.Parse()
72

73 74 75
	goos = getenv("GOOS", runtime.GOOS)
	goarch = getenv("GOARCH", runtime.GOARCH)

76 77
	findExecCmd()

78 79 80
	// Disable parallelism if printing or if using a simulator.
	if *verbose || len(findExecCmd()) > 0 {
		*numParallel = 1
81
		*runoutputLimit = 1
82 83
	}

84
	ratec = make(chan bool, *numParallel)
85
	rungatec = make(chan bool, *runoutputLimit)
86 87 88 89 90

	var tests []*test
	if flag.NArg() > 0 {
		for _, arg := range flag.Args() {
			if arg == "-" || arg == "--" {
91
				// Permit running:
92 93
				// $ go run run.go - env.go
				// $ go run run.go -- env.go
94 95
				// $ go run run.go - ./fixedbugs
				// $ go run run.go -- ./fixedbugs
96 97
				continue
			}
98 99 100 101 102 103 104 105 106
			if fi, err := os.Stat(arg); err == nil && fi.IsDir() {
				for _, baseGoFile := range goFiles(arg) {
					tests = append(tests, startTest(arg, baseGoFile))
				}
			} else if strings.HasSuffix(arg, ".go") {
				dir, file := filepath.Split(arg)
				tests = append(tests, startTest(dir, file))
			} else {
				log.Fatalf("can't yet deal with non-directory and non-go file %q", arg)
107 108 109 110 111 112 113 114 115 116 117 118 119
			}
		}
	} else {
		for _, dir := range dirs {
			for _, baseGoFile := range goFiles(dir) {
				tests = append(tests, startTest(dir, baseGoFile))
			}
		}
	}

	failed := false
	resCount := map[string]int{}
	for _, test := range tests {
David du Colombier's avatar
David du Colombier committed
120
		<-test.donec
121 122
		status := "ok  "
		errStr := ""
Keith Randall's avatar
Keith Randall committed
123
		if e, isSkip := test.err.(skipError); isSkip {
124
			test.err = nil
Keith Randall's avatar
Keith Randall committed
125
			errStr = "unexpected skip for " + path.Join(test.dir, test.gofile) + ": " + string(e)
126
			status = "FAIL"
127
		}
128
		if test.err != nil {
129
			status = "FAIL"
130 131
			errStr = test.err.Error()
		}
132
		if status == "FAIL" {
133 134
			failed = true
		}
135 136 137 138 139 140
		resCount[status]++
		dt := fmt.Sprintf("%.3fs", test.dt.Seconds())
		if status == "FAIL" {
			fmt.Printf("# go run run.go -- %s\n%s\nFAIL\t%s\t%s\n",
				path.Join(test.dir, test.gofile),
				errStr, test.goFileName(), dt)
141
			continue
142
		}
143 144 145 146
		if !*verbose {
			continue
		}
		fmt.Printf("%s\t%s\t%s\n", status, test.goFileName(), dt)
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
	}

	if *summary {
		for k, v := range resCount {
			fmt.Printf("%5d %s\n", v, k)
		}
	}

	if failed {
		os.Exit(1)
	}
}

func toolPath(name string) string {
	p := filepath.Join(os.Getenv("GOROOT"), "bin", "tool", name)
	if _, err := os.Stat(p); err != nil {
		log.Fatalf("didn't find binary at %s", p)
	}
	return p
}

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
// goTool reports the path of the go tool to use to run the tests.
// If possible, use the same Go used to run run.go, otherwise
// fallback to the go version found in the PATH.
func goTool() string {
	var exeSuffix string
	if runtime.GOOS == "windows" {
		exeSuffix = ".exe"
	}
	path := filepath.Join(runtime.GOROOT(), "bin", "go"+exeSuffix)
	if _, err := os.Stat(path); err == nil {
		return path
	}
	// Just run "go" from PATH
	return "go"
}

184 185 186 187 188 189 190 191 192
func shardMatch(name string) bool {
	if *shards == 0 {
		return true
	}
	h := fnv.New32()
	io.WriteString(h, name)
	return int(h.Sum32()%uint32(*shards)) == *shard
}

193 194 195 196 197 198 199
func goFiles(dir string) []string {
	f, err := os.Open(dir)
	check(err)
	dirnames, err := f.Readdirnames(-1)
	check(err)
	names := []string{}
	for _, name := range dirnames {
200
		if !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") && shardMatch(name) {
201 202 203 204 205 206 207
			names = append(names, name)
		}
	}
	sort.Strings(names)
	return names
}

208 209
type runCmd func(...string) ([]byte, error)

210
func compileFile(runcmd runCmd, longname string, flags []string) (out []byte, err error) {
211
	cmd := []string{goTool(), "tool", "compile", "-e"}
212
	cmd = append(cmd, flags...)
213 214 215 216 217
	if *linkshared {
		cmd = append(cmd, "-dynlink", "-installsuffix=dynlink")
	}
	cmd = append(cmd, longname)
	return runcmd(cmd...)
218 219
}

220 221 222 223 224 225
func compileInDir(runcmd runCmd, dir string, flags []string, localImports bool, names ...string) (out []byte, err error) {
	cmd := []string{goTool(), "tool", "compile", "-e"}
	if localImports {
		// Set relative path for local imports and import search path to current dir.
		cmd = append(cmd, "-D", ".", "-I", ".")
	}
226
	cmd = append(cmd, flags...)
227 228 229
	if *linkshared {
		cmd = append(cmd, "-dynlink", "-installsuffix=dynlink")
	}
230 231 232 233
	for _, name := range names {
		cmd = append(cmd, filepath.Join(dir, name))
	}
	return runcmd(cmd...)
234 235 236
}

func linkFile(runcmd runCmd, goname string) (err error) {
237
	pfile := strings.Replace(goname, ".go", ".o", -1)
238
	cmd := []string{goTool(), "tool", "link", "-w", "-o", "a.exe", "-L", "."}
239 240 241 242 243
	if *linkshared {
		cmd = append(cmd, "-linkshared", "-installsuffix=dynlink")
	}
	cmd = append(cmd, pfile)
	_, err = runcmd(cmd...)
244 245 246
	return
}

247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
// skipError describes why a test was skipped.
type skipError string

func (s skipError) Error() string { return string(s) }

func check(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

// test holds the state of a test.
type test struct {
	dir, gofile string
	donec       chan bool // closed when done
David du Colombier's avatar
David du Colombier committed
262 263
	dt          time.Duration

264
	src string
265 266 267 268 269

	tempDir string
	err     error
}

270
// startTest
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
func startTest(dir, gofile string) *test {
	t := &test{
		dir:    dir,
		gofile: gofile,
		donec:  make(chan bool, 1),
	}
	if toRun == nil {
		toRun = make(chan *test, maxTests)
		go runTests()
	}
	select {
	case toRun <- t:
	default:
		panic("toRun buffer size (maxTests) is too small")
	}
	return t
}

// runTests runs tests in parallel, but respecting the order they
// were enqueued on the toRun channel.
func runTests() {
	for {
		ratec <- true
		t := <-toRun
		go func() {
			t.run()
			<-ratec
		}()
	}
}

Russ Cox's avatar
Russ Cox committed
302 303
var cwd, _ = os.Getwd()

304 305 306 307
func (t *test) goFileName() string {
	return filepath.Join(t.dir, t.gofile)
}

308 309 310 311
func (t *test) goDirName() string {
	return filepath.Join(t.dir, strings.Replace(t.gofile, ".go", ".dir", -1))
}

312 313 314 315 316 317 318 319 320 321 322 323 324
func goDirFiles(longdir string) (filter []os.FileInfo, err error) {
	files, dirErr := ioutil.ReadDir(longdir)
	if dirErr != nil {
		return nil, dirErr
	}
	for _, gofile := range files {
		if filepath.Ext(gofile.Name()) == ".go" {
			filter = append(filter, gofile)
		}
	}
	return
}

325
var packageRE = regexp.MustCompile(`(?m)^package ([\p{Lu}\p{Ll}\w]+)`)
326

327 328 329
// If singlefilepkgs is set, each file is considered a separate package
// even if the package names are the same.
func goDirPackages(longdir string, singlefilepkgs bool) ([][]string, error) {
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
	files, err := goDirFiles(longdir)
	if err != nil {
		return nil, err
	}
	var pkgs [][]string
	m := make(map[string]int)
	for _, file := range files {
		name := file.Name()
		data, err := ioutil.ReadFile(filepath.Join(longdir, name))
		if err != nil {
			return nil, err
		}
		pkgname := packageRE.FindStringSubmatch(string(data))
		if pkgname == nil {
			return nil, fmt.Errorf("cannot find package name in %s", name)
		}
		i, ok := m[pkgname[1]]
347
		if singlefilepkgs || !ok {
348 349 350 351 352 353 354 355
			i = len(pkgs)
			pkgs = append(pkgs, nil)
			m[pkgname[1]] = i
		}
		pkgs[i] = append(pkgs[i], name)
	}
	return pkgs, nil
}
356

357
type context struct {
358 359 360
	GOOS     string
	GOARCH   string
	noOptEnv bool
361 362
}

363 364 365
// shouldTest looks for build tags in a source file and returns
// whether the file should be used according to the tags.
func shouldTest(src string, goos, goarch string) (ok bool, whyNot string) {
366 367 368
	if *runSkips {
		return true, ""
	}
369 370 371 372 373 374 375 376 377 378 379
	for _, line := range strings.Split(src, "\n") {
		line = strings.TrimSpace(line)
		if strings.HasPrefix(line, "//") {
			line = line[2:]
		} else {
			continue
		}
		line = strings.TrimSpace(line)
		if len(line) == 0 || line[0] != '+' {
			continue
		}
380
		gcFlags := os.Getenv("GO_GCFLAGS")
381
		ctxt := &context{
382 383 384
			GOOS:     goos,
			GOARCH:   goarch,
			noOptEnv: strings.Contains(gcFlags, "-N") || strings.Contains(gcFlags, "-l"),
385
		}
386

387 388
		words := strings.Fields(line)
		if words[0] == "+build" {
389 390 391 392 393
			ok := false
			for _, word := range words[1:] {
				if ctxt.match(word) {
					ok = true
					break
394 395
				}
			}
396 397 398 399
			if !ok {
				// no matching tag found.
				return false, line
			}
400 401
		}
	}
402
	// no build tags
403 404 405
	return true, ""
}

406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
func (ctxt *context) match(name string) bool {
	if name == "" {
		return false
	}
	if i := strings.Index(name, ","); i >= 0 {
		// comma-separated list
		return ctxt.match(name[:i]) && ctxt.match(name[i+1:])
	}
	if strings.HasPrefix(name, "!!") { // bad syntax, reject always
		return false
	}
	if strings.HasPrefix(name, "!") { // negation
		return len(name) > 1 && !ctxt.match(name[1:])
	}

	// Tags must be letters, digits, underscores or dots.
	// Unlike in Go identifiers, all digits are fine (e.g., "386").
	for _, c := range name {
		if !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != '_' && c != '.' {
			return false
		}
	}

	if name == ctxt.GOOS || name == ctxt.GOARCH {
		return true
	}

433 434 435 436
	if ctxt.noOptEnv && name == "gcflags_noopt" {
		return true
	}

Russ Cox's avatar
Russ Cox committed
437 438 439 440
	if name == "test_run" {
		return true
	}

441 442 443
	return false
}

444 445
func init() { checkShouldTest() }

446
// goGcflags returns the -gcflags argument to use with go build / go run.
447
// This must match the flags used for building the standard library,
448 449 450 451 452 453
// or else the commands will rebuild any needed packages (like runtime)
// over and over.
func goGcflags() string {
	return "-gcflags=" + os.Getenv("GO_GCFLAGS")
}

454 455
// run runs a test.
func (t *test) run() {
456 457 458 459 460
	start := time.Now()
	defer func() {
		t.dt = time.Since(start)
		close(t.donec)
	}()
461 462 463 464 465 466 467 468 469 470 471

	srcBytes, err := ioutil.ReadFile(t.goFileName())
	if err != nil {
		t.err = err
		return
	}
	t.src = string(srcBytes)
	if t.src[0] == '\n' {
		t.err = skipError("starts with newline")
		return
	}
472 473

	// Execution recipe stops at first blank line.
474 475 476 477 478 479
	pos := strings.Index(t.src, "\n\n")
	if pos == -1 {
		t.err = errors.New("double newline not found")
		return
	}
	action := t.src[:pos]
480 481 482 483
	if nl := strings.Index(action, "\n"); nl >= 0 && strings.Contains(action[:nl], "+build") {
		// skip first line
		action = action[nl+1:]
	}
484 485 486
	if strings.HasPrefix(action, "//") {
		action = action[2:]
	}
Russ Cox's avatar
Russ Cox committed
487

488 489 490 491 492 493 494
	// Check for build constraints only up to the actual code.
	pkgPos := strings.Index(t.src, "\npackage")
	if pkgPos == -1 {
		pkgPos = pos // some files are intentionally malformed
	}
	if ok, why := shouldTest(t.src[:pkgPos], goos, goarch); !ok {
		if *showSkips {
495
			fmt.Printf("%-20s %-20s: %s\n", "skip", t.goFileName(), why)
496 497 498 499
		}
		return
	}

500
	var args, flags []string
501
	var tim int
502
	wantError := false
503
	wantAuto := false
504
	singlefilepkgs := false
505
	localImports := true
Russ Cox's avatar
Russ Cox committed
506 507 508 509 510
	f := strings.Fields(action)
	if len(f) > 0 {
		action = f[0]
		args = f[1:]
	}
511

512
	// TODO: Clean up/simplify this switch statement.
513
	switch action {
514
	case "compile", "compiledir", "build", "builddir", "buildrundir", "run", "buildrun", "runoutput", "rundir", "asmcheck":
515
		// nothing to do
516 517
	case "errorcheckandrundir":
		wantError = false // should be no error if also will run
518 519 520 521
	case "errorcheckwithauto":
		action = "errorcheck"
		wantAuto = true
		wantError = true
522
	case "errorcheck", "errorcheckdir", "errorcheckoutput":
523
		wantError = true
524
	case "skip":
525 526 527
		if *runSkips {
			break
		}
528
		return
529 530 531 532 533
	default:
		t.err = skipError("skipped; unknown pattern: " + action)
		return
	}

534 535 536
	// collect flags
	for len(args) > 0 && strings.HasPrefix(args[0], "-") {
		switch args[0] {
537 538
		case "-1":
			wantError = true
539 540 541 542
		case "-0":
			wantError = false
		case "-s":
			singlefilepkgs = true
543 544 545 546 547 548
		case "-n":
			// Do not set relative path for local imports to current dir,
			// e.g. do not pass -D . -I . to the compiler.
			// Used in fixedbugs/bug345.go to allow compilation and import of local pkg.
			// See golang.org/issue/25635
			localImports = false
549 550 551 552 553 554 555 556
		case "-t": // timeout in seconds
			args = args[1:]
			var err error
			tim, err = strconv.Atoi(args[0])
			if err != nil {
				t.err = fmt.Errorf("need number of seconds for -t timeout, got %s instead", args[0])
			}

557 558 559 560 561
		default:
			flags = append(flags, args[0])
		}
		args = args[1:]
	}
562 563 564 565 566 567 568 569 570 571 572 573 574
	if action == "errorcheck" {
		found := false
		for i, f := range flags {
			if strings.HasPrefix(f, "-d=") {
				flags[i] = f + ",ssa/check/on"
				found = true
				break
			}
		}
		if !found {
			flags = append(flags, "-d=ssa/check/on")
		}
	}
575

576
	t.makeTempDir()
577 578 579
	if !*keep {
		defer os.RemoveAll(t.tempDir)
	}
580 581 582

	err = ioutil.WriteFile(filepath.Join(t.tempDir, t.gofile), srcBytes, 0644)
	check(err)
Russ Cox's avatar
Russ Cox committed
583

Russ Cox's avatar
Russ Cox committed
584
	// A few tests (of things like the environment) require these to be set.
585 586 587 588 589 590
	if os.Getenv("GOOS") == "" {
		os.Setenv("GOOS", runtime.GOOS)
	}
	if os.Getenv("GOARCH") == "" {
		os.Setenv("GOARCH", runtime.GOARCH)
	}
Russ Cox's avatar
Russ Cox committed
591

Russ Cox's avatar
Russ Cox committed
592 593 594 595 596 597 598 599
	useTmp := true
	runcmd := func(args ...string) ([]byte, error) {
		cmd := exec.Command(args[0], args[1:]...)
		var buf bytes.Buffer
		cmd.Stdout = &buf
		cmd.Stderr = &buf
		if useTmp {
			cmd.Dir = t.tempDir
600
			cmd.Env = envForDir(cmd.Dir)
601 602 603
		} else {
			cmd.Env = os.Environ()
		}
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628

		var err error

		if tim != 0 {
			err = cmd.Start()
			// This command-timeout code adapted from cmd/go/test.go
			if err == nil {
				tick := time.NewTimer(time.Duration(tim) * time.Second)
				done := make(chan error)
				go func() {
					done <- cmd.Wait()
				}()
				select {
				case err = <-done:
					// ok
				case <-tick.C:
					cmd.Process.Kill()
					err = <-done
					// err = errors.New("Test timeout")
				}
				tick.Stop()
			}
		} else {
			err = cmd.Run()
		}
629 630 631
		if err != nil {
			err = fmt.Errorf("%s\n%s", err, buf.Bytes())
		}
Russ Cox's avatar
Russ Cox committed
632
		return buf.Bytes(), err
633 634
	}

Russ Cox's avatar
Russ Cox committed
635
	long := filepath.Join(cwd, t.goFileName())
Russ Cox's avatar
Russ Cox committed
636
	switch action {
Russ Cox's avatar
Russ Cox committed
637 638
	default:
		t.err = fmt.Errorf("unimplemented action %q", action)
639

640
	case "asmcheck":
641 642
		// Compile Go file and match the generated assembly
		// against a set of regexps in comments.
643 644
		ops := t.wantedAsmOpcodes(long)
		for _, env := range ops.Envs() {
645 646
			// -S=2 forces outermost line numbers when disassembling inlined code.
			cmdline := []string{"build", "-gcflags", "-S=2"}
647 648
			cmdline = append(cmdline, flags...)
			cmdline = append(cmdline, long)
649
			cmd := exec.Command(goTool(), cmdline...)
650
			cmd.Env = append(os.Environ(), env.Environ()...)
651 652 653 654

			var buf bytes.Buffer
			cmd.Stdout, cmd.Stderr = &buf, &buf
			if err := cmd.Run(); err != nil {
655
				fmt.Println(env, "\n", cmd.Stderr)
656 657 658
				t.err = err
				return
			}
659

660
			t.err = t.asmCheck(buf.String(), long, env, ops[env])
661 662 663 664 665 666
			if t.err != nil {
				return
			}
		}
		return

Russ Cox's avatar
Russ Cox committed
667
	case "errorcheck":
668 669 670
		// Compile Go file.
		// Fail if wantError is true and compilation was successful and vice versa.
		// Match errors produced by gc against errors in comments.
671
		// TODO(gri) remove need for -C (disable printing of columns in error messages)
672
		cmdline := []string{goTool(), "tool", "compile", "-C", "-e", "-o", "a.o"}
673
		// No need to add -dynlink even if linkshared if we're just checking for errors...
674 675 676 677 678 679 680 681 682 683
		cmdline = append(cmdline, flags...)
		cmdline = append(cmdline, long)
		out, err := runcmd(cmdline...)
		if wantError {
			if err == nil {
				t.err = fmt.Errorf("compilation succeeded unexpectedly\n%s", out)
				return
			}
		} else {
			if err != nil {
684
				t.err = err
685 686 687
				return
			}
		}
688 689 690
		if *updateErrors {
			t.updateErrors(string(out), long)
		}
691
		t.err = t.errorCheck(string(out), wantAuto, long, t.gofile)
692
		return
Russ Cox's avatar
Russ Cox committed
693

Russ Cox's avatar
Russ Cox committed
694
	case "compile":
695
		// Compile Go file.
696
		_, t.err = compileFile(runcmd, long, flags)
Russ Cox's avatar
Russ Cox committed
697

698
	case "compiledir":
699
		// Compile all files in the directory as packages in lexicographic order.
700
		longdir := filepath.Join(cwd, t.goDirName())
701
		pkgs, err := goDirPackages(longdir, singlefilepkgs)
702 703
		if err != nil {
			t.err = err
704 705
			return
		}
706
		for _, gofiles := range pkgs {
707
			_, t.err = compileInDir(runcmd, longdir, flags, localImports, gofiles...)
708 709
			if t.err != nil {
				return
710
			}
711 712
		}

713
	case "errorcheckdir", "errorcheckandrundir":
714 715 716
		// Compile and errorCheck all files in the directory as packages in lexicographic order.
		// If errorcheckdir and wantError, compilation of the last package must fail.
		// If errorcheckandrundir and wantError, compilation of the package prior the last must fail.
717
		longdir := filepath.Join(cwd, t.goDirName())
718
		pkgs, err := goDirPackages(longdir, singlefilepkgs)
719 720 721 722
		if err != nil {
			t.err = err
			return
		}
723 724 725 726 727 728
		errPkg := len(pkgs) - 1
		if wantError && action == "errorcheckandrundir" {
			// The last pkg should compiled successfully and will be run in next case.
			// Preceding pkg must return an error from compileInDir.
			errPkg--
		}
729
		for i, gofiles := range pkgs {
730
			out, err := compileInDir(runcmd, longdir, flags, localImports, gofiles...)
731
			if i == errPkg {
732 733 734 735 736 737 738 739 740 741 742
				if wantError && err == nil {
					t.err = fmt.Errorf("compilation succeeded unexpectedly\n%s", out)
					return
				} else if !wantError && err != nil {
					t.err = err
					return
				}
			} else if err != nil {
				t.err = err
				return
			}
743 744 745 746
			var fullshort []string
			for _, name := range gofiles {
				fullshort = append(fullshort, filepath.Join(longdir, name), name)
			}
747
			t.err = t.errorCheck(string(out), wantAuto, fullshort...)
748
			if t.err != nil {
749 750 751
				break
			}
		}
752 753 754 755
		if action == "errorcheckdir" {
			return
		}
		fallthrough
756

757
	case "rundir":
758 759 760 761
		// Compile all files in the directory as packages in lexicographic order.
		// In case of errorcheckandrundir, ignore failed compilation of the package before the last.
		// Link as if the last file is the main package, run it.
		// Verify the expected output.
762
		longdir := filepath.Join(cwd, t.goDirName())
763
		pkgs, err := goDirPackages(longdir, singlefilepkgs)
764 765 766 767
		if err != nil {
			t.err = err
			return
		}
768
		for i, gofiles := range pkgs {
769
			_, err := compileInDir(runcmd, longdir, flags, localImports, gofiles...)
770 771 772
			// Allow this package compilation fail based on conditions below;
			// its errors were checked in previous case.
			if err != nil && !(wantError && action == "errorcheckandrundir" && i == len(pkgs)-2) {
773 774 775
				t.err = err
				return
			}
776 777 778 779 780 781
			if i == len(pkgs)-1 {
				err = linkFile(runcmd, gofiles[0])
				if err != nil {
					t.err = err
					return
				}
782 783 784 785 786
				var cmd []string
				cmd = append(cmd, findExecCmd()...)
				cmd = append(cmd, filepath.Join(t.tempDir, "a.exe"))
				cmd = append(cmd, args...)
				out, err := runcmd(cmd...)
787 788 789 790 791 792 793 794
				if err != nil {
					t.err = err
					return
				}
				if strings.Replace(string(out), "\r\n", "\n", -1) != t.expectedOutput() {
					t.err = fmt.Errorf("incorrect output\n%s", out)
				}
			}
795 796
		}

Russ Cox's avatar
Russ Cox committed
797
	case "build":
798
		// Build Go file.
799
		_, err := runcmd(goTool(), "build", goGcflags(), "-o", "a.exe", long)
Russ Cox's avatar
Russ Cox committed
800
		if err != nil {
801
			t.err = err
802
		}
Russ Cox's avatar
Russ Cox committed
803

804
	case "builddir", "buildrundir":
805
		// Build an executable from all the .go and .s files in a subdirectory.
806
		// Run it and verify its output in the buildrundir case.
807 808 809 810 811 812
		longdir := filepath.Join(cwd, t.goDirName())
		files, dirErr := ioutil.ReadDir(longdir)
		if dirErr != nil {
			t.err = dirErr
			break
		}
813 814
		var gos []string
		var asms []string
815 816 817
		for _, file := range files {
			switch filepath.Ext(file.Name()) {
			case ".go":
818
				gos = append(gos, filepath.Join(longdir, file.Name()))
819
			case ".s":
820
				asms = append(asms, filepath.Join(longdir, file.Name()))
821 822 823
			}

		}
824
		if len(asms) > 0 {
825 826
			emptyHdrFile := filepath.Join(t.tempDir, "go_asm.h")
			if err := ioutil.WriteFile(emptyHdrFile, nil, 0666); err != nil {
827 828 829
				t.err = fmt.Errorf("write empty go_asm.h: %s", err)
				return
			}
830
			cmd := []string{goTool(), "tool", "asm", "-gensymabis", "-o", "symabis"}
831 832 833 834 835 836 837
			cmd = append(cmd, asms...)
			_, err = runcmd(cmd...)
			if err != nil {
				t.err = err
				break
			}
		}
838
		var objs []string
839
		cmd := []string{goTool(), "tool", "compile", "-e", "-D", ".", "-I", ".", "-o", "go.o"}
840
		if len(asms) > 0 {
841
			cmd = append(cmd, "-asmhdr", "go_asm.h", "-symabis", "symabis")
842
		}
843
		cmd = append(cmd, gos...)
844 845 846 847 848 849 850
		_, err := runcmd(cmd...)
		if err != nil {
			t.err = err
			break
		}
		objs = append(objs, "go.o")
		if len(asms) > 0 {
851
			cmd = []string{goTool(), "tool", "asm", "-e", "-I", ".", "-o", "asm.o"}
852
			cmd = append(cmd, asms...)
853 854 855 856 857 858 859
			_, err = runcmd(cmd...)
			if err != nil {
				t.err = err
				break
			}
			objs = append(objs, "asm.o")
		}
860
		cmd = []string{goTool(), "tool", "pack", "c", "all.a"}
861 862 863 864 865 866
		cmd = append(cmd, objs...)
		_, err = runcmd(cmd...)
		if err != nil {
			t.err = err
			break
		}
867
		cmd = []string{goTool(), "tool", "link", "-o", "a.exe", "all.a"}
868 869 870 871 872
		_, err = runcmd(cmd...)
		if err != nil {
			t.err = err
			break
		}
873 874 875 876 877 878 879 880 881 882 883
		if action == "buildrundir" {
			cmd = append(findExecCmd(), filepath.Join(t.tempDir, "a.exe"))
			out, err := runcmd(cmd...)
			if err != nil {
				t.err = err
				break
			}
			if strings.Replace(string(out), "\r\n", "\n", -1) != t.expectedOutput() {
				t.err = fmt.Errorf("incorrect output\n%s", out)
			}
		}
884

885 886 887
	case "buildrun":
		// Build an executable from Go file, then run it, verify its output.
		// Useful for timeout tests where failure mode is infinite loop.
888
		// TODO: not supported on NaCl
889
		cmd := []string{goTool(), "build", goGcflags(), "-o", "a.exe"}
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
		if *linkshared {
			cmd = append(cmd, "-linkshared")
		}
		longdirgofile := filepath.Join(filepath.Join(cwd, t.dir), t.gofile)
		cmd = append(cmd, flags...)
		cmd = append(cmd, longdirgofile)
		out, err := runcmd(cmd...)
		if err != nil {
			t.err = err
			return
		}
		cmd = []string{"./a.exe"}
		out, err = runcmd(append(cmd, args...)...)
		if err != nil {
			t.err = err
			return
		}

		if strings.Replace(string(out), "\r\n", "\n", -1) != t.expectedOutput() {
			t.err = fmt.Errorf("incorrect output\n%s", out)
		}

Russ Cox's avatar
Russ Cox committed
912
	case "run":
913 914 915
		// Run Go file if no special go command flags are provided;
		// otherwise build an executable and run it.
		// Verify the output.
Todd Neal's avatar
Todd Neal committed
916
		useTmp = false
917 918 919 920 921 922 923 924 925 926 927
		var out []byte
		var err error
		if len(flags)+len(args) == 0 && goGcflags() == "" && !*linkshared {
			// If we're not using special go command flags,
			// skip all the go command machinery.
			// This avoids any time the go command would
			// spend checking whether, for example, the installed
			// package runtime is up to date.
			// Because we run lots of trivial test programs,
			// the time adds up.
			pkg := filepath.Join(t.tempDir, "pkg.a")
928
			if _, err := runcmd(goTool(), "tool", "compile", "-o", pkg, t.goFileName()); err != nil {
929 930 931 932
				t.err = err
				return
			}
			exe := filepath.Join(t.tempDir, "test.exe")
933
			cmd := []string{goTool(), "tool", "link", "-s", "-w"}
934 935 936 937 938 939 940
			cmd = append(cmd, "-o", exe, pkg)
			if _, err := runcmd(cmd...); err != nil {
				t.err = err
				return
			}
			out, err = runcmd(append([]string{exe}, args...)...)
		} else {
941
			cmd := []string{goTool(), "run", goGcflags()}
942 943 944 945 946 947
			if *linkshared {
				cmd = append(cmd, "-linkshared")
			}
			cmd = append(cmd, flags...)
			cmd = append(cmd, t.goFileName())
			out, err = runcmd(append(cmd, args...)...)
948
		}
949
		if err != nil {
950
			t.err = err
951
			return
952
		}
953
		if strings.Replace(string(out), "\r\n", "\n", -1) != t.expectedOutput() {
Russ Cox's avatar
Russ Cox committed
954
			t.err = fmt.Errorf("incorrect output\n%s", out)
955
		}
956 957

	case "runoutput":
958 959
		// Run Go file and write its output into temporary Go file.
		// Run generated Go file and verify its output.
960 961 962 963
		rungatec <- true
		defer func() {
			<-rungatec
		}()
964
		useTmp = false
965
		cmd := []string{goTool(), "run", goGcflags()}
966 967 968 969 970
		if *linkshared {
			cmd = append(cmd, "-linkshared")
		}
		cmd = append(cmd, t.goFileName())
		out, err := runcmd(append(cmd, args...)...)
971
		if err != nil {
972
			t.err = err
973
			return
974 975
		}
		tfile := filepath.Join(t.tempDir, "tmp__.go")
976
		if err := ioutil.WriteFile(tfile, out, 0666); err != nil {
977 978 979
			t.err = fmt.Errorf("write tempfile:%s", err)
			return
		}
980
		cmd = []string{goTool(), "run", goGcflags()}
981 982 983 984 985
		if *linkshared {
			cmd = append(cmd, "-linkshared")
		}
		cmd = append(cmd, tfile)
		out, err = runcmd(cmd...)
986
		if err != nil {
987
			t.err = err
988
			return
989 990 991 992
		}
		if string(out) != t.expectedOutput() {
			t.err = fmt.Errorf("incorrect output\n%s", out)
		}
993 994

	case "errorcheckoutput":
995 996
		// Run Go file and write its output into temporary Go file.
		// Compile and errorCheck generated Go file.
997
		useTmp = false
998
		cmd := []string{goTool(), "run", goGcflags()}
999 1000 1001 1002 1003
		if *linkshared {
			cmd = append(cmd, "-linkshared")
		}
		cmd = append(cmd, t.goFileName())
		out, err := runcmd(append(cmd, args...)...)
1004 1005
		if err != nil {
			t.err = err
1006
			return
1007 1008 1009 1010 1011 1012 1013
		}
		tfile := filepath.Join(t.tempDir, "tmp__.go")
		err = ioutil.WriteFile(tfile, out, 0666)
		if err != nil {
			t.err = fmt.Errorf("write tempfile:%s", err)
			return
		}
1014
		cmdline := []string{goTool(), "tool", "compile", "-e", "-o", "a.o"}
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
		cmdline = append(cmdline, flags...)
		cmdline = append(cmdline, tfile)
		out, err = runcmd(cmdline...)
		if wantError {
			if err == nil {
				t.err = fmt.Errorf("compilation succeeded unexpectedly\n%s", out)
				return
			}
		} else {
			if err != nil {
				t.err = err
				return
			}
		}
1029
		t.err = t.errorCheck(string(out), false, tfile, "tmp__.go")
1030
		return
1031 1032 1033
	}
}

1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
var execCmd []string

func findExecCmd() []string {
	if execCmd != nil {
		return execCmd
	}
	execCmd = []string{} // avoid work the second time
	if goos == runtime.GOOS && goarch == runtime.GOARCH {
		return execCmd
	}
	path, err := exec.LookPath(fmt.Sprintf("go_%s_%s_exec", goos, goarch))
	if err == nil {
		execCmd = []string{path}
	}
	return execCmd
David du Colombier's avatar
David du Colombier committed
1049
}
1050

1051 1052 1053 1054 1055 1056 1057 1058
func (t *test) String() string {
	return filepath.Join(t.dir, t.gofile)
}

func (t *test) makeTempDir() {
	var err error
	t.tempDir, err = ioutil.TempDir("", "")
	check(err)
1059 1060 1061
	if *keep {
		log.Printf("Temporary directory is %s", t.tempDir)
	}
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
}

func (t *test) expectedOutput() string {
	filename := filepath.Join(t.dir, t.gofile)
	filename = filename[:len(filename)-len(".go")]
	filename += ".out"
	b, _ := ioutil.ReadFile(filename)
	return string(b)
}

1072
func splitOutput(out string, wantAuto bool) []string {
1073
	// gc error messages continue onto additional lines with leading tabs.
1074
	// Split the output at the beginning of each line that doesn't begin with a tab.
1075
	// <autogenerated> lines are impossible to match so those are filtered out.
1076 1077
	var res []string
	for _, line := range strings.Split(out, "\n") {
1078
		if strings.HasSuffix(line, "\r") { // remove '\r', output by compiler on windows
1079 1080
			line = line[:len(line)-1]
		}
1081
		if strings.HasPrefix(line, "\t") {
1082
			res[len(res)-1] += "\n" + line
1083
		} else if strings.HasPrefix(line, "go tool") || strings.HasPrefix(line, "#") || !wantAuto && strings.HasPrefix(line, "<autogenerated>") {
1084 1085
			continue
		} else if strings.TrimSpace(line) != "" {
1086
			res = append(res, line)
1087 1088
		}
	}
1089 1090 1091
	return res
}

1092 1093 1094 1095 1096 1097 1098
// errorCheck matches errors in outStr against comments in source files.
// For each line of the source files which should generate an error,
// there should be a comment of the form // ERROR "regexp".
// If outStr has an error for a line which has no such comment,
// this function will report an error.
// Likewise if outStr does not have an error for a line which has a comment,
// or if the error message does not match the <regexp>.
1099
// The <regexp> syntax is Perl but it's best to stick to egrep.
1100 1101
//
// Sources files are supplied as fullshort slice.
1102
// It consists of pairs: full path to source file and its base name.
1103
func (t *test) errorCheck(outStr string, wantAuto bool, fullshort ...string) (err error) {
1104 1105 1106 1107 1108 1109
	defer func() {
		if *verbose && err != nil {
			log.Printf("%s gc output:\n%s", t, outStr)
		}
	}()
	var errs []error
1110
	out := splitOutput(outStr, wantAuto)
1111

Russ Cox's avatar
Russ Cox committed
1112 1113
	// Cut directory name.
	for i := range out {
1114 1115 1116 1117 1118
		for j := 0; j < len(fullshort); j += 2 {
			full, short := fullshort[j], fullshort[j+1]
			out[i] = strings.Replace(out[i], full, short, -1)
		}
	}
1119

1120 1121 1122 1123
	var want []wantedError
	for j := 0; j < len(fullshort); j += 2 {
		full, short := fullshort[j], fullshort[j+1]
		want = append(want, t.wantedErrors(full, short)...)
Russ Cox's avatar
Russ Cox committed
1124 1125
	}

1126
	for _, we := range want {
1127
		var errmsgs []string
1128 1129 1130 1131 1132
		if we.auto {
			errmsgs, out = partitionStrings("<autogenerated>", out)
		} else {
			errmsgs, out = partitionStrings(we.prefix, out)
		}
1133
		if len(errmsgs) == 0 {
Russ Cox's avatar
Russ Cox committed
1134
			errs = append(errs, fmt.Errorf("%s:%d: missing error %q", we.file, we.lineNum, we.reStr))
1135 1136 1137
			continue
		}
		matched := false
Russ Cox's avatar
Russ Cox committed
1138
		n := len(out)
1139
		for _, errmsg := range errmsgs {
1140 1141 1142 1143 1144 1145 1146
			// Assume errmsg says "file:line: foo".
			// Cut leading "file:line: " to avoid accidental matching of file name instead of message.
			text := errmsg
			if i := strings.Index(text, " "); i >= 0 {
				text = text[i+1:]
			}
			if we.re.MatchString(text) {
1147 1148 1149 1150 1151 1152
				matched = true
			} else {
				out = append(out, errmsg)
			}
		}
		if !matched {
Russ Cox's avatar
Russ Cox committed
1153
			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")))
1154 1155 1156 1157
			continue
		}
	}

1158 1159 1160 1161 1162 1163 1164
	if len(out) > 0 {
		errs = append(errs, fmt.Errorf("Unmatched Errors:"))
		for _, errLine := range out {
			errs = append(errs, fmt.Errorf("%s", errLine))
		}
	}

1165 1166 1167 1168 1169 1170 1171
	if len(errs) == 0 {
		return nil
	}
	if len(errs) == 1 {
		return errs[0]
	}
	var buf bytes.Buffer
Russ Cox's avatar
Russ Cox committed
1172
	fmt.Fprintf(&buf, "\n")
1173 1174 1175 1176
	for _, err := range errs {
		fmt.Fprintf(&buf, "%s\n", err.Error())
	}
	return errors.New(buf.String())
1177
}
1178

1179 1180
func (t *test) updateErrors(out, file string) {
	base := path.Base(file)
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
	// Read in source file.
	src, err := ioutil.ReadFile(file)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	}
	lines := strings.Split(string(src), "\n")
	// Remove old errors.
	for i, ln := range lines {
		pos := strings.Index(ln, " // ERROR ")
		if pos >= 0 {
			lines[i] = ln[:pos]
		}
	}
	// Parse new errors.
	errors := make(map[int]map[string]bool)
	tmpRe := regexp.MustCompile(`autotmp_[0-9]+`)
1198
	for _, errStr := range splitOutput(out, false) {
1199
		colon1 := strings.Index(errStr, ":")
Josh Bleecher Snyder's avatar
Josh Bleecher Snyder committed
1200
		if colon1 < 0 || errStr[:colon1] != file {
1201 1202 1203 1204 1205 1206
			continue
		}
		colon2 := strings.Index(errStr[colon1+1:], ":")
		if colon2 < 0 {
			continue
		}
Josh Bleecher Snyder's avatar
Josh Bleecher Snyder committed
1207 1208
		colon2 += colon1 + 1
		line, err := strconv.Atoi(errStr[colon1+1 : colon2])
1209 1210 1211 1212 1213
		line--
		if err != nil || line < 0 || line >= len(lines) {
			continue
		}
		msg := errStr[colon2+2:]
1214 1215
		msg = strings.Replace(msg, file, base, -1) // normalize file mentions in error itself
		msg = strings.TrimLeft(msg, " \t")
1216
		for _, r := range []string{`\`, `*`, `+`, `?`, `[`, `]`, `(`, `)`} {
Josh Bleecher Snyder's avatar
Josh Bleecher Snyder committed
1217
			msg = strings.Replace(msg, r, `\`+r, -1)
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
		}
		msg = strings.Replace(msg, `"`, `.`, -1)
		msg = tmpRe.ReplaceAllLiteralString(msg, `autotmp_[0-9]+`)
		if errors[line] == nil {
			errors[line] = make(map[string]bool)
		}
		errors[line][msg] = true
	}
	// Add new errors.
	for line, errs := range errors {
		var sorted []string
		for e := range errs {
			sorted = append(sorted, e)
		}
		sort.Strings(sorted)
		lines[line] += " // ERROR"
		for _, e := range sorted {
			lines[line] += fmt.Sprintf(` "%s$"`, e)
		}
	}
	// Write new file.
	err = ioutil.WriteFile(file, []byte(strings.Join(lines, "\n")), 0640)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	}
	// Polish.
1245
	exec.Command(goTool(), "fmt", file).CombinedOutput()
1246 1247
}

1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
// matchPrefix reports whether s is of the form ^(.*/)?prefix(:|[),
// That is, it needs the file name prefix followed by a : or a [,
// and possibly preceded by a directory name.
func matchPrefix(s, prefix string) bool {
	i := strings.Index(s, ":")
	if i < 0 {
		return false
	}
	j := strings.LastIndex(s[:i], "/")
	s = s[j+1:]
	if len(s) <= len(prefix) || s[:len(prefix)] != prefix {
		return false
	}
	switch s[len(prefix)] {
	case '[', ':':
		return true
	}
	return false
}

func partitionStrings(prefix string, strs []string) (matched, unmatched []string) {
1269
	for _, s := range strs {
1270
		if matchPrefix(s, prefix) {
1271 1272 1273 1274 1275 1276 1277 1278 1279
			matched = append(matched, s)
		} else {
			unmatched = append(unmatched, s)
		}
	}
	return
}

type wantedError struct {
David du Colombier's avatar
David du Colombier committed
1280 1281 1282
	reStr   string
	re      *regexp.Regexp
	lineNum int
1283
	auto    bool // match <autogenerated> line
David du Colombier's avatar
David du Colombier committed
1284 1285
	file    string
	prefix  string
1286 1287 1288 1289
}

var (
	errRx       = regexp.MustCompile(`// (?:GC_)?ERROR (.*)`)
1290
	errAutoRx   = regexp.MustCompile(`// (?:GC_)?ERRORAUTO (.*)`)
1291 1292 1293 1294
	errQuotesRx = regexp.MustCompile(`"([^"]*)"`)
	lineRx      = regexp.MustCompile(`LINE(([+-])([0-9]+))?`)
)

1295
func (t *test) wantedErrors(file, short string) (errs []wantedError) {
1296 1297
	cache := make(map[string]*regexp.Regexp)

1298 1299
	src, _ := ioutil.ReadFile(file)
	for i, line := range strings.Split(string(src), "\n") {
1300 1301 1302 1303 1304
		lineNum := i + 1
		if strings.Contains(line, "////") {
			// double comment disables ERROR
			continue
		}
1305 1306 1307 1308 1309 1310 1311
		var auto bool
		m := errAutoRx.FindStringSubmatch(line)
		if m != nil {
			auto = true
		} else {
			m = errRx.FindStringSubmatch(line)
		}
1312 1313 1314 1315 1316 1317
		if m == nil {
			continue
		}
		all := m[1]
		mm := errQuotesRx.FindAllStringSubmatch(all, -1)
		if mm == nil {
Russ Cox's avatar
Russ Cox committed
1318
			log.Fatalf("%s:%d: invalid errchk line: %s", t.goFileName(), lineNum, line)
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
		}
		for _, m := range mm {
			rx := lineRx.ReplaceAllStringFunc(m[1], func(m string) string {
				n := lineNum
				if strings.HasPrefix(m, "LINE+") {
					delta, _ := strconv.Atoi(m[5:])
					n += delta
				} else if strings.HasPrefix(m, "LINE-") {
					delta, _ := strconv.Atoi(m[5:])
					n -= delta
				}
1330
				return fmt.Sprintf("%s:%d", short, n)
1331
			})
1332 1333 1334 1335 1336
			re := cache[rx]
			if re == nil {
				var err error
				re, err = regexp.Compile(rx)
				if err != nil {
1337
					log.Fatalf("%s:%d: invalid regexp \"%s\" in ERROR line: %v", t.goFileName(), lineNum, rx, err)
1338 1339
				}
				cache[rx] = re
Russ Cox's avatar
Russ Cox committed
1340
			}
1341
			prefix := fmt.Sprintf("%s:%d", short, lineNum)
1342
			errs = append(errs, wantedError{
David du Colombier's avatar
David du Colombier committed
1343 1344 1345
				reStr:   rx,
				re:      re,
				prefix:  prefix,
1346
				auto:    auto,
David du Colombier's avatar
David du Colombier committed
1347 1348
				lineNum: lineNum,
				file:    short,
1349 1350 1351 1352 1353 1354
			})
		}
	}

	return
}
1355

1356 1357 1358 1359 1360 1361 1362
const (
	// Regexp to match a single opcode check: optionally begin with "-" (to indicate
	// a negative check), followed by a string literal enclosed in "" or ``. For "",
	// backslashes must be handled.
	reMatchCheck = `-?(?:\x60[^\x60]*\x60|"(?:[^"\\]|\\.)*")`
)

1363
var (
1364
	// Regexp to split a line in code and comment, trimming spaces
1365
	rxAsmComment = regexp.MustCompile(`^\s*(.*?)\s*(?://\s*(.+)\s*)?$`)
1366

1367 1368 1369 1370
	// Regexp to extract an architecture check: architecture name (or triplet),
	// followed by semi-colon, followed by a comma-separated list of opcode checks.
	// Extraneous spaces are ignored.
	rxAsmPlatform = regexp.MustCompile(`(\w+)(/\w+)?(/\w*)?\s*:\s*(` + reMatchCheck + `(?:\s*,\s*` + reMatchCheck + `)*)`)
1371 1372 1373

	// Regexp to extract a single opcoded check
	rxAsmCheck = regexp.MustCompile(reMatchCheck)
1374 1375

	// List of all architecture variants. Key is the GOARCH architecture,
1376
	// value[0] is the variant-changing environment variable, and values[1:]
1377 1378 1379 1380 1381 1382 1383
	// are the supported variants.
	archVariants = map[string][]string{
		"386":     {"GO386", "387", "sse2"},
		"amd64":   {},
		"arm":     {"GOARM", "5", "6", "7"},
		"arm64":   {},
		"mips":    {"GOMIPS", "hardfloat", "softfloat"},
1384
		"mips64":  {"GOMIPS64", "hardfloat", "softfloat"},
1385 1386
		"ppc64":   {"GOPPC64", "power8", "power9"},
		"ppc64le": {"GOPPC64", "power8", "power9"},
1387
		"s390x":   {},
1388
		"wasm":    {},
1389
	}
1390 1391
)

1392
// wantedAsmOpcode is a single asmcheck check
1393
type wantedAsmOpcode struct {
1394 1395 1396 1397 1398
	fileline string         // original source file/line (eg: "/path/foo.go:45")
	line     int            // original source line
	opcode   *regexp.Regexp // opcode check to be performed on assembly output
	negative bool           // true if the check is supposed to fail rather than pass
	found    bool           // true if the opcode check matched at least one in the output
1399 1400
}

1401
// A build environment triplet separated by slashes (eg: linux/386/sse2).
1402
// The third field can be empty if the arch does not support variants (eg: "plan9/amd64/")
1403 1404 1405 1406 1407 1408
type buildEnv string

// Environ returns the environment it represents in cmd.Environ() "key=val" format
// For instance, "linux/386/sse2".Environ() returns {"GOOS=linux", "GOARCH=386", "GO386=sse2"}
func (b buildEnv) Environ() []string {
	fields := strings.Split(string(b), "/")
1409
	if len(fields) != 3 {
1410 1411 1412
		panic("invalid buildEnv string: " + string(b))
	}
	env := []string{"GOOS=" + fields[0], "GOARCH=" + fields[1]}
1413
	if fields[2] != "" {
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
		env = append(env, archVariants[fields[1]][0]+"="+fields[2])
	}
	return env
}

// asmChecks represents all the asmcheck checks present in a test file
// The outer map key is the build triplet in which the checks must be performed.
// The inner map key represent the source file line ("filename.go:1234") at which the
// checks must be performed.
type asmChecks map[buildEnv]map[string][]wantedAsmOpcode

// Envs returns all the buildEnv in which at least one check is present
func (a asmChecks) Envs() []buildEnv {
	var envs []buildEnv
	for e := range a {
		envs = append(envs, e)
	}
	sort.Slice(envs, func(i, j int) bool {
		return string(envs[i]) < string(envs[j])
	})
	return envs
}

func (t *test) wantedAsmOpcodes(fn string) asmChecks {
	ops := make(asmChecks)
1439

1440
	comment := ""
1441 1442
	src, _ := ioutil.ReadFile(fn)
	for i, line := range strings.Split(string(src), "\n") {
1443 1444 1445 1446 1447 1448 1449
		matches := rxAsmComment.FindStringSubmatch(line)
		code, cmt := matches[1], matches[2]

		// Keep comments pending in the comment variable until
		// we find a line that contains some code.
		comment += " " + cmt
		if code == "" {
1450 1451 1452
			continue
		}

1453 1454
		// Parse and extract any architecture check from comments,
		// made by one architecture name and multiple checks.
1455
		lnum := fn + ":" + strconv.Itoa(i+1)
1456
		for _, ac := range rxAsmPlatform.FindAllStringSubmatch(comment, -1) {
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
			archspec, allchecks := ac[1:4], ac[4]

			var arch, subarch, os string
			switch {
			case archspec[2] != "": // 3 components: "linux/386/sse2"
				os, arch, subarch = archspec[0], archspec[1][1:], archspec[2][1:]
			case archspec[1] != "": // 2 components: "386/sse2"
				os, arch, subarch = "linux", archspec[0], archspec[1][1:]
			default: // 1 component: "386"
				os, arch, subarch = "linux", archspec[0], ""
1467 1468 1469
				if arch == "wasm" {
					os = "js"
				}
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
			}

			if _, ok := archVariants[arch]; !ok {
				log.Fatalf("%s:%d: unsupported architecture: %v", t.goFileName(), i+1, arch)
			}

			// Create the build environments corresponding the above specifiers
			envs := make([]buildEnv, 0, 4)
			if subarch != "" {
				envs = append(envs, buildEnv(os+"/"+arch+"/"+subarch))
			} else {
				subarchs := archVariants[arch]
				if len(subarchs) == 0 {
1483
					envs = append(envs, buildEnv(os+"/"+arch+"/"))
1484 1485 1486 1487 1488 1489
				} else {
					for _, sa := range archVariants[arch][1:] {
						envs = append(envs, buildEnv(os+"/"+arch+"/"+sa))
					}
				}
			}
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501

			for _, m := range rxAsmCheck.FindAllString(allchecks, -1) {
				negative := false
				if m[0] == '-' {
					negative = true
					m = m[1:]
				}

				rxsrc, err := strconv.Unquote(m)
				if err != nil {
					log.Fatalf("%s:%d: error unquoting string: %v", t.goFileName(), i+1, err)
				}
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511

				// Compile the checks as regular expressions. Notice that we
				// consider checks as matching from the beginning of the actual
				// assembler source (that is, what is left on each line of the
				// compile -S output after we strip file/line info) to avoid
				// trivial bugs such as "ADD" matching "FADD". This
				// doesn't remove genericity: it's still possible to write
				// something like "F?ADD", but we make common cases simpler
				// to get right.
				oprx, err := regexp.Compile("^" + rxsrc)
1512 1513 1514
				if err != nil {
					log.Fatalf("%s:%d: %v", t.goFileName(), i+1, err)
				}
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525

				for _, env := range envs {
					if ops[env] == nil {
						ops[env] = make(map[string][]wantedAsmOpcode)
					}
					ops[env][lnum] = append(ops[env][lnum], wantedAsmOpcode{
						negative: negative,
						fileline: lnum,
						line:     i + 1,
						opcode:   oprx,
					})
1526
				}
1527 1528
			}
		}
1529
		comment = ""
1530 1531
	}

1532
	return ops
1533 1534
}

1535
func (t *test) asmCheck(outStr string, fn string, env buildEnv, fullops map[string][]wantedAsmOpcode) (err error) {
1536 1537 1538 1539 1540 1541 1542 1543
	// The assembly output contains the concatenated dump of multiple functions.
	// the first line of each function begins at column 0, while the rest is
	// indented by a tabulation. These data structures help us index the
	// output by function.
	functionMarkers := make([]int, 1)
	lineFuncMap := make(map[string]int)

	lines := strings.Split(outStr, "\n")
1544 1545
	rxLine := regexp.MustCompile(fmt.Sprintf(`\((%s:\d+)\)\s+(.*)`, regexp.QuoteMeta(fn)))

1546 1547 1548 1549 1550 1551 1552 1553
	for nl, line := range lines {
		// Check if this line begins a function
		if len(line) > 0 && line[0] != '\t' {
			functionMarkers = append(functionMarkers, nl)
		}

		// Search if this line contains a assembly opcode (which is prefixed by the
		// original source file/line in parenthesis)
1554 1555 1556 1557
		matches := rxLine.FindStringSubmatch(line)
		if len(matches) == 0 {
			continue
		}
1558 1559 1560 1561 1562 1563
		srcFileLine, asm := matches[1], matches[2]

		// Associate the original file/line information to the current
		// function in the output; it will be useful to dump it in case
		// of error.
		lineFuncMap[srcFileLine] = len(functionMarkers) - 1
1564

1565 1566 1567 1568 1569 1570 1571
		// If there are opcode checks associated to this source file/line,
		// run the checks.
		if ops, found := fullops[srcFileLine]; found {
			for i := range ops {
				if !ops[i].found && ops[i].opcode.FindString(asm) != "" {
					ops[i].found = true
				}
1572 1573 1574
			}
		}
	}
1575
	functionMarkers = append(functionMarkers, len(lines))
1576

1577
	var failed []wantedAsmOpcode
1578 1579
	for _, ops := range fullops {
		for _, o := range ops {
1580 1581 1582 1583
			// There's a failure if a negative match was found,
			// or a positive match was not found.
			if o.negative == o.found {
				failed = append(failed, o)
1584 1585 1586
			}
		}
	}
1587
	if len(failed) == 0 {
1588 1589 1590 1591
		return
	}

	// At least one asmcheck failed; report them
1592 1593
	sort.Slice(failed, func(i, j int) bool {
		return failed[i].line < failed[j].line
1594 1595
	})

1596
	lastFunction := -1
1597 1598
	var errbuf bytes.Buffer
	fmt.Fprintln(&errbuf)
1599
	for _, o := range failed {
1600 1601 1602 1603 1604 1605 1606 1607 1608
		// Dump the function in which this opcode check was supposed to
		// pass but failed.
		funcIdx := lineFuncMap[o.fileline]
		if funcIdx != 0 && funcIdx != lastFunction {
			funcLines := lines[functionMarkers[funcIdx]:functionMarkers[funcIdx+1]]
			log.Println(strings.Join(funcLines, "\n"))
			lastFunction = funcIdx // avoid printing same function twice
		}

1609
		if o.negative {
1610
			fmt.Fprintf(&errbuf, "%s:%d: %s: wrong opcode found: %q\n", t.goFileName(), o.line, env, o.opcode.String())
1611
		} else {
1612
			fmt.Fprintf(&errbuf, "%s:%d: %s: opcode not found: %q\n", t.goFileName(), o.line, env, o.opcode.String())
1613
		}
1614 1615 1616 1617 1618
	}
	err = errors.New(errbuf.String())
	return
}

1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
// defaultRunOutputLimit returns the number of runoutput tests that
// can be executed in parallel.
func defaultRunOutputLimit() int {
	const maxArmCPU = 2

	cpu := runtime.NumCPU()
	if runtime.GOARCH == "arm" && cpu > maxArmCPU {
		cpu = maxArmCPU
	}
	return cpu
}
1630

1631
// checkShouldTest runs sanity checks on the shouldTest function.
1632 1633 1634 1635 1636 1637 1638
func checkShouldTest() {
	assert := func(ok bool, _ string) {
		if !ok {
			panic("fail")
		}
	}
	assertNot := func(ok bool, _ string) { assert(!ok, "") }
1639 1640

	// Simple tests.
1641 1642 1643
	assert(shouldTest("// +build linux", "linux", "arm"))
	assert(shouldTest("// +build !windows", "linux", "arm"))
	assertNot(shouldTest("// +build !windows", "windows", "amd64"))
1644 1645

	// A file with no build tags will always be tested.
1646
	assert(shouldTest("// This is a test.", "os", "arch"))
1647 1648 1649 1650

	// Build tags separated by a space are OR-ed together.
	assertNot(shouldTest("// +build arm 386", "linux", "amd64"))

1651
	// Build tags separated by a comma are AND-ed together.
1652 1653 1654 1655 1656 1657 1658 1659 1660
	assertNot(shouldTest("// +build !windows,!plan9", "windows", "amd64"))
	assertNot(shouldTest("// +build !windows,!plan9", "plan9", "386"))

	// Build tags on multiple lines are AND-ed together.
	assert(shouldTest("// +build !windows\n// +build amd64", "linux", "amd64"))
	assertNot(shouldTest("// +build !windows\n// +build amd64", "windows", "amd64"))

	// Test that (!a OR !b) matches anything.
	assert(shouldTest("// +build !windows !plan9", "windows", "amd64"))
1661
}
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678

// envForDir returns a copy of the environment
// suitable for running in the given directory.
// The environment is the current process's environment
// but with an updated $PWD, so that an os.Getwd in the
// child will be faster.
func envForDir(dir string) []string {
	env := os.Environ()
	for i, kv := range env {
		if strings.HasPrefix(kv, "PWD=") {
			env[i] = "PWD=" + dir
			return env
		}
	}
	env = append(env, "PWD="+dir)
	return env
}
1679 1680 1681 1682 1683 1684 1685 1686

func getenv(key, def string) string {
	value := os.Getenv(key)
	if value != "" {
		return value
	}
	return def
}