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.
22 func testEnv(cmd *exec.Cmd) *exec.Cmd {
24 panic("environment already set")
26 for _, env := range os.Environ() {
27 // Exclude GODEBUG from the environment to prevent its output
28 // from breaking tests that are trying to parse other command output.
29 if strings.HasPrefix(env, "GODEBUG=") {
32 // Exclude GOTRACEBACK for the same reason.
33 if strings.HasPrefix(env, "GOTRACEBACK=") {
36 cmd.Env = append(cmd.Env, env)
41 func executeTest(t *testing.T, templ string, data interface{}, extra ...string) string {
42 testenv.MustHaveGoBuild(t)
46 st := template.Must(template.New("crashSource").Parse(templ))
48 dir, err := ioutil.TempDir("", "go-build")
50 t.Fatalf("failed to create temp directory: %v", err)
52 defer os.RemoveAll(dir)
54 src := filepath.Join(dir, "main.go")
55 f, err := os.Create(src)
57 t.Fatalf("failed to create file: %v", err)
59 err = st.Execute(f, data)
62 t.Fatalf("failed to execute template: %v", err)
64 if err := f.Close(); err != nil {
65 t.Fatalf("failed to close file: %v", err)
68 for i := 0; i < len(extra); i += 2 {
70 contents := extra[i+1]
71 if d, _ := filepath.Split(fname); d != "" {
72 if err := os.Mkdir(filepath.Join(dir, d), 0755); err != nil {
76 if err := ioutil.WriteFile(filepath.Join(dir, fname), []byte(contents), 0666); err != nil {
81 cmd := exec.Command("go", "build", "-o", "a.exe")
83 out, err := testEnv(cmd).CombinedOutput()
85 t.Fatalf("building source: %v\n%s", err, out)
88 got, _ := testEnv(exec.Command(filepath.Join(dir, "a.exe"))).CombinedOutput()
93 staleRuntimeOnce sync.Once // guards init of staleRuntimeErr
97 func checkStaleRuntime(t *testing.T) {
98 staleRuntimeOnce.Do(func() {
99 // 'go run' uses the installed copy of runtime.a, which may be out of date.
100 out, err := testEnv(exec.Command("go", "list", "-f", "{{.Stale}}", "runtime")).CombinedOutput()
102 staleRuntimeErr = fmt.Errorf("failed to execute 'go list': %v\n%v", err, string(out))
105 if string(out) != "false\n" {
106 staleRuntimeErr = fmt.Errorf("Stale runtime.a. Run 'go install runtime'.")
109 if staleRuntimeErr != nil {
110 t.Fatal(staleRuntimeErr)
114 func testCrashHandler(t *testing.T, cgo bool) {
115 type crashTest struct {
118 output := executeTest(t, crashSource, &crashTest{Cgo: cgo})
119 want := "main: recovered done\nnew-thread: recovered done\nsecond-new-thread: recovered done\nmain-again: recovered done\n"
121 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
125 func TestCrashHandler(t *testing.T) {
126 testCrashHandler(t, false)
129 func testDeadlock(t *testing.T, source string) {
130 output := executeTest(t, source, nil)
131 want := "fatal error: all goroutines are asleep - deadlock!\n"
132 if !strings.HasPrefix(output, want) {
133 t.Fatalf("output does not start with %q:\n%s", want, output)
137 func TestSimpleDeadlock(t *testing.T) {
138 testDeadlock(t, simpleDeadlockSource)
141 func TestInitDeadlock(t *testing.T) {
142 testDeadlock(t, initDeadlockSource)
145 func TestLockedDeadlock(t *testing.T) {
146 testDeadlock(t, lockedDeadlockSource)
149 func TestLockedDeadlock2(t *testing.T) {
150 testDeadlock(t, lockedDeadlockSource2)
153 func TestGoexitDeadlock(t *testing.T) {
154 output := executeTest(t, goexitDeadlockSource, nil)
155 want := "no goroutines (main called runtime.Goexit) - deadlock!"
156 if !strings.Contains(output, want) {
157 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
161 func TestStackOverflow(t *testing.T) {
162 output := executeTest(t, stackOverflowSource, nil)
163 want := "runtime: goroutine stack exceeds 4194304-byte limit\nfatal error: stack overflow"
164 if !strings.HasPrefix(output, want) {
165 t.Fatalf("output does not start with %q:\n%s", want, output)
169 func TestThreadExhaustion(t *testing.T) {
170 output := executeTest(t, threadExhaustionSource, nil)
171 want := "runtime: program exceeds 10-thread limit\nfatal error: thread exhaustion"
172 if !strings.HasPrefix(output, want) {
173 t.Fatalf("output does not start with %q:\n%s", want, output)
177 func TestRecursivePanic(t *testing.T) {
178 output := executeTest(t, recursivePanicSource, nil)
183 if !strings.HasPrefix(output, want) {
184 t.Fatalf("output does not start with %q:\n%s", want, output)
189 func TestGoexitCrash(t *testing.T) {
190 output := executeTest(t, goexitExitSource, nil)
191 want := "no goroutines (main called runtime.Goexit) - deadlock!"
192 if !strings.Contains(output, want) {
193 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
197 func TestGoexitDefer(t *testing.T) {
198 c := make(chan struct{})
203 t.Errorf("non-nil recover during Goexit")
209 // Note: if the defer fails to run, we will get a deadlock here
213 func TestGoNil(t *testing.T) {
214 output := executeTest(t, goNilSource, nil)
215 want := "go of nil func value"
216 if !strings.Contains(output, want) {
217 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
221 func TestMainGoroutineId(t *testing.T) {
222 output := executeTest(t, mainGoroutineIdSource, nil)
223 want := "panic: test\n\ngoroutine 1 [running]:\n"
224 if !strings.HasPrefix(output, want) {
225 t.Fatalf("output does not start with %q:\n%s", want, output)
229 func TestNoHelperGoroutines(t *testing.T) {
230 output := executeTest(t, noHelperGoroutinesSource, nil)
231 matches := regexp.MustCompile(`goroutine [0-9]+ \[`).FindAllStringSubmatch(output, -1)
232 if len(matches) != 1 || matches[0][0] != "goroutine 1 [" {
233 t.Fatalf("want to see only goroutine 1, see:\n%s", output)
237 func TestBreakpoint(t *testing.T) {
238 output := executeTest(t, breakpointSource, nil)
239 want := "runtime.Breakpoint()"
240 if !strings.Contains(output, want) {
241 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
245 const crashSource = `
257 func test(name string) {
259 if x := recover(); x != nil {
260 fmt.Printf(" recovered")
262 fmt.Printf(" done\n")
264 fmt.Printf("%s:", name)
267 fmt.Print("SHOULD NOT BE HERE")
270 func testInNewThread(name string) {
273 runtime.LockOSThread()
281 runtime.LockOSThread()
283 testInNewThread("new-thread")
284 testInNewThread("second-new-thread")
289 const simpleDeadlockSource = `
296 const initDeadlockSource = `
305 const lockedDeadlockSource = `
309 runtime.LockOSThread()
314 const lockedDeadlockSource2 = `
322 runtime.LockOSThread()
325 time.Sleep(time.Millisecond)
330 const goexitDeadlockSource = `
337 for i := 0; i < 10; i++ {
348 const stackOverflowSource = `
351 import "runtime/debug"
354 debug.SetMaxStack(4<<20)
358 func f(x []byte) byte {
360 return x[0] + f(buf[:])
364 const threadExhaustionSource = `
373 debug.SetMaxThreads(10)
375 for i := 0; i < 100; i++ {
377 runtime.LockOSThread()
386 const recursivePanicSource = `
396 fmt.Println(recover())
401 if err := recover(); err != nil {
402 panic("wrap: " + err.(string))
412 const goexitExitSource = `
422 time.Sleep(time.Millisecond)
425 runtime.SetFinalizer(&i, func(p *int) {})
431 const goNilSource = `
444 const mainGoroutineIdSource = `
451 const noHelperGoroutinesSource = `
459 runtime.SetFinalizer(&i, func(p *int) {})
460 time.AfterFunc(time.Hour, func() {})
467 const breakpointSource = `
475 func TestGoexitInPanic(t *testing.T) {
476 // see issue 8774: this code used to trigger an infinite recursion
477 output := executeTest(t, goexitInPanicSource, nil)
478 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
479 if !strings.HasPrefix(output, want) {
480 t.Fatalf("output does not start with %q:\n%s", want, output)
484 const goexitInPanicSource = `
498 func TestPanicAfterGoexit(t *testing.T) {
499 // an uncaught panic should still work after goexit
500 output := executeTest(t, panicAfterGoexitSource, nil)
501 want := "panic: hello"
502 if !strings.HasPrefix(output, want) {
503 t.Fatalf("output does not start with %q:\n%s", want, output)
507 const panicAfterGoexitSource = `
518 func TestRecoveredPanicAfterGoexit(t *testing.T) {
519 output := executeTest(t, recoveredPanicAfterGoexitSource, nil)
520 want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
521 if !strings.HasPrefix(output, want) {
522 t.Fatalf("output does not start with %q:\n%s", want, output)
526 const recoveredPanicAfterGoexitSource = `
543 func TestRecoverBeforePanicAfterGoexit(t *testing.T) {
544 // 1. defer a function that recovers
545 // 2. defer a function that panics
547 // Goexit should run the #2 defer. Its panic
548 // should be caught by the #1 defer, and execution
549 // should resume in the caller. Like the Goexit
563 func TestNetpollDeadlock(t *testing.T) {
564 output := executeTest(t, netpollDeadlockSource, nil)
566 if !strings.HasSuffix(output, want) {
567 t.Fatalf("output does not start with %q:\n%s", want, output)
571 const netpollDeadlockSource = `
578 fmt.Println("dialing")
579 c, err := net.Dial("tcp", "localhost:14356")
583 fmt.Println("error: ", err)