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) {
108 defer testprog.Unlock()
109 if testprog.dir == "" {
110 dir, err := ioutil.TempDir("", "go-build")
112 t.Fatalf("failed to create temp directory: %v", err)
115 toRemove = append(toRemove, dir)
118 if testprog.target == nil {
119 testprog.target = make(map[string]buildexe)
123 name += "_" + strings.Join(flags, "_")
125 target, ok := testprog.target[name]
127 return target.exe, target.err
130 exe := filepath.Join(testprog.dir, name+".exe")
131 cmd := exec.Command(testenv.GoToolPath(t), append([]string{"build", "-o", exe}, flags...)...)
132 cmd.Dir = "testdata/" + binary
133 out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
135 target.err = fmt.Errorf("building %s %v: %v\n%s", binary, flags, err, out)
136 testprog.target[name] = target
137 return "", target.err
140 testprog.target[name] = target
144 func TestVDSO(t *testing.T) {
146 output := runTestProg(t, "testprog", "SignalInVDSO")
149 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
153 func testCrashHandler(t *testing.T, cgo bool) {
154 type crashTest struct {
159 output = runTestProg(t, "testprogcgo", "Crash")
161 output = runTestProg(t, "testprog", "Crash")
163 want := "main: recovered done\nnew-thread: recovered done\nsecond-new-thread: recovered done\nmain-again: recovered done\n"
165 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
169 func TestCrashHandler(t *testing.T) {
170 testCrashHandler(t, false)
173 func testDeadlock(t *testing.T, name string) {
174 output := runTestProg(t, "testprog", name)
175 want := "fatal error: all goroutines are asleep - deadlock!\n"
176 if !strings.HasPrefix(output, want) {
177 t.Fatalf("output does not start with %q:\n%s", want, output)
181 func TestSimpleDeadlock(t *testing.T) {
182 testDeadlock(t, "SimpleDeadlock")
185 func TestInitDeadlock(t *testing.T) {
186 testDeadlock(t, "InitDeadlock")
189 func TestLockedDeadlock(t *testing.T) {
190 testDeadlock(t, "LockedDeadlock")
193 func TestLockedDeadlock2(t *testing.T) {
194 testDeadlock(t, "LockedDeadlock2")
197 func TestGoexitDeadlock(t *testing.T) {
198 output := runTestProg(t, "testprog", "GoexitDeadlock")
199 want := "no goroutines (main called runtime.Goexit) - deadlock!"
200 if !strings.Contains(output, want) {
201 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
205 func TestStackOverflow(t *testing.T) {
206 if runtime.Compiler == "gccgo" {
207 t.Skip("gccgo does not do stack overflow checking")
209 output := runTestProg(t, "testprog", "StackOverflow")
211 "runtime: goroutine stack exceeds 1474560-byte limit\n",
212 "fatal error: stack overflow",
213 // information about the current SP and stack bounds
217 if !strings.HasPrefix(output, want[0]) {
218 t.Errorf("output does not start with %q", want[0])
220 for _, s := range want[1:] {
221 if !strings.Contains(output, s) {
222 t.Errorf("output does not contain %q", s)
226 t.Logf("output:\n%s", output)
230 func TestThreadExhaustion(t *testing.T) {
231 output := runTestProg(t, "testprog", "ThreadExhaustion")
232 want := "runtime: program exceeds 10-thread limit\nfatal error: thread exhaustion"
233 if !strings.HasPrefix(output, want) {
234 t.Fatalf("output does not start with %q:\n%s", want, output)
238 func TestRecursivePanic(t *testing.T) {
239 output := runTestProg(t, "testprog", "RecursivePanic")
244 if !strings.HasPrefix(output, want) {
245 t.Fatalf("output does not start with %q:\n%s", want, output)
250 func TestRecursivePanic2(t *testing.T) {
251 output := runTestProg(t, "testprog", "RecursivePanic2")
257 if !strings.HasPrefix(output, want) {
258 t.Fatalf("output does not start with %q:\n%s", want, output)
263 func TestRecursivePanic3(t *testing.T) {
264 output := runTestProg(t, "testprog", "RecursivePanic3")
265 want := `panic: first panic
268 if !strings.HasPrefix(output, want) {
269 t.Fatalf("output does not start with %q:\n%s", want, output)
274 func TestRecursivePanic4(t *testing.T) {
275 output := runTestProg(t, "testprog", "RecursivePanic4")
276 want := `panic: first panic [recovered]
279 if !strings.HasPrefix(output, want) {
280 t.Fatalf("output does not start with %q:\n%s", want, output)
285 func TestGoexitCrash(t *testing.T) {
286 output := runTestProg(t, "testprog", "GoexitExit")
287 want := "no goroutines (main called runtime.Goexit) - deadlock!"
288 if !strings.Contains(output, want) {
289 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
293 func TestGoexitDefer(t *testing.T) {
294 c := make(chan struct{})
299 t.Errorf("non-nil recover during Goexit")
305 // Note: if the defer fails to run, we will get a deadlock here
309 func TestGoNil(t *testing.T) {
310 output := runTestProg(t, "testprog", "GoNil")
311 want := "go of nil func value"
312 if !strings.Contains(output, want) {
313 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
317 func TestMainGoroutineID(t *testing.T) {
318 output := runTestProg(t, "testprog", "MainGoroutineID")
319 want := "panic: test\n\ngoroutine 1 [running]:\n"
320 if !strings.HasPrefix(output, want) {
321 t.Fatalf("output does not start with %q:\n%s", want, output)
325 func TestNoHelperGoroutines(t *testing.T) {
326 output := runTestProg(t, "testprog", "NoHelperGoroutines")
327 matches := regexp.MustCompile(`goroutine [0-9]+ \[`).FindAllStringSubmatch(output, -1)
328 if len(matches) != 1 || matches[0][0] != "goroutine 1 [" {
329 t.Fatalf("want to see only goroutine 1, see:\n%s", output)
333 func TestBreakpoint(t *testing.T) {
334 output := runTestProg(t, "testprog", "Breakpoint")
335 // If runtime.Breakpoint() is inlined, then the stack trace prints
336 // "runtime.Breakpoint(...)" instead of "runtime.Breakpoint()".
337 // For gccgo, no parens.
338 want := "runtime.Breakpoint"
339 if !strings.Contains(output, want) {
340 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
344 func TestGoexitInPanic(t *testing.T) {
345 // see issue 8774: this code used to trigger an infinite recursion
346 output := runTestProg(t, "testprog", "GoexitInPanic")
347 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
348 if !strings.HasPrefix(output, want) {
349 t.Fatalf("output does not start with %q:\n%s", want, output)
353 // Issue 14965: Runtime panics should be of type runtime.Error
354 func TestRuntimePanicWithRuntimeError(t *testing.T) {
355 testCases := [...]func(){
357 var m map[uint64]bool
361 ch := make(chan struct{})
366 var ch = make(chan struct{})
371 var s = make([]int, 2)
376 _ = make(chan bool, n)
379 close((chan bool)(nil))
383 for i, fn := range testCases {
384 got := panicValue(fn)
385 if _, ok := got.(runtime.Error); !ok {
386 t.Errorf("test #%d: recovered value %v(type %T) does not implement runtime.Error", i, got, got)
391 func panicValue(fn func()) (recovered interface{}) {
393 recovered = recover()
399 func TestPanicAfterGoexit(t *testing.T) {
400 // an uncaught panic should still work after goexit
401 output := runTestProg(t, "testprog", "PanicAfterGoexit")
402 want := "panic: hello"
403 if !strings.HasPrefix(output, want) {
404 t.Fatalf("output does not start with %q:\n%s", want, output)
408 func TestRecoveredPanicAfterGoexit(t *testing.T) {
409 output := runTestProg(t, "testprog", "RecoveredPanicAfterGoexit")
410 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
411 if !strings.HasPrefix(output, want) {
412 t.Fatalf("output does not start with %q:\n%s", want, output)
416 func TestRecoverBeforePanicAfterGoexit(t *testing.T) {
418 output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit")
419 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
420 if !strings.HasPrefix(output, want) {
421 t.Fatalf("output does not start with %q:\n%s", want, output)
425 func TestRecoverBeforePanicAfterGoexit2(t *testing.T) {
427 output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit2")
428 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
429 if !strings.HasPrefix(output, want) {
430 t.Fatalf("output does not start with %q:\n%s", want, output)
434 func TestNetpollDeadlock(t *testing.T) {
435 if os.Getenv("GO_BUILDER_NAME") == "darwin-amd64-10_12" {
436 // A suspected kernel bug in macOS 10.12 occasionally results in
437 // an apparent deadlock when dialing localhost. The errors have not
438 // been observed on newer versions of the OS, so we don't plan to work
439 // around them. See https://golang.org/issue/22019.
440 testenv.SkipFlaky(t, 22019)
444 output := runTestProg(t, "testprognet", "NetpollDeadlock")
446 if !strings.HasSuffix(output, want) {
447 t.Fatalf("output does not start with %q:\n%s", want, output)
451 func TestPanicTraceback(t *testing.T) {
453 output := runTestProg(t, "testprog", "PanicTraceback")
454 want := "panic: hello\n\tpanic: panic pt2\n\tpanic: panic pt1\n"
455 if !strings.HasPrefix(output, want) {
456 t.Fatalf("output does not start with %q:\n%s", want, output)
459 // Check functions in the traceback.
460 fns := []string{"main.pt1.func1", "panic", "main.pt2.func1", "panic", "main.pt2", "main.pt1"}
461 if runtime.Compiler == "gccgo" {
462 fns = []string{"main.pt1..func1", "panic", "main.pt2..func1", "panic", "main.pt2", "main.pt1"}
464 for _, fn := range fns {
465 var re *regexp.Regexp
466 if runtime.Compiler != "gccgo" {
467 re = regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(fn) + `\(.*\n`)
469 re = regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(fn) + `.*\n`)
471 idx := re.FindStringIndex(output)
473 t.Fatalf("expected %q function in traceback:\n%s", fn, output)
475 output = output[idx[1]:]
479 func testPanicDeadlock(t *testing.T, name string, want string) {
481 output := runTestProg(t, "testprog", name)
482 if !strings.HasPrefix(output, want) {
483 t.Fatalf("output does not start with %q:\n%s", want, output)
487 func TestPanicDeadlockGosched(t *testing.T) {
488 testPanicDeadlock(t, "GoschedInPanic", "panic: errorThatGosched\n\n")
491 func TestPanicDeadlockSyscall(t *testing.T) {
492 testPanicDeadlock(t, "SyscallInPanic", "1\n2\npanic: 3\n\n")
495 func TestPanicLoop(t *testing.T) {
496 output := runTestProg(t, "testprog", "PanicLoop")
497 if want := "panic while printing panic value"; !strings.Contains(output, want) {
498 t.Errorf("output does not contain %q:\n%s", want, output)
502 func TestMemPprof(t *testing.T) {
503 testenv.MustHaveGoRun(t)
504 if runtime.Compiler == "gccgo" {
505 t.Skip("gccgo may not have the pprof tool")
508 exe, err := buildTestProg(t, "testprog")
513 got, err := testenv.CleanCmdEnv(exec.Command(exe, "MemProf")).CombinedOutput()
517 fn := strings.TrimSpace(string(got))
520 for try := 0; try < 2; try++ {
521 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-alloc_space", "-top"))
522 // Check that pprof works both with and without explicit executable on command line.
524 cmd.Args = append(cmd.Args, exe, fn)
526 cmd.Args = append(cmd.Args, fn)
529 for i, e := range cmd.Env {
530 if strings.HasPrefix(e, "PPROF_TMPDIR=") {
531 cmd.Env[i] = "PPROF_TMPDIR=" + os.TempDir()
537 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
540 top, err := cmd.CombinedOutput()
541 t.Logf("%s:\n%s", cmd.Args, top)
544 } else if !bytes.Contains(top, []byte("MemProf")) {
545 t.Error("missing MemProf in pprof output")
550 var concurrentMapTest = flag.Bool("run_concurrent_map_tests", false, "also run flaky concurrent map tests")
552 func TestConcurrentMapWrites(t *testing.T) {
553 if !*concurrentMapTest {
554 t.Skip("skipping without -run_concurrent_map_tests")
556 testenv.MustHaveGoRun(t)
557 output := runTestProg(t, "testprog", "concurrentMapWrites")
558 want := "fatal error: concurrent map writes"
559 if !strings.HasPrefix(output, want) {
560 t.Fatalf("output does not start with %q:\n%s", want, output)
563 func TestConcurrentMapReadWrite(t *testing.T) {
564 if !*concurrentMapTest {
565 t.Skip("skipping without -run_concurrent_map_tests")
567 testenv.MustHaveGoRun(t)
568 output := runTestProg(t, "testprog", "concurrentMapReadWrite")
569 want := "fatal error: concurrent map read and map write"
570 if !strings.HasPrefix(output, want) {
571 t.Fatalf("output does not start with %q:\n%s", want, output)
574 func TestConcurrentMapIterateWrite(t *testing.T) {
575 if !*concurrentMapTest {
576 t.Skip("skipping without -run_concurrent_map_tests")
578 testenv.MustHaveGoRun(t)
579 output := runTestProg(t, "testprog", "concurrentMapIterateWrite")
580 want := "fatal error: concurrent map iteration and map write"
581 if !strings.HasPrefix(output, want) {
582 t.Fatalf("output does not start with %q:\n%s", want, output)
590 func (p *point) negate() {
595 // Test for issue #10152.
596 func TestPanicInlined(t *testing.T) {
600 t.Fatalf("recover failed")
602 buf := make([]byte, 2048)
603 n := runtime.Stack(buf, false)
605 want := []byte("(*point).negate(")
606 if runtime.Compiler == "gccgo" {
607 want = []byte("point.negate")
609 if !bytes.Contains(buf, want) {
611 t.Fatalf("expecting stack trace to contain call to %s", want)
619 // Test for issues #3934 and #20018.
620 // We want to delay exiting until a panic print is complete.
621 func TestPanicRace(t *testing.T) {
622 testenv.MustHaveGoRun(t)
624 exe, err := buildTestProg(t, "testprog")
629 // The test is intentionally racy, and in my testing does not
630 // produce the expected output about 0.05% of the time.
631 // So run the program in a loop and only fail the test if we
632 // get the wrong output ten times in a row.
635 for i := 0; i < tries; i++ {
636 got, err := testenv.CleanCmdEnv(exec.Command(exe, "PanicRace")).CombinedOutput()
638 t.Logf("try %d: program exited successfully, should have failed", i+1)
643 t.Logf("try %d:\n", i+1)
652 if runtime.Compiler == "gccgo" {
653 // gccgo will dump a function name like main.$nested30.
654 // Match on the file name instead.
655 wants[1] = "panicrace"
657 for _, want := range wants {
658 if !bytes.Contains(got, []byte(want)) {
659 t.Logf("did not find expected string %q", want)
664 // Test generated expected output.
667 t.Errorf("test ran %d times without producing expected output", tries)
670 func TestBadTraceback(t *testing.T) {
671 if runtime.Compiler == "gccgo" {
672 t.Skip("gccgo does not do a hex dump")
674 output := runTestProg(t, "testprog", "BadTraceback")
675 for _, want := range []string{
676 "runtime: unexpected return pc",
678 "00000bad", // Smashed LR in hex dump
679 "<main.badLR", // Symbolization in hex dump (badLR1 or badLR2)
681 if !strings.Contains(output, want) {
682 t.Errorf("output does not contain %q:\n%s", want, output)
687 func TestTimePprof(t *testing.T) {
688 if runtime.Compiler == "gccgo" {
689 t.Skip("gccgo may not have the pprof tool")
691 if runtime.GOOS == "aix" {
692 t.Skip("pprof not yet available on AIX (see golang.org/issue/28555)")
694 fn := runTestProg(t, "testprog", "TimeProf")
695 fn = strings.TrimSpace(fn)
698 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-top", "-nodecount=1", fn))
699 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
700 top, err := cmd.CombinedOutput()
704 } else if bytes.Contains(top, []byte("ExternalCode")) {
705 t.Error("profiler refers to ExternalCode")
709 // Test that runtime.abort does so.
710 func TestAbort(t *testing.T) {
711 // Pass GOTRACEBACK to ensure we get runtime frames.
712 output := runTestProg(t, "testprog", "Abort", "GOTRACEBACK=system")
713 if want := "runtime.abort"; !strings.Contains(output, want) {
714 t.Errorf("output does not contain %q:\n%s", want, output)
716 if strings.Contains(output, "BAD") {
717 t.Errorf("output contains BAD:\n%s", output)
719 // Check that it's a signal traceback.
721 // For systems that use a breakpoint, check specifically for that.
722 if runtime.Compiler == "gc" {
723 switch runtime.GOARCH {
725 switch runtime.GOOS {
727 want = "sys: breakpoint"
729 want = "Exception 0x80000003"
735 if !strings.Contains(output, want) {
736 t.Errorf("output does not contain %q:\n%s", want, output)
740 // For TestRuntimePanic: test a panic in the runtime package without
741 // involving the testing harness.
743 if os.Getenv("GO_TEST_RUNTIME_PANIC") == "1" {
745 if r := recover(); r != nil {
746 // We expect to crash, so exit 0
747 // to indicate failure.
751 runtime.PanicForTesting(nil, 1)
752 // We expect to crash, so exit 0 to indicate failure.
757 func TestRuntimePanic(t *testing.T) {
758 testenv.MustHaveExec(t)
759 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestRuntimePanic"))
760 cmd.Env = append(cmd.Env, "GO_TEST_RUNTIME_PANIC=1")
761 out, err := cmd.CombinedOutput()
764 t.Error("child process did not fail")
765 } else if want := "runtime.unexportedPanicForTesting"; !bytes.Contains(out, []byte(want)) {
766 t.Errorf("output did not contain expected string %q", want)
770 // Test that g0 stack overflows are handled gracefully.
771 func TestG0StackOverflow(t *testing.T) {
772 testenv.MustHaveExec(t)
774 switch runtime.GOOS {
775 case "darwin", "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "android":
776 t.Skipf("g0 stack is wrong on pthread platforms (see golang.org/issue/26061)")
779 if os.Getenv("TEST_G0_STACK_OVERFLOW") != "1" {
780 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestG0StackOverflow", "-test.v"))
781 cmd.Env = append(cmd.Env, "TEST_G0_STACK_OVERFLOW=1")
782 out, err := cmd.CombinedOutput()
783 // Don't check err since it's expected to crash.
784 if n := strings.Count(string(out), "morestack on g0\n"); n != 1 {
785 t.Fatalf("%s\n(exit status %v)", out, err)
787 // Check that it's a signal-style traceback.
788 if runtime.GOOS != "windows" {
789 if want := "PC="; !strings.Contains(string(out), want) {
790 t.Errorf("output does not contain %q:\n%s", want, out)
796 runtime.G0StackOverflow()
799 // Test that panic message is not clobbered.
801 func TestDoublePanic(t *testing.T) {
802 output := runTestProg(t, "testprog", "DoublePanic", "GODEBUG=clobberfree=1")
803 wants := []string{"panic: XXX", "panic: YYY"}
804 for _, want := range wants {
805 if !strings.Contains(output, want) {
806 t.Errorf("output:\n%s\n\nwant output containing: %s", output, want)