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) {
27 _, coreErrBefore := os.Stat("core")
30 for _, file := range toRemove {
34 _, coreErrAfter := os.Stat("core")
35 if coreErrBefore != nil && coreErrAfter == nil {
36 fmt.Fprintln(os.Stderr, "runtime.test: some test left a core file behind")
48 target map[string]*buildexe
51 type buildexe struct {
57 func runTestProg(t *testing.T, binary, name string, env ...string) string {
62 testenv.MustHaveGoBuild(t)
65 exe, err := buildTestProg(t, binary)
70 return runBuiltTestProg(t, exe, name, env...)
73 func runBuiltTestProg(t *testing.T, exe, name string, env ...string) string {
82 cmd := testenv.CleanCmdEnv(testenv.Command(t, exe, name))
83 cmd.Env = append(cmd.Env, env...)
85 cmd.Env = append(cmd.Env, "RUNTIME_TEST_SHORT=1")
87 out, err := cmd.CombinedOutput()
89 t.Logf("%v (%v): ok", cmd, time.Since(start))
91 if _, ok := err.(*exec.ExitError); ok {
92 t.Logf("%v: %v", cmd, err)
93 } else if errors.Is(err, exec.ErrWaitDelay) {
94 t.Fatalf("%v: %v", cmd, err)
96 t.Fatalf("%v failed to start: %v", cmd, err)
102 var serializeBuild = make(chan bool, 2)
104 func buildTestProg(t *testing.T, binary string, flags ...string) (string, error) {
108 testenv.MustHaveGoBuild(t)
111 if testprog.dir == "" {
112 dir, err := os.MkdirTemp("", "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]
130 testprog.target[name] = target
135 // Unlock testprog while actually building, so that other
136 // tests can look up executables that were already built.
139 target.once.Do(func() {
140 // Only do two "go build"'s at a time,
141 // to keep load from getting too high.
142 serializeBuild <- true
143 defer func() { <-serializeBuild }()
145 // Don't get confused if testenv.GoToolPath calls t.Skip.
146 target.err = errors.New("building test called t.Skip")
148 exe := filepath.Join(dir, name+".exe")
151 cmd := exec.Command(testenv.GoToolPath(t), append([]string{"build", "-o", exe}, flags...)...)
152 t.Logf("running %v", cmd)
153 cmd.Dir = "testdata/" + binary
154 out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
156 target.err = fmt.Errorf("building %s %v: %v\n%s", binary, flags, err, out)
158 t.Logf("built %v in %v", name, time.Since(start))
164 return target.exe, target.err
167 func TestVDSO(t *testing.T) {
169 output := runTestProg(t, "testprog", "SignalInVDSO")
172 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
176 func testCrashHandler(t *testing.T, cgo bool) {
177 type crashTest struct {
182 output = runTestProg(t, "testprogcgo", "Crash")
184 output = runTestProg(t, "testprog", "Crash")
186 want := "main: recovered done\nnew-thread: recovered done\nsecond-new-thread: recovered done\nmain-again: recovered done\n"
188 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
192 func TestCrashHandler(t *testing.T) {
193 testCrashHandler(t, false)
196 func testDeadlock(t *testing.T, name string) {
197 // External linking brings in cgo, causing deadlock detection not working.
198 testenv.MustInternalLink(t, false)
200 output := runTestProg(t, "testprog", name)
201 want := "fatal error: all goroutines are asleep - deadlock!\n"
202 if !strings.HasPrefix(output, want) {
203 t.Fatalf("output does not start with %q:\n%s", want, output)
207 func TestSimpleDeadlock(t *testing.T) {
208 testDeadlock(t, "SimpleDeadlock")
211 func TestInitDeadlock(t *testing.T) {
212 testDeadlock(t, "InitDeadlock")
215 func TestLockedDeadlock(t *testing.T) {
216 testDeadlock(t, "LockedDeadlock")
219 func TestLockedDeadlock2(t *testing.T) {
220 testDeadlock(t, "LockedDeadlock2")
223 func TestGoexitDeadlock(t *testing.T) {
224 // External linking brings in cgo, causing deadlock detection not working.
225 testenv.MustInternalLink(t, false)
227 output := runTestProg(t, "testprog", "GoexitDeadlock")
228 want := "no goroutines (main called runtime.Goexit) - deadlock!"
229 if !strings.Contains(output, want) {
230 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
234 func TestStackOverflow(t *testing.T) {
235 output := runTestProg(t, "testprog", "StackOverflow")
237 "runtime: goroutine stack exceeds 1474560-byte limit\n",
238 "fatal error: stack overflow",
239 // information about the current SP and stack bounds
243 if !strings.HasPrefix(output, want[0]) {
244 t.Errorf("output does not start with %q", want[0])
246 for _, s := range want[1:] {
247 if !strings.Contains(output, s) {
248 t.Errorf("output does not contain %q", s)
252 t.Logf("output:\n%s", output)
256 func TestThreadExhaustion(t *testing.T) {
257 output := runTestProg(t, "testprog", "ThreadExhaustion")
258 want := "runtime: program exceeds 10-thread limit\nfatal error: thread exhaustion"
259 if !strings.HasPrefix(output, want) {
260 t.Fatalf("output does not start with %q:\n%s", want, output)
264 func TestRecursivePanic(t *testing.T) {
265 output := runTestProg(t, "testprog", "RecursivePanic")
270 if !strings.HasPrefix(output, want) {
271 t.Fatalf("output does not start with %q:\n%s", want, output)
276 func TestRecursivePanic2(t *testing.T) {
277 output := runTestProg(t, "testprog", "RecursivePanic2")
283 if !strings.HasPrefix(output, want) {
284 t.Fatalf("output does not start with %q:\n%s", want, output)
289 func TestRecursivePanic3(t *testing.T) {
290 output := runTestProg(t, "testprog", "RecursivePanic3")
291 want := `panic: first panic
294 if !strings.HasPrefix(output, want) {
295 t.Fatalf("output does not start with %q:\n%s", want, output)
300 func TestRecursivePanic4(t *testing.T) {
301 output := runTestProg(t, "testprog", "RecursivePanic4")
302 want := `panic: first panic [recovered]
305 if !strings.HasPrefix(output, want) {
306 t.Fatalf("output does not start with %q:\n%s", want, output)
311 func TestRecursivePanic5(t *testing.T) {
312 output := runTestProg(t, "testprog", "RecursivePanic5")
317 if !strings.HasPrefix(output, want) {
318 t.Fatalf("output does not start with %q:\n%s", want, output)
323 func TestGoexitCrash(t *testing.T) {
324 // External linking brings in cgo, causing deadlock detection not working.
325 testenv.MustInternalLink(t, false)
327 output := runTestProg(t, "testprog", "GoexitExit")
328 want := "no goroutines (main called runtime.Goexit) - deadlock!"
329 if !strings.Contains(output, want) {
330 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
334 func TestGoexitDefer(t *testing.T) {
335 c := make(chan struct{})
340 t.Errorf("non-nil recover during Goexit")
346 // Note: if the defer fails to run, we will get a deadlock here
350 func TestGoNil(t *testing.T) {
351 output := runTestProg(t, "testprog", "GoNil")
352 want := "go of nil func value"
353 if !strings.Contains(output, want) {
354 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
358 func TestMainGoroutineID(t *testing.T) {
359 output := runTestProg(t, "testprog", "MainGoroutineID")
360 want := "panic: test\n\ngoroutine 1 [running]:\n"
361 if !strings.HasPrefix(output, want) {
362 t.Fatalf("output does not start with %q:\n%s", want, output)
366 func TestNoHelperGoroutines(t *testing.T) {
367 output := runTestProg(t, "testprog", "NoHelperGoroutines")
368 matches := regexp.MustCompile(`goroutine [0-9]+ \[`).FindAllStringSubmatch(output, -1)
369 if len(matches) != 1 || matches[0][0] != "goroutine 1 [" {
370 t.Fatalf("want to see only goroutine 1, see:\n%s", output)
374 func TestBreakpoint(t *testing.T) {
375 output := runTestProg(t, "testprog", "Breakpoint")
376 // If runtime.Breakpoint() is inlined, then the stack trace prints
377 // "runtime.Breakpoint(...)" instead of "runtime.Breakpoint()".
378 want := "runtime.Breakpoint("
379 if !strings.Contains(output, want) {
380 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
384 func TestGoexitInPanic(t *testing.T) {
385 // External linking brings in cgo, causing deadlock detection not working.
386 testenv.MustInternalLink(t, false)
388 // see issue 8774: this code used to trigger an infinite recursion
389 output := runTestProg(t, "testprog", "GoexitInPanic")
390 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
391 if !strings.HasPrefix(output, want) {
392 t.Fatalf("output does not start with %q:\n%s", want, output)
396 // Issue 14965: Runtime panics should be of type runtime.Error
397 func TestRuntimePanicWithRuntimeError(t *testing.T) {
398 testCases := [...]func(){
400 var m map[uint64]bool
404 ch := make(chan struct{})
409 var ch = make(chan struct{})
414 var s = make([]int, 2)
419 _ = make(chan bool, n)
422 close((chan bool)(nil))
426 for i, fn := range testCases {
427 got := panicValue(fn)
428 if _, ok := got.(runtime.Error); !ok {
429 t.Errorf("test #%d: recovered value %v(type %T) does not implement runtime.Error", i, got, got)
434 func panicValue(fn func()) (recovered any) {
436 recovered = recover()
442 func TestPanicAfterGoexit(t *testing.T) {
443 // an uncaught panic should still work after goexit
444 output := runTestProg(t, "testprog", "PanicAfterGoexit")
445 want := "panic: hello"
446 if !strings.HasPrefix(output, want) {
447 t.Fatalf("output does not start with %q:\n%s", want, output)
451 func TestRecoveredPanicAfterGoexit(t *testing.T) {
452 // External linking brings in cgo, causing deadlock detection not working.
453 testenv.MustInternalLink(t, false)
455 output := runTestProg(t, "testprog", "RecoveredPanicAfterGoexit")
456 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
457 if !strings.HasPrefix(output, want) {
458 t.Fatalf("output does not start with %q:\n%s", want, output)
462 func TestRecoverBeforePanicAfterGoexit(t *testing.T) {
463 // External linking brings in cgo, causing deadlock detection not working.
464 testenv.MustInternalLink(t, false)
467 output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit")
468 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
469 if !strings.HasPrefix(output, want) {
470 t.Fatalf("output does not start with %q:\n%s", want, output)
474 func TestRecoverBeforePanicAfterGoexit2(t *testing.T) {
475 // External linking brings in cgo, causing deadlock detection not working.
476 testenv.MustInternalLink(t, false)
479 output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit2")
480 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
481 if !strings.HasPrefix(output, want) {
482 t.Fatalf("output does not start with %q:\n%s", want, output)
486 func TestNetpollDeadlock(t *testing.T) {
488 output := runTestProg(t, "testprognet", "NetpollDeadlock")
490 if !strings.HasSuffix(output, want) {
491 t.Fatalf("output does not start with %q:\n%s", want, output)
495 func TestPanicTraceback(t *testing.T) {
497 output := runTestProg(t, "testprog", "PanicTraceback")
498 want := "panic: hello\n\tpanic: panic pt2\n\tpanic: panic pt1\n"
499 if !strings.HasPrefix(output, want) {
500 t.Fatalf("output does not start with %q:\n%s", want, output)
503 // Check functions in the traceback.
504 fns := []string{"main.pt1.func1", "panic", "main.pt2.func1", "panic", "main.pt2", "main.pt1"}
505 for _, fn := range fns {
506 re := regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(fn) + `\(.*\n`)
507 idx := re.FindStringIndex(output)
509 t.Fatalf("expected %q function in traceback:\n%s", fn, output)
511 output = output[idx[1]:]
515 func testPanicDeadlock(t *testing.T, name string, want string) {
517 output := runTestProg(t, "testprog", name)
518 if !strings.HasPrefix(output, want) {
519 t.Fatalf("output does not start with %q:\n%s", want, output)
523 func TestPanicDeadlockGosched(t *testing.T) {
524 testPanicDeadlock(t, "GoschedInPanic", "panic: errorThatGosched\n\n")
527 func TestPanicDeadlockSyscall(t *testing.T) {
528 testPanicDeadlock(t, "SyscallInPanic", "1\n2\npanic: 3\n\n")
531 func TestPanicLoop(t *testing.T) {
532 output := runTestProg(t, "testprog", "PanicLoop")
533 if want := "panic while printing panic value"; !strings.Contains(output, want) {
534 t.Errorf("output does not contain %q:\n%s", want, output)
538 func TestMemPprof(t *testing.T) {
539 testenv.MustHaveGoRun(t)
541 exe, err := buildTestProg(t, "testprog")
546 got, err := testenv.CleanCmdEnv(exec.Command(exe, "MemProf")).CombinedOutput()
548 t.Fatalf("testprog failed: %s, output:\n%s", err, got)
550 fn := strings.TrimSpace(string(got))
553 for try := 0; try < 2; try++ {
554 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-alloc_space", "-top"))
555 // Check that pprof works both with and without explicit executable on command line.
557 cmd.Args = append(cmd.Args, exe, fn)
559 cmd.Args = append(cmd.Args, fn)
562 for i, e := range cmd.Env {
563 if strings.HasPrefix(e, "PPROF_TMPDIR=") {
564 cmd.Env[i] = "PPROF_TMPDIR=" + os.TempDir()
570 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
573 top, err := cmd.CombinedOutput()
574 t.Logf("%s:\n%s", cmd.Args, top)
577 } else if !bytes.Contains(top, []byte("MemProf")) {
578 t.Error("missing MemProf in pprof output")
583 var concurrentMapTest = flag.Bool("run_concurrent_map_tests", false, "also run flaky concurrent map tests")
585 func TestConcurrentMapWrites(t *testing.T) {
586 if !*concurrentMapTest {
587 t.Skip("skipping without -run_concurrent_map_tests")
589 testenv.MustHaveGoRun(t)
590 output := runTestProg(t, "testprog", "concurrentMapWrites")
591 want := "fatal error: concurrent map writes"
592 if !strings.HasPrefix(output, want) {
593 t.Fatalf("output does not start with %q:\n%s", want, output)
596 func TestConcurrentMapReadWrite(t *testing.T) {
597 if !*concurrentMapTest {
598 t.Skip("skipping without -run_concurrent_map_tests")
600 testenv.MustHaveGoRun(t)
601 output := runTestProg(t, "testprog", "concurrentMapReadWrite")
602 want := "fatal error: concurrent map read and map write"
603 if !strings.HasPrefix(output, want) {
604 t.Fatalf("output does not start with %q:\n%s", want, output)
607 func TestConcurrentMapIterateWrite(t *testing.T) {
608 if !*concurrentMapTest {
609 t.Skip("skipping without -run_concurrent_map_tests")
611 testenv.MustHaveGoRun(t)
612 output := runTestProg(t, "testprog", "concurrentMapIterateWrite")
613 want := "fatal error: concurrent map iteration and map write"
614 if !strings.HasPrefix(output, want) {
615 t.Fatalf("output does not start with %q:\n%s", want, output)
623 func (p *point) negate() {
628 // Test for issue #10152.
629 func TestPanicInlined(t *testing.T) {
633 t.Fatalf("recover failed")
635 buf := make([]byte, 2048)
636 n := runtime.Stack(buf, false)
638 if !bytes.Contains(buf, []byte("(*point).negate(")) {
639 t.Fatalf("expecting stack trace to contain call to (*point).negate()")
647 // Test for issues #3934 and #20018.
648 // We want to delay exiting until a panic print is complete.
649 func TestPanicRace(t *testing.T) {
650 testenv.MustHaveGoRun(t)
652 exe, err := buildTestProg(t, "testprog")
657 // The test is intentionally racy, and in my testing does not
658 // produce the expected output about 0.05% of the time.
659 // So run the program in a loop and only fail the test if we
660 // get the wrong output ten times in a row.
663 for i := 0; i < tries; i++ {
664 got, err := testenv.CleanCmdEnv(exec.Command(exe, "PanicRace")).CombinedOutput()
666 t.Logf("try %d: program exited successfully, should have failed", i+1)
671 t.Logf("try %d:\n", i+1)
680 for _, want := range wants {
681 if !bytes.Contains(got, []byte(want)) {
682 t.Logf("did not find expected string %q", want)
687 // Test generated expected output.
690 t.Errorf("test ran %d times without producing expected output", tries)
693 func TestBadTraceback(t *testing.T) {
694 output := runTestProg(t, "testprog", "BadTraceback")
695 for _, want := range []string{
696 "unexpected return pc",
698 "00000bad", // Smashed LR in hex dump
699 "<main.badLR", // Symbolization in hex dump (badLR1 or badLR2)
701 if !strings.Contains(output, want) {
702 t.Errorf("output does not contain %q:\n%s", want, output)
707 func TestTimePprof(t *testing.T) {
708 // This test is unreliable on any system in which nanotime
710 switch runtime.GOOS {
711 case "aix", "darwin", "illumos", "openbsd", "solaris":
712 t.Skipf("skipping on %s because nanotime calls libc", runtime.GOOS)
715 // Pass GOTRACEBACK for issue #41120 to try to get more
716 // information on timeout.
717 fn := runTestProg(t, "testprog", "TimeProf", "GOTRACEBACK=crash")
718 fn = strings.TrimSpace(fn)
721 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-top", "-nodecount=1", fn))
722 cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
723 top, err := cmd.CombinedOutput()
727 } else if bytes.Contains(top, []byte("ExternalCode")) {
728 t.Error("profiler refers to ExternalCode")
732 // Test that runtime.abort does so.
733 func TestAbort(t *testing.T) {
734 // Pass GOTRACEBACK to ensure we get runtime frames.
735 output := runTestProg(t, "testprog", "Abort", "GOTRACEBACK=system")
736 if want := "runtime.abort"; !strings.Contains(output, want) {
737 t.Errorf("output does not contain %q:\n%s", want, output)
739 if strings.Contains(output, "BAD") {
740 t.Errorf("output contains BAD:\n%s", output)
742 // Check that it's a signal traceback.
744 // For systems that use a breakpoint, check specifically for that.
745 switch runtime.GOARCH {
747 switch runtime.GOOS {
749 want = "sys: breakpoint"
751 want = "Exception 0x80000003"
756 if !strings.Contains(output, want) {
757 t.Errorf("output does not contain %q:\n%s", want, output)
761 // For TestRuntimePanic: test a panic in the runtime package without
762 // involving the testing harness.
764 if os.Getenv("GO_TEST_RUNTIME_PANIC") == "1" {
766 if r := recover(); r != nil {
767 // We expect to crash, so exit 0
768 // to indicate failure.
772 runtime.PanicForTesting(nil, 1)
773 // We expect to crash, so exit 0 to indicate failure.
778 func TestRuntimePanic(t *testing.T) {
779 testenv.MustHaveExec(t)
780 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=^TestRuntimePanic$"))
781 cmd.Env = append(cmd.Env, "GO_TEST_RUNTIME_PANIC=1")
782 out, err := cmd.CombinedOutput()
785 t.Error("child process did not fail")
786 } else if want := "runtime.unexportedPanicForTesting"; !bytes.Contains(out, []byte(want)) {
787 t.Errorf("output did not contain expected string %q", want)
791 // Test that g0 stack overflows are handled gracefully.
792 func TestG0StackOverflow(t *testing.T) {
793 testenv.MustHaveExec(t)
795 if runtime.GOOS == "ios" {
796 testenv.SkipFlaky(t, 62671)
799 if os.Getenv("TEST_G0_STACK_OVERFLOW") != "1" {
800 cmd := testenv.CleanCmdEnv(testenv.Command(t, os.Args[0], "-test.run=^TestG0StackOverflow$", "-test.v"))
801 cmd.Env = append(cmd.Env, "TEST_G0_STACK_OVERFLOW=1")
802 out, err := cmd.CombinedOutput()
803 // Don't check err since it's expected to crash.
804 if n := strings.Count(string(out), "morestack on g0\n"); n != 1 {
805 t.Fatalf("%s\n(exit status %v)", out, err)
807 if runtime.GOARCH == "amd64" || runtime.GOARCH == "arm64" {
808 // check for a stack trace
809 want := "runtime.stackOverflow"
810 if n := strings.Count(string(out), want); n < 5 {
811 t.Errorf("output does not contain %q at least 5 times:\n%s", want, out)
813 return // it's not a signal-style traceback
815 // Check that it's a signal-style traceback.
816 if runtime.GOOS != "windows" {
817 if want := "PC="; !strings.Contains(string(out), want) {
818 t.Errorf("output does not contain %q:\n%s", want, out)
824 runtime.G0StackOverflow()
827 // Test that panic message is not clobbered.
829 func TestDoublePanic(t *testing.T) {
830 output := runTestProg(t, "testprog", "DoublePanic", "GODEBUG=clobberfree=1")
831 wants := []string{"panic: XXX", "panic: YYY"}
832 for _, want := range wants {
833 if !strings.Contains(output, want) {
834 t.Errorf("output:\n%s\n\nwant output containing: %s", output, want)
839 // Test that panic while panicking discards error message
841 func TestPanicWhilePanicking(t *testing.T) {
847 "panic while printing panic value: important error message",
851 "panic while printing panic value: important stringer message",
855 "panic while printing panic value: type",
859 "panic while printing panic value: type",
860 "DoubleStringerPanic",
863 "panic while printing panic value: type",
867 "important string message",
875 for _, x := range tests {
876 output := runTestProg(t, "testprog", x.Func)
877 if !strings.Contains(output, x.Want) {
878 t.Errorf("output does not contain %q:\n%s", x.Want, output)
883 func TestPanicOnUnsafeSlice(t *testing.T) {
884 output := runTestProg(t, "testprog", "panicOnNilAndEleSizeIsZero")
885 want := "panic: runtime error: unsafe.Slice: ptr is nil and len is not zero"
886 if !strings.Contains(output, want) {
887 t.Errorf("output does not contain %q:\n%s", want, output)
891 func TestNetpollWaiters(t *testing.T) {
893 output := runTestProg(t, "testprognet", "NetpollWaiters")
896 t.Fatalf("output is not %q\n%s", want, output)