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 {
47 func runTestProg(t *testing.T, binary, name string, env ...string) string {
52 testenv.MustHaveGoBuild(t)
54 exe, err := buildTestProg(t, binary)
59 return runBuiltTestProg(t, exe, name, env...)
62 func runBuiltTestProg(t *testing.T, exe, name string, env ...string) string {
67 testenv.MustHaveGoBuild(t)
69 cmd := testenv.CleanCmdEnv(exec.Command(exe, name))
70 cmd.Env = append(cmd.Env, env...)
72 cmd.Env = append(cmd.Env, "RUNTIME_TEST_SHORT=1")
77 if err := cmd.Start(); err != nil {
78 t.Fatalf("starting %s %s: %v", exe, name, err)
81 // If the process doesn't complete within 1 minute,
82 // assume it is hanging and kill it to get a stack trace.
84 done := make(chan bool)
87 // This GOARCH/GOOS test is copied from cmd/dist/test.go.
88 // TODO(iant): Have cmd/dist update the environment variable.
89 if runtime.GOARCH == "arm" || runtime.GOOS == "windows" {
92 if s := os.Getenv("GO_TEST_TIMEOUT_SCALE"); s != "" {
93 if sc, err := strconv.Atoi(s); err == nil {
100 case <-time.After(time.Duration(scale) * time.Minute):
105 if err := cmd.Wait(); err != nil {
106 t.Logf("%s %s exit status: %v", exe, name, err)
113 var serializeBuild = make(chan bool, 2)
115 func buildTestProg(t *testing.T, binary string, flags ...string) (string, error) {
119 testenv.MustHaveGoBuild(t)
122 if testprog.dir == "" {
123 dir, err := os.MkdirTemp("", "go-build")
125 t.Fatalf("failed to create temp directory: %v", err)
128 toRemove = append(toRemove, dir)
131 if testprog.target == nil {
132 testprog.target = make(map[string]*buildexe)
136 name += "_" + strings.Join(flags, "_")
138 target, ok := testprog.target[name]
141 testprog.target[name] = target
146 // Unlock testprog while actually building, so that other
147 // tests can look up executables that were already built.
150 target.once.Do(func() {
151 // Only do two "go build"'s at a time,
152 // to keep load from getting too high.
153 serializeBuild <- true
154 defer func() { <-serializeBuild }()
156 // Don't get confused if testenv.GoToolPath calls t.Skip.
157 target.err = errors.New("building test called t.Skip")
159 exe := filepath.Join(dir, name+".exe")
161 t.Logf("running go build -o %s %s", exe, strings.Join(flags, " "))
162 cmd := exec.Command(testenv.GoToolPath(t), append([]string{"build", "-o", exe}, flags...)...)
163 cmd.Dir = "testdata/" + binary
164 out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
166 target.err = fmt.Errorf("building %s %v: %v\n%s", binary, flags, err, out)
173 return target.exe, target.err
176 func TestVDSO(t *testing.T) {
178 output := runTestProg(t, "testprog", "SignalInVDSO")
181 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
185 func testCrashHandler(t *testing.T, cgo bool) {
186 type crashTest struct {
191 output = runTestProg(t, "testprogcgo", "Crash")
193 output = runTestProg(t, "testprog", "Crash")
195 want := "main: recovered done\nnew-thread: recovered done\nsecond-new-thread: recovered done\nmain-again: recovered done\n"
197 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
201 func TestCrashHandler(t *testing.T) {
202 testCrashHandler(t, false)
205 func testDeadlock(t *testing.T, name string) {
206 // External linking brings in cgo, causing deadlock detection not working.
207 testenv.MustInternalLink(t)
209 output := runTestProg(t, "testprog", name)
210 want := "fatal error: all goroutines are asleep - deadlock!\n"
211 if !strings.HasPrefix(output, want) {
212 t.Fatalf("output does not start with %q:\n%s", want, output)
216 func TestSimpleDeadlock(t *testing.T) {
217 testDeadlock(t, "SimpleDeadlock")
220 func TestInitDeadlock(t *testing.T) {
221 testDeadlock(t, "InitDeadlock")
224 func TestLockedDeadlock(t *testing.T) {
225 testDeadlock(t, "LockedDeadlock")
228 func TestLockedDeadlock2(t *testing.T) {
229 testDeadlock(t, "LockedDeadlock2")
232 func TestGoexitDeadlock(t *testing.T) {
233 // External linking brings in cgo, causing deadlock detection not working.
234 testenv.MustInternalLink(t)
236 output := runTestProg(t, "testprog", "GoexitDeadlock")
237 want := "no goroutines (main called runtime.Goexit) - deadlock!"
238 if !strings.Contains(output, want) {
239 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
243 func TestStackOverflow(t *testing.T) {
244 output := runTestProg(t, "testprog", "StackOverflow")
246 "runtime: goroutine stack exceeds 1474560-byte limit\n",
247 "fatal error: stack overflow",
248 // information about the current SP and stack bounds
252 if !strings.HasPrefix(output, want[0]) {
253 t.Errorf("output does not start with %q", want[0])
255 for _, s := range want[1:] {
256 if !strings.Contains(output, s) {
257 t.Errorf("output does not contain %q", s)
261 t.Logf("output:\n%s", output)
265 func TestThreadExhaustion(t *testing.T) {
266 output := runTestProg(t, "testprog", "ThreadExhaustion")
267 want := "runtime: program exceeds 10-thread limit\nfatal error: thread exhaustion"
268 if !strings.HasPrefix(output, want) {
269 t.Fatalf("output does not start with %q:\n%s", want, output)
273 func TestRecursivePanic(t *testing.T) {
274 output := runTestProg(t, "testprog", "RecursivePanic")
279 if !strings.HasPrefix(output, want) {
280 t.Fatalf("output does not start with %q:\n%s", want, output)
285 func TestRecursivePanic2(t *testing.T) {
286 output := runTestProg(t, "testprog", "RecursivePanic2")
292 if !strings.HasPrefix(output, want) {
293 t.Fatalf("output does not start with %q:\n%s", want, output)
298 func TestRecursivePanic3(t *testing.T) {
299 output := runTestProg(t, "testprog", "RecursivePanic3")
300 want := `panic: first panic
303 if !strings.HasPrefix(output, want) {
304 t.Fatalf("output does not start with %q:\n%s", want, output)
309 func TestRecursivePanic4(t *testing.T) {
310 output := runTestProg(t, "testprog", "RecursivePanic4")
311 want := `panic: first panic [recovered]
314 if !strings.HasPrefix(output, want) {
315 t.Fatalf("output does not start with %q:\n%s", want, output)
320 func TestRecursivePanic5(t *testing.T) {
321 output := runTestProg(t, "testprog", "RecursivePanic5")
326 if !strings.HasPrefix(output, want) {
327 t.Fatalf("output does not start with %q:\n%s", want, output)
332 func TestGoexitCrash(t *testing.T) {
333 // External linking brings in cgo, causing deadlock detection not working.
334 testenv.MustInternalLink(t)
336 output := runTestProg(t, "testprog", "GoexitExit")
337 want := "no goroutines (main called runtime.Goexit) - deadlock!"
338 if !strings.Contains(output, want) {
339 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
343 func TestGoexitDefer(t *testing.T) {
344 c := make(chan struct{})
349 t.Errorf("non-nil recover during Goexit")
355 // Note: if the defer fails to run, we will get a deadlock here
359 func TestGoNil(t *testing.T) {
360 output := runTestProg(t, "testprog", "GoNil")
361 want := "go of nil func value"
362 if !strings.Contains(output, want) {
363 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
367 func TestMainGoroutineID(t *testing.T) {
368 output := runTestProg(t, "testprog", "MainGoroutineID")
369 want := "panic: test\n\ngoroutine 1 [running]:\n"
370 if !strings.HasPrefix(output, want) {
371 t.Fatalf("output does not start with %q:\n%s", want, output)
375 func TestNoHelperGoroutines(t *testing.T) {
376 output := runTestProg(t, "testprog", "NoHelperGoroutines")
377 matches := regexp.MustCompile(`goroutine [0-9]+ \[`).FindAllStringSubmatch(output, -1)
378 if len(matches) != 1 || matches[0][0] != "goroutine 1 [" {
379 t.Fatalf("want to see only goroutine 1, see:\n%s", output)
383 func TestBreakpoint(t *testing.T) {
384 output := runTestProg(t, "testprog", "Breakpoint")
385 // If runtime.Breakpoint() is inlined, then the stack trace prints
386 // "runtime.Breakpoint(...)" instead of "runtime.Breakpoint()".
387 want := "runtime.Breakpoint("
388 if !strings.Contains(output, want) {
389 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
393 func TestGoexitInPanic(t *testing.T) {
394 // External linking brings in cgo, causing deadlock detection not working.
395 testenv.MustInternalLink(t)
397 // see issue 8774: this code used to trigger an infinite recursion
398 output := runTestProg(t, "testprog", "GoexitInPanic")
399 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
400 if !strings.HasPrefix(output, want) {
401 t.Fatalf("output does not start with %q:\n%s", want, output)
405 // Issue 14965: Runtime panics should be of type runtime.Error
406 func TestRuntimePanicWithRuntimeError(t *testing.T) {
407 testCases := [...]func(){
409 var m map[uint64]bool
413 ch := make(chan struct{})
418 var ch = make(chan struct{})
423 var s = make([]int, 2)
428 _ = make(chan bool, n)
431 close((chan bool)(nil))
435 for i, fn := range testCases {
436 got := panicValue(fn)
437 if _, ok := got.(runtime.Error); !ok {
438 t.Errorf("test #%d: recovered value %v(type %T) does not implement runtime.Error", i, got, got)
443 func panicValue(fn func()) (recovered interface{}) {
445 recovered = recover()
451 func TestPanicAfterGoexit(t *testing.T) {
452 // an uncaught panic should still work after goexit
453 output := runTestProg(t, "testprog", "PanicAfterGoexit")
454 want := "panic: hello"
455 if !strings.HasPrefix(output, want) {
456 t.Fatalf("output does not start with %q:\n%s", want, output)
460 func TestRecoveredPanicAfterGoexit(t *testing.T) {
461 // External linking brings in cgo, causing deadlock detection not working.
462 testenv.MustInternalLink(t)
464 output := runTestProg(t, "testprog", "RecoveredPanicAfterGoexit")
465 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
466 if !strings.HasPrefix(output, want) {
467 t.Fatalf("output does not start with %q:\n%s", want, output)
471 func TestRecoverBeforePanicAfterGoexit(t *testing.T) {
472 // External linking brings in cgo, causing deadlock detection not working.
473 testenv.MustInternalLink(t)
476 output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit")
477 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
478 if !strings.HasPrefix(output, want) {
479 t.Fatalf("output does not start with %q:\n%s", want, output)
483 func TestRecoverBeforePanicAfterGoexit2(t *testing.T) {
484 // External linking brings in cgo, causing deadlock detection not working.
485 testenv.MustInternalLink(t)
488 output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit2")
489 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
490 if !strings.HasPrefix(output, want) {
491 t.Fatalf("output does not start with %q:\n%s", want, output)
495 func TestNetpollDeadlock(t *testing.T) {
497 output := runTestProg(t, "testprognet", "NetpollDeadlock")
499 if !strings.HasSuffix(output, want) {
500 t.Fatalf("output does not start with %q:\n%s", want, output)
504 func TestPanicTraceback(t *testing.T) {
506 output := runTestProg(t, "testprog", "PanicTraceback")
507 want := "panic: hello\n\tpanic: panic pt2\n\tpanic: panic pt1\n"
508 if !strings.HasPrefix(output, want) {
509 t.Fatalf("output does not start with %q:\n%s", want, output)
512 // Check functions in the traceback.
513 fns := []string{"main.pt1.func1", "panic", "main.pt2.func1", "panic", "main.pt2", "main.pt1"}
514 for _, fn := range fns {
515 re := regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(fn) + `\(.*\n`)
516 idx := re.FindStringIndex(output)
518 t.Fatalf("expected %q function in traceback:\n%s", fn, output)
520 output = output[idx[1]:]
524 func testPanicDeadlock(t *testing.T, name string, want string) {
526 output := runTestProg(t, "testprog", name)
527 if !strings.HasPrefix(output, want) {
528 t.Fatalf("output does not start with %q:\n%s", want, output)
532 func TestPanicDeadlockGosched(t *testing.T) {
533 testPanicDeadlock(t, "GoschedInPanic", "panic: errorThatGosched\n\n")
536 func TestPanicDeadlockSyscall(t *testing.T) {
537 testPanicDeadlock(t, "SyscallInPanic", "1\n2\npanic: 3\n\n")
540 func TestPanicLoop(t *testing.T) {
541 output := runTestProg(t, "testprog", "PanicLoop")
542 if want := "panic while printing panic value"; !strings.Contains(output, want) {
543 t.Errorf("output does not contain %q:\n%s", want, output)
547 func TestMemPprof(t *testing.T) {
548 testenv.MustHaveGoRun(t)
550 exe, err := buildTestProg(t, "testprog")
555 got, err := testenv.CleanCmdEnv(exec.Command(exe, "MemProf")).CombinedOutput()
559 fn := strings.TrimSpace(string(got))
562 for try := 0; try < 2; try++ {
563 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-alloc_space", "-top"))
564 // Check that pprof works both with and without explicit executable on command line.
566 cmd.Args = append(cmd.Args, exe, fn)
568 cmd.Args = append(cmd.Args, fn)
571 for i, e := range cmd.Env {
572 if strings.HasPrefix(e, "PPROF_TMPDIR=") {
573 cmd.Env[i] = "PPROF_TMPDIR=" + os.TempDir()
579 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
582 top, err := cmd.CombinedOutput()
583 t.Logf("%s:\n%s", cmd.Args, top)
586 } else if !bytes.Contains(top, []byte("MemProf")) {
587 t.Error("missing MemProf in pprof output")
592 var concurrentMapTest = flag.Bool("run_concurrent_map_tests", false, "also run flaky concurrent map tests")
594 func TestConcurrentMapWrites(t *testing.T) {
595 if !*concurrentMapTest {
596 t.Skip("skipping without -run_concurrent_map_tests")
598 testenv.MustHaveGoRun(t)
599 output := runTestProg(t, "testprog", "concurrentMapWrites")
600 want := "fatal error: concurrent map writes"
601 if !strings.HasPrefix(output, want) {
602 t.Fatalf("output does not start with %q:\n%s", want, output)
605 func TestConcurrentMapReadWrite(t *testing.T) {
606 if !*concurrentMapTest {
607 t.Skip("skipping without -run_concurrent_map_tests")
609 testenv.MustHaveGoRun(t)
610 output := runTestProg(t, "testprog", "concurrentMapReadWrite")
611 want := "fatal error: concurrent map read and map write"
612 if !strings.HasPrefix(output, want) {
613 t.Fatalf("output does not start with %q:\n%s", want, output)
616 func TestConcurrentMapIterateWrite(t *testing.T) {
617 if !*concurrentMapTest {
618 t.Skip("skipping without -run_concurrent_map_tests")
620 testenv.MustHaveGoRun(t)
621 output := runTestProg(t, "testprog", "concurrentMapIterateWrite")
622 want := "fatal error: concurrent map iteration and map write"
623 if !strings.HasPrefix(output, want) {
624 t.Fatalf("output does not start with %q:\n%s", want, output)
632 func (p *point) negate() {
637 // Test for issue #10152.
638 func TestPanicInlined(t *testing.T) {
642 t.Fatalf("recover failed")
644 buf := make([]byte, 2048)
645 n := runtime.Stack(buf, false)
647 if !bytes.Contains(buf, []byte("(*point).negate(")) {
648 t.Fatalf("expecting stack trace to contain call to (*point).negate()")
656 // Test for issues #3934 and #20018.
657 // We want to delay exiting until a panic print is complete.
658 func TestPanicRace(t *testing.T) {
659 testenv.MustHaveGoRun(t)
661 exe, err := buildTestProg(t, "testprog")
666 // The test is intentionally racy, and in my testing does not
667 // produce the expected output about 0.05% of the time.
668 // So run the program in a loop and only fail the test if we
669 // get the wrong output ten times in a row.
672 for i := 0; i < tries; i++ {
673 got, err := testenv.CleanCmdEnv(exec.Command(exe, "PanicRace")).CombinedOutput()
675 t.Logf("try %d: program exited successfully, should have failed", i+1)
680 t.Logf("try %d:\n", i+1)
689 for _, want := range wants {
690 if !bytes.Contains(got, []byte(want)) {
691 t.Logf("did not find expected string %q", want)
696 // Test generated expected output.
699 t.Errorf("test ran %d times without producing expected output", tries)
702 func TestBadTraceback(t *testing.T) {
703 output := runTestProg(t, "testprog", "BadTraceback")
704 for _, want := range []string{
705 "runtime: unexpected return pc",
707 "00000bad", // Smashed LR in hex dump
708 "<main.badLR", // Symbolization in hex dump (badLR1 or badLR2)
710 if !strings.Contains(output, want) {
711 t.Errorf("output does not contain %q:\n%s", want, output)
716 func TestTimePprof(t *testing.T) {
717 // Pass GOTRACEBACK for issue #41120 to try to get more
718 // information on timeout.
719 fn := runTestProg(t, "testprog", "TimeProf", "GOTRACEBACK=crash")
720 fn = strings.TrimSpace(fn)
723 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-top", "-nodecount=1", fn))
724 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
725 top, err := cmd.CombinedOutput()
729 } else if bytes.Contains(top, []byte("ExternalCode")) {
730 t.Error("profiler refers to ExternalCode")
734 // Test that runtime.abort does so.
735 func TestAbort(t *testing.T) {
736 // Pass GOTRACEBACK to ensure we get runtime frames.
737 output := runTestProg(t, "testprog", "Abort", "GOTRACEBACK=system")
738 if want := "runtime.abort"; !strings.Contains(output, want) {
739 t.Errorf("output does not contain %q:\n%s", want, output)
741 if strings.Contains(output, "BAD") {
742 t.Errorf("output contains BAD:\n%s", output)
744 // Check that it's a signal traceback.
746 // For systems that use a breakpoint, check specifically for that.
747 switch runtime.GOARCH {
749 switch runtime.GOOS {
751 want = "sys: breakpoint"
753 want = "Exception 0x80000003"
758 if !strings.Contains(output, want) {
759 t.Errorf("output does not contain %q:\n%s", want, output)
763 // For TestRuntimePanic: test a panic in the runtime package without
764 // involving the testing harness.
766 if os.Getenv("GO_TEST_RUNTIME_PANIC") == "1" {
768 if r := recover(); r != nil {
769 // We expect to crash, so exit 0
770 // to indicate failure.
774 runtime.PanicForTesting(nil, 1)
775 // We expect to crash, so exit 0 to indicate failure.
780 func TestRuntimePanic(t *testing.T) {
781 testenv.MustHaveExec(t)
782 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestRuntimePanic"))
783 cmd.Env = append(cmd.Env, "GO_TEST_RUNTIME_PANIC=1")
784 out, err := cmd.CombinedOutput()
787 t.Error("child process did not fail")
788 } else if want := "runtime.unexportedPanicForTesting"; !bytes.Contains(out, []byte(want)) {
789 t.Errorf("output did not contain expected string %q", want)
793 // Test that g0 stack overflows are handled gracefully.
794 func TestG0StackOverflow(t *testing.T) {
795 testenv.MustHaveExec(t)
797 switch runtime.GOOS {
798 case "darwin", "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "android":
799 t.Skipf("g0 stack is wrong on pthread platforms (see golang.org/issue/26061)")
802 if os.Getenv("TEST_G0_STACK_OVERFLOW") != "1" {
803 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestG0StackOverflow", "-test.v"))
804 cmd.Env = append(cmd.Env, "TEST_G0_STACK_OVERFLOW=1")
805 out, err := cmd.CombinedOutput()
806 // Don't check err since it's expected to crash.
807 if n := strings.Count(string(out), "morestack on g0\n"); n != 1 {
808 t.Fatalf("%s\n(exit status %v)", out, err)
810 // Check that it's a signal-style traceback.
811 if runtime.GOOS != "windows" {
812 if want := "PC="; !strings.Contains(string(out), want) {
813 t.Errorf("output does not contain %q:\n%s", want, out)
819 runtime.G0StackOverflow()
822 // Test that panic message is not clobbered.
824 func TestDoublePanic(t *testing.T) {
825 output := runTestProg(t, "testprog", "DoublePanic", "GODEBUG=clobberfree=1")
826 wants := []string{"panic: XXX", "panic: YYY"}
827 for _, want := range wants {
828 if !strings.Contains(output, want) {
829 t.Errorf("output:\n%s\n\nwant output containing: %s", output, want)