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.
26 func TestMain(m *testing.M) {
28 for _, file := range toRemove {
37 target map[string]buildexe
40 type buildexe struct {
45 func runTestProg(t *testing.T, binary, name string, env ...string) string {
50 testenv.MustHaveGoBuild(t)
52 exe, err := buildTestProg(t, binary)
57 return runBuiltTestProg(t, exe, name, env...)
60 func runBuiltTestProg(t *testing.T, exe, name string, env ...string) string {
65 testenv.MustHaveGoBuild(t)
67 cmd := testenv.CleanCmdEnv(exec.Command(exe, name))
68 cmd.Env = append(cmd.Env, env...)
70 cmd.Env = append(cmd.Env, "RUNTIME_TEST_SHORT=1")
75 if err := cmd.Start(); err != nil {
76 t.Fatalf("starting %s %s: %v", exe, name, err)
79 // If the process doesn't complete within 1 minute,
80 // assume it is hanging and kill it to get a stack trace.
82 done := make(chan bool)
85 // This GOARCH/GOOS test is copied from cmd/dist/test.go.
86 // TODO(iant): Have cmd/dist update the environment variable.
87 if runtime.GOARCH == "arm" || runtime.GOOS == "windows" {
90 if s := os.Getenv("GO_TEST_TIMEOUT_SCALE"); s != "" {
91 if sc, err := strconv.Atoi(s); err == nil {
98 case <-time.After(time.Duration(scale) * time.Minute):
103 if err := cmd.Wait(); err != nil {
104 t.Logf("%s %s exit status: %v", exe, name, err)
111 func buildTestProg(t *testing.T, binary string, flags ...string) (string, error) {
117 defer testprog.Unlock()
118 if testprog.dir == "" {
119 dir, err := os.MkdirTemp("", "go-build")
121 t.Fatalf("failed to create temp directory: %v", err)
124 toRemove = append(toRemove, dir)
127 if testprog.target == nil {
128 testprog.target = make(map[string]buildexe)
132 name += "_" + strings.Join(flags, "_")
134 target, ok := testprog.target[name]
136 return target.exe, target.err
139 exe := filepath.Join(testprog.dir, name+".exe")
140 cmd := exec.Command(testenv.GoToolPath(t), append([]string{"build", "-o", exe}, flags...)...)
141 cmd.Dir = "testdata/" + binary
142 out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
144 target.err = fmt.Errorf("building %s %v: %v\n%s", binary, flags, err, out)
145 testprog.target[name] = target
146 return "", target.err
149 testprog.target[name] = target
153 func TestVDSO(t *testing.T) {
155 output := runTestProg(t, "testprog", "SignalInVDSO")
158 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
162 func testCrashHandler(t *testing.T, cgo bool) {
163 type crashTest struct {
168 output = runTestProg(t, "testprogcgo", "Crash")
170 output = runTestProg(t, "testprog", "Crash")
172 want := "main: recovered done\nnew-thread: recovered done\nsecond-new-thread: recovered done\nmain-again: recovered done\n"
174 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
178 func TestCrashHandler(t *testing.T) {
179 testCrashHandler(t, false)
182 func testDeadlock(t *testing.T, name string) {
183 // External linking brings in cgo, causing deadlock detection not working.
184 testenv.MustInternalLink(t)
186 output := runTestProg(t, "testprog", name)
187 want := "fatal error: all goroutines are asleep - deadlock!\n"
188 if !strings.HasPrefix(output, want) {
189 t.Fatalf("output does not start with %q:\n%s", want, output)
193 func TestSimpleDeadlock(t *testing.T) {
194 testDeadlock(t, "SimpleDeadlock")
197 func TestInitDeadlock(t *testing.T) {
198 testDeadlock(t, "InitDeadlock")
201 func TestLockedDeadlock(t *testing.T) {
202 testDeadlock(t, "LockedDeadlock")
205 func TestLockedDeadlock2(t *testing.T) {
206 testDeadlock(t, "LockedDeadlock2")
209 func TestGoexitDeadlock(t *testing.T) {
210 // External linking brings in cgo, causing deadlock detection not working.
211 testenv.MustInternalLink(t)
213 output := runTestProg(t, "testprog", "GoexitDeadlock")
214 want := "no goroutines (main called runtime.Goexit) - deadlock!"
215 if !strings.Contains(output, want) {
216 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
220 func TestStackOverflow(t *testing.T) {
221 output := runTestProg(t, "testprog", "StackOverflow")
223 "runtime: goroutine stack exceeds 1474560-byte limit\n",
224 "fatal error: stack overflow",
225 // information about the current SP and stack bounds
229 if !strings.HasPrefix(output, want[0]) {
230 t.Errorf("output does not start with %q", want[0])
232 for _, s := range want[1:] {
233 if !strings.Contains(output, s) {
234 t.Errorf("output does not contain %q", s)
238 t.Logf("output:\n%s", output)
242 func TestThreadExhaustion(t *testing.T) {
243 output := runTestProg(t, "testprog", "ThreadExhaustion")
244 want := "runtime: program exceeds 10-thread limit\nfatal error: thread exhaustion"
245 if !strings.HasPrefix(output, want) {
246 t.Fatalf("output does not start with %q:\n%s", want, output)
250 func TestRecursivePanic(t *testing.T) {
251 output := runTestProg(t, "testprog", "RecursivePanic")
256 if !strings.HasPrefix(output, want) {
257 t.Fatalf("output does not start with %q:\n%s", want, output)
262 func TestRecursivePanic2(t *testing.T) {
263 output := runTestProg(t, "testprog", "RecursivePanic2")
269 if !strings.HasPrefix(output, want) {
270 t.Fatalf("output does not start with %q:\n%s", want, output)
275 func TestRecursivePanic3(t *testing.T) {
276 output := runTestProg(t, "testprog", "RecursivePanic3")
277 want := `panic: first panic
280 if !strings.HasPrefix(output, want) {
281 t.Fatalf("output does not start with %q:\n%s", want, output)
286 func TestRecursivePanic4(t *testing.T) {
287 output := runTestProg(t, "testprog", "RecursivePanic4")
288 want := `panic: first panic [recovered]
291 if !strings.HasPrefix(output, want) {
292 t.Fatalf("output does not start with %q:\n%s", want, output)
297 func TestRecursivePanic5(t *testing.T) {
298 output := runTestProg(t, "testprog", "RecursivePanic5")
303 if !strings.HasPrefix(output, want) {
304 t.Fatalf("output does not start with %q:\n%s", want, output)
309 func TestGoexitCrash(t *testing.T) {
310 // External linking brings in cgo, causing deadlock detection not working.
311 testenv.MustInternalLink(t)
313 output := runTestProg(t, "testprog", "GoexitExit")
314 want := "no goroutines (main called runtime.Goexit) - deadlock!"
315 if !strings.Contains(output, want) {
316 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
320 func TestGoexitDefer(t *testing.T) {
321 c := make(chan struct{})
326 t.Errorf("non-nil recover during Goexit")
332 // Note: if the defer fails to run, we will get a deadlock here
336 func TestGoNil(t *testing.T) {
337 output := runTestProg(t, "testprog", "GoNil")
338 want := "go of nil func value"
339 if !strings.Contains(output, want) {
340 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
344 func TestMainGoroutineID(t *testing.T) {
345 output := runTestProg(t, "testprog", "MainGoroutineID")
346 want := "panic: test\n\ngoroutine 1 [running]:\n"
347 if !strings.HasPrefix(output, want) {
348 t.Fatalf("output does not start with %q:\n%s", want, output)
352 func TestNoHelperGoroutines(t *testing.T) {
353 output := runTestProg(t, "testprog", "NoHelperGoroutines")
354 matches := regexp.MustCompile(`goroutine [0-9]+ \[`).FindAllStringSubmatch(output, -1)
355 if len(matches) != 1 || matches[0][0] != "goroutine 1 [" {
356 t.Fatalf("want to see only goroutine 1, see:\n%s", output)
360 func TestBreakpoint(t *testing.T) {
361 output := runTestProg(t, "testprog", "Breakpoint")
362 // If runtime.Breakpoint() is inlined, then the stack trace prints
363 // "runtime.Breakpoint(...)" instead of "runtime.Breakpoint()".
364 want := "runtime.Breakpoint("
365 if !strings.Contains(output, want) {
366 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
370 func TestGoexitInPanic(t *testing.T) {
371 // External linking brings in cgo, causing deadlock detection not working.
372 testenv.MustInternalLink(t)
374 // see issue 8774: this code used to trigger an infinite recursion
375 output := runTestProg(t, "testprog", "GoexitInPanic")
376 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
377 if !strings.HasPrefix(output, want) {
378 t.Fatalf("output does not start with %q:\n%s", want, output)
382 // Issue 14965: Runtime panics should be of type runtime.Error
383 func TestRuntimePanicWithRuntimeError(t *testing.T) {
384 testCases := [...]func(){
386 var m map[uint64]bool
390 ch := make(chan struct{})
395 var ch = make(chan struct{})
400 var s = make([]int, 2)
405 _ = make(chan bool, n)
408 close((chan bool)(nil))
412 for i, fn := range testCases {
413 got := panicValue(fn)
414 if _, ok := got.(runtime.Error); !ok {
415 t.Errorf("test #%d: recovered value %v(type %T) does not implement runtime.Error", i, got, got)
420 func panicValue(fn func()) (recovered interface{}) {
422 recovered = recover()
428 func TestPanicAfterGoexit(t *testing.T) {
429 // an uncaught panic should still work after goexit
430 output := runTestProg(t, "testprog", "PanicAfterGoexit")
431 want := "panic: hello"
432 if !strings.HasPrefix(output, want) {
433 t.Fatalf("output does not start with %q:\n%s", want, output)
437 func TestRecoveredPanicAfterGoexit(t *testing.T) {
438 // External linking brings in cgo, causing deadlock detection not working.
439 testenv.MustInternalLink(t)
441 output := runTestProg(t, "testprog", "RecoveredPanicAfterGoexit")
442 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
443 if !strings.HasPrefix(output, want) {
444 t.Fatalf("output does not start with %q:\n%s", want, output)
448 func TestRecoverBeforePanicAfterGoexit(t *testing.T) {
449 // External linking brings in cgo, causing deadlock detection not working.
450 testenv.MustInternalLink(t)
453 output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit")
454 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
455 if !strings.HasPrefix(output, want) {
456 t.Fatalf("output does not start with %q:\n%s", want, output)
460 func TestRecoverBeforePanicAfterGoexit2(t *testing.T) {
461 // External linking brings in cgo, causing deadlock detection not working.
462 testenv.MustInternalLink(t)
465 output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit2")
466 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
467 if !strings.HasPrefix(output, want) {
468 t.Fatalf("output does not start with %q:\n%s", want, output)
472 func TestNetpollDeadlock(t *testing.T) {
473 if os.Getenv("GO_BUILDER_NAME") == "darwin-amd64-10_12" {
474 // A suspected kernel bug in macOS 10.12 occasionally results in
475 // an apparent deadlock when dialing localhost. The errors have not
476 // been observed on newer versions of the OS, so we don't plan to work
477 // around them. See https://golang.org/issue/22019.
478 testenv.SkipFlaky(t, 22019)
482 output := runTestProg(t, "testprognet", "NetpollDeadlock")
484 if !strings.HasSuffix(output, want) {
485 t.Fatalf("output does not start with %q:\n%s", want, output)
489 func TestPanicTraceback(t *testing.T) {
491 output := runTestProg(t, "testprog", "PanicTraceback")
492 want := "panic: hello\n\tpanic: panic pt2\n\tpanic: panic pt1\n"
493 if !strings.HasPrefix(output, want) {
494 t.Fatalf("output does not start with %q:\n%s", want, output)
497 // Check functions in the traceback.
498 fns := []string{"main.pt1.func1", "panic", "main.pt2.func1", "panic", "main.pt2", "main.pt1"}
499 for _, fn := range fns {
500 re := regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(fn) + `\(.*\n`)
501 idx := re.FindStringIndex(output)
503 t.Fatalf("expected %q function in traceback:\n%s", fn, output)
505 output = output[idx[1]:]
509 func testPanicDeadlock(t *testing.T, name string, want string) {
511 output := runTestProg(t, "testprog", name)
512 if !strings.HasPrefix(output, want) {
513 t.Fatalf("output does not start with %q:\n%s", want, output)
517 func TestPanicDeadlockGosched(t *testing.T) {
518 testPanicDeadlock(t, "GoschedInPanic", "panic: errorThatGosched\n\n")
521 func TestPanicDeadlockSyscall(t *testing.T) {
522 testPanicDeadlock(t, "SyscallInPanic", "1\n2\npanic: 3\n\n")
525 func TestPanicLoop(t *testing.T) {
526 output := runTestProg(t, "testprog", "PanicLoop")
527 if want := "panic while printing panic value"; !strings.Contains(output, want) {
528 t.Errorf("output does not contain %q:\n%s", want, output)
532 func TestMemPprof(t *testing.T) {
533 testenv.MustHaveGoRun(t)
535 exe, err := buildTestProg(t, "testprog")
540 got, err := testenv.CleanCmdEnv(exec.Command(exe, "MemProf")).CombinedOutput()
544 fn := strings.TrimSpace(string(got))
547 for try := 0; try < 2; try++ {
548 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-alloc_space", "-top"))
549 // Check that pprof works both with and without explicit executable on command line.
551 cmd.Args = append(cmd.Args, exe, fn)
553 cmd.Args = append(cmd.Args, fn)
556 for i, e := range cmd.Env {
557 if strings.HasPrefix(e, "PPROF_TMPDIR=") {
558 cmd.Env[i] = "PPROF_TMPDIR=" + os.TempDir()
564 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
567 top, err := cmd.CombinedOutput()
568 t.Logf("%s:\n%s", cmd.Args, top)
571 } else if !bytes.Contains(top, []byte("MemProf")) {
572 t.Error("missing MemProf in pprof output")
577 var concurrentMapTest = flag.Bool("run_concurrent_map_tests", false, "also run flaky concurrent map tests")
579 func TestConcurrentMapWrites(t *testing.T) {
580 if !*concurrentMapTest {
581 t.Skip("skipping without -run_concurrent_map_tests")
583 testenv.MustHaveGoRun(t)
584 output := runTestProg(t, "testprog", "concurrentMapWrites")
585 want := "fatal error: concurrent map writes"
586 if !strings.HasPrefix(output, want) {
587 t.Fatalf("output does not start with %q:\n%s", want, output)
590 func TestConcurrentMapReadWrite(t *testing.T) {
591 if !*concurrentMapTest {
592 t.Skip("skipping without -run_concurrent_map_tests")
594 testenv.MustHaveGoRun(t)
595 output := runTestProg(t, "testprog", "concurrentMapReadWrite")
596 want := "fatal error: concurrent map read and map write"
597 if !strings.HasPrefix(output, want) {
598 t.Fatalf("output does not start with %q:\n%s", want, output)
601 func TestConcurrentMapIterateWrite(t *testing.T) {
602 if !*concurrentMapTest {
603 t.Skip("skipping without -run_concurrent_map_tests")
605 testenv.MustHaveGoRun(t)
606 output := runTestProg(t, "testprog", "concurrentMapIterateWrite")
607 want := "fatal error: concurrent map iteration and map write"
608 if !strings.HasPrefix(output, want) {
609 t.Fatalf("output does not start with %q:\n%s", want, output)
617 func (p *point) negate() {
622 // Test for issue #10152.
623 func TestPanicInlined(t *testing.T) {
627 t.Fatalf("recover failed")
629 buf := make([]byte, 2048)
630 n := runtime.Stack(buf, false)
632 if !bytes.Contains(buf, []byte("(*point).negate(")) {
633 t.Fatalf("expecting stack trace to contain call to (*point).negate()")
641 // Test for issues #3934 and #20018.
642 // We want to delay exiting until a panic print is complete.
643 func TestPanicRace(t *testing.T) {
644 testenv.MustHaveGoRun(t)
646 exe, err := buildTestProg(t, "testprog")
651 // The test is intentionally racy, and in my testing does not
652 // produce the expected output about 0.05% of the time.
653 // So run the program in a loop and only fail the test if we
654 // get the wrong output ten times in a row.
657 for i := 0; i < tries; i++ {
658 got, err := testenv.CleanCmdEnv(exec.Command(exe, "PanicRace")).CombinedOutput()
660 t.Logf("try %d: program exited successfully, should have failed", i+1)
665 t.Logf("try %d:\n", i+1)
674 for _, want := range wants {
675 if !bytes.Contains(got, []byte(want)) {
676 t.Logf("did not find expected string %q", want)
681 // Test generated expected output.
684 t.Errorf("test ran %d times without producing expected output", tries)
687 func TestBadTraceback(t *testing.T) {
688 output := runTestProg(t, "testprog", "BadTraceback")
689 for _, want := range []string{
690 "runtime: unexpected return pc",
692 "00000bad", // Smashed LR in hex dump
693 "<main.badLR", // Symbolization in hex dump (badLR1 or badLR2)
695 if !strings.Contains(output, want) {
696 t.Errorf("output does not contain %q:\n%s", want, output)
701 func TestTimePprof(t *testing.T) {
702 // Pass GOTRACEBACK for issue #41120 to try to get more
703 // information on timeout.
704 fn := runTestProg(t, "testprog", "TimeProf", "GOTRACEBACK=crash")
705 fn = strings.TrimSpace(fn)
708 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-top", "-nodecount=1", fn))
709 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
710 top, err := cmd.CombinedOutput()
714 } else if bytes.Contains(top, []byte("ExternalCode")) {
715 t.Error("profiler refers to ExternalCode")
719 // Test that runtime.abort does so.
720 func TestAbort(t *testing.T) {
721 // Pass GOTRACEBACK to ensure we get runtime frames.
722 output := runTestProg(t, "testprog", "Abort", "GOTRACEBACK=system")
723 if want := "runtime.abort"; !strings.Contains(output, want) {
724 t.Errorf("output does not contain %q:\n%s", want, output)
726 if strings.Contains(output, "BAD") {
727 t.Errorf("output contains BAD:\n%s", output)
729 // Check that it's a signal traceback.
731 // For systems that use a breakpoint, check specifically for that.
732 switch runtime.GOARCH {
734 switch runtime.GOOS {
736 want = "sys: breakpoint"
738 want = "Exception 0x80000003"
743 if !strings.Contains(output, want) {
744 t.Errorf("output does not contain %q:\n%s", want, output)
748 // For TestRuntimePanic: test a panic in the runtime package without
749 // involving the testing harness.
751 if os.Getenv("GO_TEST_RUNTIME_PANIC") == "1" {
753 if r := recover(); r != nil {
754 // We expect to crash, so exit 0
755 // to indicate failure.
759 runtime.PanicForTesting(nil, 1)
760 // We expect to crash, so exit 0 to indicate failure.
765 func TestRuntimePanic(t *testing.T) {
766 testenv.MustHaveExec(t)
767 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestRuntimePanic"))
768 cmd.Env = append(cmd.Env, "GO_TEST_RUNTIME_PANIC=1")
769 out, err := cmd.CombinedOutput()
772 t.Error("child process did not fail")
773 } else if want := "runtime.unexportedPanicForTesting"; !bytes.Contains(out, []byte(want)) {
774 t.Errorf("output did not contain expected string %q", want)
778 // Test that g0 stack overflows are handled gracefully.
779 func TestG0StackOverflow(t *testing.T) {
780 testenv.MustHaveExec(t)
782 switch runtime.GOOS {
783 case "darwin", "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "android":
784 t.Skipf("g0 stack is wrong on pthread platforms (see golang.org/issue/26061)")
787 if os.Getenv("TEST_G0_STACK_OVERFLOW") != "1" {
788 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestG0StackOverflow", "-test.v"))
789 cmd.Env = append(cmd.Env, "TEST_G0_STACK_OVERFLOW=1")
790 out, err := cmd.CombinedOutput()
791 // Don't check err since it's expected to crash.
792 if n := strings.Count(string(out), "morestack on g0\n"); n != 1 {
793 t.Fatalf("%s\n(exit status %v)", out, err)
795 // Check that it's a signal-style traceback.
796 if runtime.GOOS != "windows" {
797 if want := "PC="; !strings.Contains(string(out), want) {
798 t.Errorf("output does not contain %q:\n%s", want, out)
804 runtime.G0StackOverflow()
807 // Test that panic message is not clobbered.
809 func TestDoublePanic(t *testing.T) {
810 output := runTestProg(t, "testprog", "DoublePanic", "GODEBUG=clobberfree=1")
811 wants := []string{"panic: XXX", "panic: YYY"}
812 for _, want := range wants {
813 if !strings.Contains(output, want) {
814 t.Errorf("output:\n%s\n\nwant output containing: %s", output, want)