1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
27 func TestMain(m *testing.M) {
29 for _, file := range toRemove {
38 target map[string]buildexe
41 type buildexe struct {
46 func runTestProg(t *testing.T, binary, name string, env ...string) string {
51 testenv.MustHaveGoBuild(t)
53 exe, err := buildTestProg(t, binary)
58 cmd := testenv.CleanCmdEnv(exec.Command(exe, name))
59 cmd.Env = append(cmd.Env, env...)
61 cmd.Env = append(cmd.Env, "RUNTIME_TEST_SHORT=1")
66 if err := cmd.Start(); err != nil {
67 t.Fatalf("starting %s %s: %v", binary, name, err)
70 // If the process doesn't complete within 1 minute,
71 // assume it is hanging and kill it to get a stack trace.
73 done := make(chan bool)
76 // This GOARCH/GOOS test is copied from cmd/dist/test.go.
77 // TODO(iant): Have cmd/dist update the environment variable.
78 if runtime.GOARCH == "arm" || runtime.GOOS == "windows" {
81 if s := os.Getenv("GO_TEST_TIMEOUT_SCALE"); s != "" {
82 if sc, err := strconv.Atoi(s); err == nil {
89 case <-time.After(time.Duration(scale) * time.Minute):
94 if err := cmd.Wait(); err != nil {
95 t.Logf("%s %s exit status: %v", binary, name, err)
102 func buildTestProg(t *testing.T, binary string, flags ...string) (string, error) {
110 defer testprog.Unlock()
111 if testprog.dir == "" {
112 dir, err := ioutil.TempDir("", "go-build")
114 t.Fatalf("failed to create temp directory: %v", err)
117 toRemove = append(toRemove, dir)
120 if testprog.target == nil {
121 testprog.target = make(map[string]buildexe)
125 name += "_" + strings.Join(flags, "_")
127 target, ok := testprog.target[name]
129 return target.exe, target.err
132 exe := filepath.Join(testprog.dir, name+".exe")
133 cmd := exec.Command(testenv.GoToolPath(t), append([]string{"build", "-o", exe}, flags...)...)
134 cmd.Dir = "testdata/" + binary
135 out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
137 target.err = fmt.Errorf("building %s %v: %v\n%s", binary, flags, err, out)
138 testprog.target[name] = target
139 return "", target.err
142 testprog.target[name] = target
147 staleRuntimeOnce sync.Once // guards init of staleRuntimeErr
148 staleRuntimeErr error
151 func checkStaleRuntime(t *testing.T) {
152 staleRuntimeOnce.Do(func() {
153 if runtime.Compiler == "gccgo" {
156 // 'go run' uses the installed copy of runtime.a, which may be out of date.
157 out, err := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "list", "-gcflags=all="+os.Getenv("GO_GCFLAGS"), "-f", "{{.Stale}}", "runtime")).CombinedOutput()
159 staleRuntimeErr = fmt.Errorf("failed to execute 'go list': %v\n%v", err, string(out))
162 if string(out) != "false\n" {
163 t.Logf("go list -f {{.Stale}} runtime:\n%s", out)
164 out, err := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "list", "-gcflags=all="+os.Getenv("GO_GCFLAGS"), "-f", "{{.StaleReason}}", "runtime")).CombinedOutput()
166 t.Logf("go list -f {{.StaleReason}} failed: %v", err)
168 t.Logf("go list -f {{.StaleReason}} runtime:\n%s", out)
169 staleRuntimeErr = fmt.Errorf("Stale runtime.a. Run 'go install runtime'.")
172 if staleRuntimeErr != nil {
173 t.Fatal(staleRuntimeErr)
177 func testCrashHandler(t *testing.T, cgo bool) {
178 type crashTest struct {
183 output = runTestProg(t, "testprogcgo", "Crash")
185 output = runTestProg(t, "testprog", "Crash")
187 want := "main: recovered done\nnew-thread: recovered done\nsecond-new-thread: recovered done\nmain-again: recovered done\n"
189 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
193 func TestCrashHandler(t *testing.T) {
194 testCrashHandler(t, false)
197 func testDeadlock(t *testing.T, name string) {
198 output := runTestProg(t, "testprog", name)
199 want := "fatal error: all goroutines are asleep - deadlock!\n"
200 if !strings.HasPrefix(output, want) {
201 t.Fatalf("output does not start with %q:\n%s", want, output)
205 func TestSimpleDeadlock(t *testing.T) {
206 testDeadlock(t, "SimpleDeadlock")
209 func TestInitDeadlock(t *testing.T) {
210 testDeadlock(t, "InitDeadlock")
213 func TestLockedDeadlock(t *testing.T) {
214 testDeadlock(t, "LockedDeadlock")
217 func TestLockedDeadlock2(t *testing.T) {
218 testDeadlock(t, "LockedDeadlock2")
221 func TestGoexitDeadlock(t *testing.T) {
222 output := runTestProg(t, "testprog", "GoexitDeadlock")
223 want := "no goroutines (main called runtime.Goexit) - deadlock!"
224 if !strings.Contains(output, want) {
225 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
229 func TestStackOverflow(t *testing.T) {
230 if runtime.Compiler == "gccgo" {
231 t.Skip("gccgo does not do stack overflow checking")
233 output := runTestProg(t, "testprog", "StackOverflow")
234 want := "runtime: goroutine stack exceeds 1474560-byte limit\nfatal error: stack overflow"
235 if !strings.HasPrefix(output, want) {
236 t.Fatalf("output does not start with %q:\n%s", want, output)
240 func TestThreadExhaustion(t *testing.T) {
241 output := runTestProg(t, "testprog", "ThreadExhaustion")
242 want := "runtime: program exceeds 10-thread limit\nfatal error: thread exhaustion"
243 if !strings.HasPrefix(output, want) {
244 t.Fatalf("output does not start with %q:\n%s", want, output)
248 func TestRecursivePanic(t *testing.T) {
249 output := runTestProg(t, "testprog", "RecursivePanic")
254 if !strings.HasPrefix(output, want) {
255 t.Fatalf("output does not start with %q:\n%s", want, output)
260 func TestGoexitCrash(t *testing.T) {
261 output := runTestProg(t, "testprog", "GoexitExit")
262 want := "no goroutines (main called runtime.Goexit) - deadlock!"
263 if !strings.Contains(output, want) {
264 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
268 func TestGoexitDefer(t *testing.T) {
269 c := make(chan struct{})
274 t.Errorf("non-nil recover during Goexit")
280 // Note: if the defer fails to run, we will get a deadlock here
284 func TestGoNil(t *testing.T) {
285 output := runTestProg(t, "testprog", "GoNil")
286 want := "go of nil func value"
287 if !strings.Contains(output, want) {
288 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
292 func TestMainGoroutineID(t *testing.T) {
293 output := runTestProg(t, "testprog", "MainGoroutineID")
294 want := "panic: test\n\ngoroutine 1 [running]:\n"
295 if !strings.HasPrefix(output, want) {
296 t.Fatalf("output does not start with %q:\n%s", want, output)
300 func TestNoHelperGoroutines(t *testing.T) {
301 output := runTestProg(t, "testprog", "NoHelperGoroutines")
302 matches := regexp.MustCompile(`goroutine [0-9]+ \[`).FindAllStringSubmatch(output, -1)
303 if len(matches) != 1 || matches[0][0] != "goroutine 1 [" {
304 t.Fatalf("want to see only goroutine 1, see:\n%s", output)
308 func TestBreakpoint(t *testing.T) {
309 output := runTestProg(t, "testprog", "Breakpoint")
310 // If runtime.Breakpoint() is inlined, then the stack trace prints
311 // "runtime.Breakpoint(...)" instead of "runtime.Breakpoint()".
312 // For gccgo, no parens.
313 want := "runtime.Breakpoint"
314 if !strings.Contains(output, want) {
315 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
319 func TestGoexitInPanic(t *testing.T) {
320 // see issue 8774: this code used to trigger an infinite recursion
321 output := runTestProg(t, "testprog", "GoexitInPanic")
322 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
323 if !strings.HasPrefix(output, want) {
324 t.Fatalf("output does not start with %q:\n%s", want, output)
328 // Issue 14965: Runtime panics should be of type runtime.Error
329 func TestRuntimePanicWithRuntimeError(t *testing.T) {
330 testCases := [...]func(){
332 var m map[uint64]bool
336 ch := make(chan struct{})
341 var ch = make(chan struct{})
346 var s = make([]int, 2)
351 _ = make(chan bool, n)
354 close((chan bool)(nil))
358 for i, fn := range testCases {
359 got := panicValue(fn)
360 if _, ok := got.(runtime.Error); !ok {
361 t.Errorf("test #%d: recovered value %v(type %T) does not implement runtime.Error", i, got, got)
366 func panicValue(fn func()) (recovered interface{}) {
368 recovered = recover()
374 func TestPanicAfterGoexit(t *testing.T) {
375 // an uncaught panic should still work after goexit
376 output := runTestProg(t, "testprog", "PanicAfterGoexit")
377 want := "panic: hello"
378 if !strings.HasPrefix(output, want) {
379 t.Fatalf("output does not start with %q:\n%s", want, output)
383 func TestRecoveredPanicAfterGoexit(t *testing.T) {
384 output := runTestProg(t, "testprog", "RecoveredPanicAfterGoexit")
385 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
386 if !strings.HasPrefix(output, want) {
387 t.Fatalf("output does not start with %q:\n%s", want, output)
391 func TestRecoverBeforePanicAfterGoexit(t *testing.T) {
392 // 1. defer a function that recovers
393 // 2. defer a function that panics
395 // Goexit should run the #2 defer. Its panic
396 // should be caught by the #1 defer, and execution
397 // should resume in the caller. Like the Goexit
411 func TestNetpollDeadlock(t *testing.T) {
413 output := runTestProg(t, "testprognet", "NetpollDeadlock")
415 if !strings.HasSuffix(output, want) {
416 t.Fatalf("output does not start with %q:\n%s", want, output)
420 func TestPanicTraceback(t *testing.T) {
422 output := runTestProg(t, "testprog", "PanicTraceback")
423 want := "panic: hello"
424 if !strings.HasPrefix(output, want) {
425 t.Fatalf("output does not start with %q:\n%s", want, output)
428 // Check functions in the traceback.
429 fns := []string{"main.pt1.func1", "panic", "main.pt2.func1", "panic", "main.pt2", "main.pt1"}
430 if runtime.Compiler == "gccgo" {
431 fns = []string{"main.pt1..func1", "panic", "main.pt2..func1", "panic", "main.pt2", "main.pt1"}
433 for _, fn := range fns {
434 var re *regexp.Regexp
435 if runtime.Compiler != "gccgo" {
436 re = regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(fn) + `\(.*\n`)
438 re = regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(fn) + `.*\n`)
440 idx := re.FindStringIndex(output)
442 t.Fatalf("expected %q function in traceback:\n%s", fn, output)
444 output = output[idx[1]:]
448 func testPanicDeadlock(t *testing.T, name string, want string) {
450 output := runTestProg(t, "testprog", name)
451 if !strings.HasPrefix(output, want) {
452 t.Fatalf("output does not start with %q:\n%s", want, output)
456 func TestPanicDeadlockGosched(t *testing.T) {
457 testPanicDeadlock(t, "GoschedInPanic", "panic: errorThatGosched\n\n")
460 func TestPanicDeadlockSyscall(t *testing.T) {
461 testPanicDeadlock(t, "SyscallInPanic", "1\n2\npanic: 3\n\n")
464 func TestPanicLoop(t *testing.T) {
465 output := runTestProg(t, "testprog", "PanicLoop")
466 if want := "panic while printing panic value"; !strings.Contains(output, want) {
467 t.Errorf("output does not contain %q:\n%s", want, output)
471 func TestMemPprof(t *testing.T) {
472 testenv.MustHaveGoRun(t)
473 if runtime.Compiler == "gccgo" {
474 t.Skip("gccgo may not have the pprof tool")
477 exe, err := buildTestProg(t, "testprog")
482 got, err := testenv.CleanCmdEnv(exec.Command(exe, "MemProf")).CombinedOutput()
486 fn := strings.TrimSpace(string(got))
489 for try := 0; try < 2; try++ {
490 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-alloc_space", "-top"))
491 // Check that pprof works both with and without explicit executable on command line.
493 cmd.Args = append(cmd.Args, exe, fn)
495 cmd.Args = append(cmd.Args, fn)
498 for i, e := range cmd.Env {
499 if strings.HasPrefix(e, "PPROF_TMPDIR=") {
500 cmd.Env[i] = "PPROF_TMPDIR=" + os.TempDir()
506 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
509 top, err := cmd.CombinedOutput()
510 t.Logf("%s:\n%s", cmd.Args, top)
513 } else if !bytes.Contains(top, []byte("MemProf")) {
514 t.Error("missing MemProf in pprof output")
519 var concurrentMapTest = flag.Bool("run_concurrent_map_tests", false, "also run flaky concurrent map tests")
521 func TestConcurrentMapWrites(t *testing.T) {
522 if !*concurrentMapTest {
523 t.Skip("skipping without -run_concurrent_map_tests")
525 testenv.MustHaveGoRun(t)
526 output := runTestProg(t, "testprog", "concurrentMapWrites")
527 want := "fatal error: concurrent map writes"
528 if !strings.HasPrefix(output, want) {
529 t.Fatalf("output does not start with %q:\n%s", want, output)
532 func TestConcurrentMapReadWrite(t *testing.T) {
533 if !*concurrentMapTest {
534 t.Skip("skipping without -run_concurrent_map_tests")
536 testenv.MustHaveGoRun(t)
537 output := runTestProg(t, "testprog", "concurrentMapReadWrite")
538 want := "fatal error: concurrent map read and map write"
539 if !strings.HasPrefix(output, want) {
540 t.Fatalf("output does not start with %q:\n%s", want, output)
543 func TestConcurrentMapIterateWrite(t *testing.T) {
544 if !*concurrentMapTest {
545 t.Skip("skipping without -run_concurrent_map_tests")
547 testenv.MustHaveGoRun(t)
548 output := runTestProg(t, "testprog", "concurrentMapIterateWrite")
549 want := "fatal error: concurrent map iteration and map write"
550 if !strings.HasPrefix(output, want) {
551 t.Fatalf("output does not start with %q:\n%s", want, output)
559 func (p *point) negate() {
564 // Test for issue #10152.
565 func TestPanicInlined(t *testing.T) {
569 t.Fatalf("recover failed")
571 buf := make([]byte, 2048)
572 n := runtime.Stack(buf, false)
574 want := []byte("(*point).negate(")
575 if runtime.Compiler == "gccgo" {
576 want = []byte("point.negate")
578 if !bytes.Contains(buf, want) {
580 t.Fatalf("expecting stack trace to contain call to %s", want)
588 // Test for issues #3934 and #20018.
589 // We want to delay exiting until a panic print is complete.
590 func TestPanicRace(t *testing.T) {
591 testenv.MustHaveGoRun(t)
593 exe, err := buildTestProg(t, "testprog")
598 // The test is intentionally racy, and in my testing does not
599 // produce the expected output about 0.05% of the time.
600 // So run the program in a loop and only fail the test if we
601 // get the wrong output ten times in a row.
604 for i := 0; i < tries; i++ {
605 got, err := testenv.CleanCmdEnv(exec.Command(exe, "PanicRace")).CombinedOutput()
607 t.Logf("try %d: program exited successfully, should have failed", i+1)
612 t.Logf("try %d:\n", i+1)
621 if runtime.Compiler == "gccgo" {
622 // gccgo will dump a function name like main.$nested30.
623 // Match on the file name instead.
624 wants[1] = "panicrace"
626 for _, want := range wants {
627 if !bytes.Contains(got, []byte(want)) {
628 t.Logf("did not find expected string %q", want)
633 // Test generated expected output.
636 t.Errorf("test ran %d times without producing expected output", tries)
639 func TestBadTraceback(t *testing.T) {
640 if runtime.Compiler == "gccgo" {
641 t.Skip("gccgo does not do a hex dump")
643 output := runTestProg(t, "testprog", "BadTraceback")
644 for _, want := range []string{
645 "runtime: unexpected return pc",
647 "00000bad", // Smashed LR in hex dump
648 "<main.badLR", // Symbolization in hex dump (badLR1 or badLR2)
650 if !strings.Contains(output, want) {
651 t.Errorf("output does not contain %q:\n%s", want, output)
656 func TestTimePprof(t *testing.T) {
657 if runtime.Compiler == "gccgo" {
658 t.Skip("gccgo may not have the pprof tool")
660 if runtime.GOOS == "aix" {
661 t.Skip("pprof not yet available on AIX (see golang.org/issue/28555)")
663 fn := runTestProg(t, "testprog", "TimeProf")
664 fn = strings.TrimSpace(fn)
667 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-top", "-nodecount=1", fn))
668 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
669 top, err := cmd.CombinedOutput()
673 } else if bytes.Contains(top, []byte("ExternalCode")) {
674 t.Error("profiler refers to ExternalCode")
678 // Test that runtime.abort does so.
679 func TestAbort(t *testing.T) {
680 // Pass GOTRACEBACK to ensure we get runtime frames.
681 output := runTestProg(t, "testprog", "Abort", "GOTRACEBACK=system")
682 if want := "runtime.abort"; !strings.Contains(output, want) {
683 t.Errorf("output does not contain %q:\n%s", want, output)
685 if strings.Contains(output, "BAD") {
686 t.Errorf("output contains BAD:\n%s", output)
688 // Check that it's a signal traceback.
690 // For systems that use a breakpoint, check specifically for that.
691 if runtime.Compiler == "gc" {
692 switch runtime.GOARCH {
694 switch runtime.GOOS {
696 want = "sys: breakpoint"
698 want = "Exception 0x80000003"
704 if !strings.Contains(output, want) {
705 t.Errorf("output does not contain %q:\n%s", want, output)
709 // For TestRuntimePanic: test a panic in the runtime package without
710 // involving the testing harness.
712 if os.Getenv("GO_TEST_RUNTIME_PANIC") == "1" {
714 if r := recover(); r != nil {
715 // We expect to crash, so exit 0
716 // to indicate failure.
720 runtime.PanicForTesting(nil, 1)
721 // We expect to crash, so exit 0 to indicate failure.
726 func TestRuntimePanic(t *testing.T) {
727 testenv.MustHaveExec(t)
728 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestRuntimePanic"))
729 cmd.Env = append(cmd.Env, "GO_TEST_RUNTIME_PANIC=1")
730 out, err := cmd.CombinedOutput()
733 t.Error("child process did not fail")
734 } else if want := "runtime.unexportedPanicForTesting"; !bytes.Contains(out, []byte(want)) {
735 t.Errorf("output did not contain expected string %q", want)
739 // Test that g0 stack overflows are handled gracefully.
740 func TestG0StackOverflow(t *testing.T) {
741 testenv.MustHaveExec(t)
743 switch runtime.GOOS {
744 case "darwin", "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "android":
745 t.Skipf("g0 stack is wrong on pthread platforms (see golang.org/issue/26061)")
748 if os.Getenv("TEST_G0_STACK_OVERFLOW") != "1" {
749 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestG0StackOverflow", "-test.v"))
750 cmd.Env = append(cmd.Env, "TEST_G0_STACK_OVERFLOW=1")
751 out, err := cmd.CombinedOutput()
752 // Don't check err since it's expected to crash.
753 if n := strings.Count(string(out), "morestack on g0\n"); n != 1 {
754 t.Fatalf("%s\n(exit status %v)", out, err)
756 // Check that it's a signal-style traceback.
757 if runtime.GOOS != "windows" {
758 if want := "PC="; !strings.Contains(string(out), want) {
759 t.Errorf("output does not contain %q:\n%s", want, out)
765 runtime.G0StackOverflow()