]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/crash_test.go
[dev.boringcrypto] all: merge master into dev.boringcrypto
[gostls13.git] / src / runtime / crash_test.go
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.
4
5 package runtime_test
6
7 import (
8         "bytes"
9         "flag"
10         "fmt"
11         "internal/testenv"
12         "io/ioutil"
13         "os"
14         "os/exec"
15         "path/filepath"
16         "regexp"
17         "runtime"
18         "strconv"
19         "strings"
20         "sync"
21         "testing"
22         "time"
23 )
24
25 var toRemove []string
26
27 func TestMain(m *testing.M) {
28         status := m.Run()
29         for _, file := range toRemove {
30                 os.RemoveAll(file)
31         }
32         os.Exit(status)
33 }
34
35 var testprog struct {
36         sync.Mutex
37         dir    string
38         target map[string]buildexe
39 }
40
41 type buildexe struct {
42         exe string
43         err error
44 }
45
46 func runTestProg(t *testing.T, binary, name string, env ...string) string {
47         if *flagQuick {
48                 t.Skip("-quick")
49         }
50
51         testenv.MustHaveGoBuild(t)
52
53         exe, err := buildTestProg(t, binary)
54         if err != nil {
55                 t.Fatal(err)
56         }
57
58         return runBuiltTestProg(t, exe, name, env...)
59 }
60
61 func runBuiltTestProg(t *testing.T, exe, name string, env ...string) string {
62         if *flagQuick {
63                 t.Skip("-quick")
64         }
65
66         testenv.MustHaveGoBuild(t)
67
68         cmd := testenv.CleanCmdEnv(exec.Command(exe, name))
69         cmd.Env = append(cmd.Env, env...)
70         if testing.Short() {
71                 cmd.Env = append(cmd.Env, "RUNTIME_TEST_SHORT=1")
72         }
73         var b bytes.Buffer
74         cmd.Stdout = &b
75         cmd.Stderr = &b
76         if err := cmd.Start(); err != nil {
77                 t.Fatalf("starting %s %s: %v", exe, name, err)
78         }
79
80         // If the process doesn't complete within 1 minute,
81         // assume it is hanging and kill it to get a stack trace.
82         p := cmd.Process
83         done := make(chan bool)
84         go func() {
85                 scale := 1
86                 // This GOARCH/GOOS test is copied from cmd/dist/test.go.
87                 // TODO(iant): Have cmd/dist update the environment variable.
88                 if runtime.GOARCH == "arm" || runtime.GOOS == "windows" {
89                         scale = 2
90                 }
91                 if s := os.Getenv("GO_TEST_TIMEOUT_SCALE"); s != "" {
92                         if sc, err := strconv.Atoi(s); err == nil {
93                                 scale = sc
94                         }
95                 }
96
97                 select {
98                 case <-done:
99                 case <-time.After(time.Duration(scale) * time.Minute):
100                         p.Signal(sigquit)
101                 }
102         }()
103
104         if err := cmd.Wait(); err != nil {
105                 t.Logf("%s %s exit status: %v", exe, name, err)
106         }
107         close(done)
108
109         return b.String()
110 }
111
112 func buildTestProg(t *testing.T, binary string, flags ...string) (string, error) {
113         if *flagQuick {
114                 t.Skip("-quick")
115         }
116
117         testprog.Lock()
118         defer testprog.Unlock()
119         if testprog.dir == "" {
120                 dir, err := ioutil.TempDir("", "go-build")
121                 if err != nil {
122                         t.Fatalf("failed to create temp directory: %v", err)
123                 }
124                 testprog.dir = dir
125                 toRemove = append(toRemove, dir)
126         }
127
128         if testprog.target == nil {
129                 testprog.target = make(map[string]buildexe)
130         }
131         name := binary
132         if len(flags) > 0 {
133                 name += "_" + strings.Join(flags, "_")
134         }
135         target, ok := testprog.target[name]
136         if ok {
137                 return target.exe, target.err
138         }
139
140         exe := filepath.Join(testprog.dir, name+".exe")
141         cmd := exec.Command(testenv.GoToolPath(t), append([]string{"build", "-o", exe}, flags...)...)
142         cmd.Dir = "testdata/" + binary
143         out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
144         if err != nil {
145                 target.err = fmt.Errorf("building %s %v: %v\n%s", binary, flags, err, out)
146                 testprog.target[name] = target
147                 return "", target.err
148         }
149         target.exe = exe
150         testprog.target[name] = target
151         return exe, nil
152 }
153
154 func TestVDSO(t *testing.T) {
155         t.Parallel()
156         output := runTestProg(t, "testprog", "SignalInVDSO")
157         want := "success\n"
158         if output != want {
159                 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
160         }
161 }
162
163 func testCrashHandler(t *testing.T, cgo bool) {
164         type crashTest struct {
165                 Cgo bool
166         }
167         var output string
168         if cgo {
169                 output = runTestProg(t, "testprogcgo", "Crash")
170         } else {
171                 output = runTestProg(t, "testprog", "Crash")
172         }
173         want := "main: recovered done\nnew-thread: recovered done\nsecond-new-thread: recovered done\nmain-again: recovered done\n"
174         if output != want {
175                 t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
176         }
177 }
178
179 func TestCrashHandler(t *testing.T) {
180         testCrashHandler(t, false)
181 }
182
183 func testDeadlock(t *testing.T, name string) {
184         output := runTestProg(t, "testprog", name)
185         want := "fatal error: all goroutines are asleep - deadlock!\n"
186         if !strings.HasPrefix(output, want) {
187                 t.Fatalf("output does not start with %q:\n%s", want, output)
188         }
189 }
190
191 func TestSimpleDeadlock(t *testing.T) {
192         testDeadlock(t, "SimpleDeadlock")
193 }
194
195 func TestInitDeadlock(t *testing.T) {
196         testDeadlock(t, "InitDeadlock")
197 }
198
199 func TestLockedDeadlock(t *testing.T) {
200         testDeadlock(t, "LockedDeadlock")
201 }
202
203 func TestLockedDeadlock2(t *testing.T) {
204         testDeadlock(t, "LockedDeadlock2")
205 }
206
207 func TestGoexitDeadlock(t *testing.T) {
208         output := runTestProg(t, "testprog", "GoexitDeadlock")
209         want := "no goroutines (main called runtime.Goexit) - deadlock!"
210         if !strings.Contains(output, want) {
211                 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
212         }
213 }
214
215 func TestStackOverflow(t *testing.T) {
216         output := runTestProg(t, "testprog", "StackOverflow")
217         want := []string{
218                 "runtime: goroutine stack exceeds 1474560-byte limit\n",
219                 "fatal error: stack overflow",
220                 // information about the current SP and stack bounds
221                 "runtime: sp=",
222                 "stack=[",
223         }
224         if !strings.HasPrefix(output, want[0]) {
225                 t.Errorf("output does not start with %q", want[0])
226         }
227         for _, s := range want[1:] {
228                 if !strings.Contains(output, s) {
229                         t.Errorf("output does not contain %q", s)
230                 }
231         }
232         if t.Failed() {
233                 t.Logf("output:\n%s", output)
234         }
235 }
236
237 func TestThreadExhaustion(t *testing.T) {
238         output := runTestProg(t, "testprog", "ThreadExhaustion")
239         want := "runtime: program exceeds 10-thread limit\nfatal error: thread exhaustion"
240         if !strings.HasPrefix(output, want) {
241                 t.Fatalf("output does not start with %q:\n%s", want, output)
242         }
243 }
244
245 func TestRecursivePanic(t *testing.T) {
246         output := runTestProg(t, "testprog", "RecursivePanic")
247         want := `wrap: bad
248 panic: again
249
250 `
251         if !strings.HasPrefix(output, want) {
252                 t.Fatalf("output does not start with %q:\n%s", want, output)
253         }
254
255 }
256
257 func TestRecursivePanic2(t *testing.T) {
258         output := runTestProg(t, "testprog", "RecursivePanic2")
259         want := `first panic
260 second panic
261 panic: third panic
262
263 `
264         if !strings.HasPrefix(output, want) {
265                 t.Fatalf("output does not start with %q:\n%s", want, output)
266         }
267
268 }
269
270 func TestRecursivePanic3(t *testing.T) {
271         output := runTestProg(t, "testprog", "RecursivePanic3")
272         want := `panic: first panic
273
274 `
275         if !strings.HasPrefix(output, want) {
276                 t.Fatalf("output does not start with %q:\n%s", want, output)
277         }
278
279 }
280
281 func TestRecursivePanic4(t *testing.T) {
282         output := runTestProg(t, "testprog", "RecursivePanic4")
283         want := `panic: first panic [recovered]
284         panic: second panic
285 `
286         if !strings.HasPrefix(output, want) {
287                 t.Fatalf("output does not start with %q:\n%s", want, output)
288         }
289
290 }
291
292 func TestGoexitCrash(t *testing.T) {
293         output := runTestProg(t, "testprog", "GoexitExit")
294         want := "no goroutines (main called runtime.Goexit) - deadlock!"
295         if !strings.Contains(output, want) {
296                 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
297         }
298 }
299
300 func TestGoexitDefer(t *testing.T) {
301         c := make(chan struct{})
302         go func() {
303                 defer func() {
304                         r := recover()
305                         if r != nil {
306                                 t.Errorf("non-nil recover during Goexit")
307                         }
308                         c <- struct{}{}
309                 }()
310                 runtime.Goexit()
311         }()
312         // Note: if the defer fails to run, we will get a deadlock here
313         <-c
314 }
315
316 func TestGoNil(t *testing.T) {
317         output := runTestProg(t, "testprog", "GoNil")
318         want := "go of nil func value"
319         if !strings.Contains(output, want) {
320                 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
321         }
322 }
323
324 func TestMainGoroutineID(t *testing.T) {
325         output := runTestProg(t, "testprog", "MainGoroutineID")
326         want := "panic: test\n\ngoroutine 1 [running]:\n"
327         if !strings.HasPrefix(output, want) {
328                 t.Fatalf("output does not start with %q:\n%s", want, output)
329         }
330 }
331
332 func TestNoHelperGoroutines(t *testing.T) {
333         output := runTestProg(t, "testprog", "NoHelperGoroutines")
334         matches := regexp.MustCompile(`goroutine [0-9]+ \[`).FindAllStringSubmatch(output, -1)
335         if len(matches) != 1 || matches[0][0] != "goroutine 1 [" {
336                 t.Fatalf("want to see only goroutine 1, see:\n%s", output)
337         }
338 }
339
340 func TestBreakpoint(t *testing.T) {
341         output := runTestProg(t, "testprog", "Breakpoint")
342         // If runtime.Breakpoint() is inlined, then the stack trace prints
343         // "runtime.Breakpoint(...)" instead of "runtime.Breakpoint()".
344         want := "runtime.Breakpoint("
345         if !strings.Contains(output, want) {
346                 t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
347         }
348 }
349
350 func TestGoexitInPanic(t *testing.T) {
351         // see issue 8774: this code used to trigger an infinite recursion
352         output := runTestProg(t, "testprog", "GoexitInPanic")
353         want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
354         if !strings.HasPrefix(output, want) {
355                 t.Fatalf("output does not start with %q:\n%s", want, output)
356         }
357 }
358
359 // Issue 14965: Runtime panics should be of type runtime.Error
360 func TestRuntimePanicWithRuntimeError(t *testing.T) {
361         testCases := [...]func(){
362                 0: func() {
363                         var m map[uint64]bool
364                         m[1234] = true
365                 },
366                 1: func() {
367                         ch := make(chan struct{})
368                         close(ch)
369                         close(ch)
370                 },
371                 2: func() {
372                         var ch = make(chan struct{})
373                         close(ch)
374                         ch <- struct{}{}
375                 },
376                 3: func() {
377                         var s = make([]int, 2)
378                         _ = s[2]
379                 },
380                 4: func() {
381                         n := -1
382                         _ = make(chan bool, n)
383                 },
384                 5: func() {
385                         close((chan bool)(nil))
386                 },
387         }
388
389         for i, fn := range testCases {
390                 got := panicValue(fn)
391                 if _, ok := got.(runtime.Error); !ok {
392                         t.Errorf("test #%d: recovered value %v(type %T) does not implement runtime.Error", i, got, got)
393                 }
394         }
395 }
396
397 func panicValue(fn func()) (recovered interface{}) {
398         defer func() {
399                 recovered = recover()
400         }()
401         fn()
402         return
403 }
404
405 func TestPanicAfterGoexit(t *testing.T) {
406         // an uncaught panic should still work after goexit
407         output := runTestProg(t, "testprog", "PanicAfterGoexit")
408         want := "panic: hello"
409         if !strings.HasPrefix(output, want) {
410                 t.Fatalf("output does not start with %q:\n%s", want, output)
411         }
412 }
413
414 func TestRecoveredPanicAfterGoexit(t *testing.T) {
415         output := runTestProg(t, "testprog", "RecoveredPanicAfterGoexit")
416         want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
417         if !strings.HasPrefix(output, want) {
418                 t.Fatalf("output does not start with %q:\n%s", want, output)
419         }
420 }
421
422 func TestRecoverBeforePanicAfterGoexit(t *testing.T) {
423         t.Parallel()
424         output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit")
425         want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
426         if !strings.HasPrefix(output, want) {
427                 t.Fatalf("output does not start with %q:\n%s", want, output)
428         }
429 }
430
431 func TestRecoverBeforePanicAfterGoexit2(t *testing.T) {
432         t.Parallel()
433         output := runTestProg(t, "testprog", "RecoverBeforePanicAfterGoexit2")
434         want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
435         if !strings.HasPrefix(output, want) {
436                 t.Fatalf("output does not start with %q:\n%s", want, output)
437         }
438 }
439
440 func TestNetpollDeadlock(t *testing.T) {
441         if os.Getenv("GO_BUILDER_NAME") == "darwin-amd64-10_12" {
442                 // A suspected kernel bug in macOS 10.12 occasionally results in
443                 // an apparent deadlock when dialing localhost. The errors have not
444                 // been observed on newer versions of the OS, so we don't plan to work
445                 // around them. See https://golang.org/issue/22019.
446                 testenv.SkipFlaky(t, 22019)
447         }
448
449         t.Parallel()
450         output := runTestProg(t, "testprognet", "NetpollDeadlock")
451         want := "done\n"
452         if !strings.HasSuffix(output, want) {
453                 t.Fatalf("output does not start with %q:\n%s", want, output)
454         }
455 }
456
457 func TestPanicTraceback(t *testing.T) {
458         t.Parallel()
459         output := runTestProg(t, "testprog", "PanicTraceback")
460         want := "panic: hello\n\tpanic: panic pt2\n\tpanic: panic pt1\n"
461         if !strings.HasPrefix(output, want) {
462                 t.Fatalf("output does not start with %q:\n%s", want, output)
463         }
464
465         // Check functions in the traceback.
466         fns := []string{"main.pt1.func1", "panic", "main.pt2.func1", "panic", "main.pt2", "main.pt1"}
467         for _, fn := range fns {
468                 re := regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(fn) + `\(.*\n`)
469                 idx := re.FindStringIndex(output)
470                 if idx == nil {
471                         t.Fatalf("expected %q function in traceback:\n%s", fn, output)
472                 }
473                 output = output[idx[1]:]
474         }
475 }
476
477 func testPanicDeadlock(t *testing.T, name string, want string) {
478         // test issue 14432
479         output := runTestProg(t, "testprog", name)
480         if !strings.HasPrefix(output, want) {
481                 t.Fatalf("output does not start with %q:\n%s", want, output)
482         }
483 }
484
485 func TestPanicDeadlockGosched(t *testing.T) {
486         testPanicDeadlock(t, "GoschedInPanic", "panic: errorThatGosched\n\n")
487 }
488
489 func TestPanicDeadlockSyscall(t *testing.T) {
490         testPanicDeadlock(t, "SyscallInPanic", "1\n2\npanic: 3\n\n")
491 }
492
493 func TestPanicLoop(t *testing.T) {
494         output := runTestProg(t, "testprog", "PanicLoop")
495         if want := "panic while printing panic value"; !strings.Contains(output, want) {
496                 t.Errorf("output does not contain %q:\n%s", want, output)
497         }
498 }
499
500 func TestMemPprof(t *testing.T) {
501         testenv.MustHaveGoRun(t)
502
503         exe, err := buildTestProg(t, "testprog")
504         if err != nil {
505                 t.Fatal(err)
506         }
507
508         got, err := testenv.CleanCmdEnv(exec.Command(exe, "MemProf")).CombinedOutput()
509         if err != nil {
510                 t.Fatal(err)
511         }
512         fn := strings.TrimSpace(string(got))
513         defer os.Remove(fn)
514
515         for try := 0; try < 2; try++ {
516                 cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-alloc_space", "-top"))
517                 // Check that pprof works both with and without explicit executable on command line.
518                 if try == 0 {
519                         cmd.Args = append(cmd.Args, exe, fn)
520                 } else {
521                         cmd.Args = append(cmd.Args, fn)
522                 }
523                 found := false
524                 for i, e := range cmd.Env {
525                         if strings.HasPrefix(e, "PPROF_TMPDIR=") {
526                                 cmd.Env[i] = "PPROF_TMPDIR=" + os.TempDir()
527                                 found = true
528                                 break
529                         }
530                 }
531                 if !found {
532                         cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
533                 }
534
535                 top, err := cmd.CombinedOutput()
536                 t.Logf("%s:\n%s", cmd.Args, top)
537                 if err != nil {
538                         t.Error(err)
539                 } else if !bytes.Contains(top, []byte("MemProf")) {
540                         t.Error("missing MemProf in pprof output")
541                 }
542         }
543 }
544
545 var concurrentMapTest = flag.Bool("run_concurrent_map_tests", false, "also run flaky concurrent map tests")
546
547 func TestConcurrentMapWrites(t *testing.T) {
548         if !*concurrentMapTest {
549                 t.Skip("skipping without -run_concurrent_map_tests")
550         }
551         testenv.MustHaveGoRun(t)
552         output := runTestProg(t, "testprog", "concurrentMapWrites")
553         want := "fatal error: concurrent map writes"
554         if !strings.HasPrefix(output, want) {
555                 t.Fatalf("output does not start with %q:\n%s", want, output)
556         }
557 }
558 func TestConcurrentMapReadWrite(t *testing.T) {
559         if !*concurrentMapTest {
560                 t.Skip("skipping without -run_concurrent_map_tests")
561         }
562         testenv.MustHaveGoRun(t)
563         output := runTestProg(t, "testprog", "concurrentMapReadWrite")
564         want := "fatal error: concurrent map read and map write"
565         if !strings.HasPrefix(output, want) {
566                 t.Fatalf("output does not start with %q:\n%s", want, output)
567         }
568 }
569 func TestConcurrentMapIterateWrite(t *testing.T) {
570         if !*concurrentMapTest {
571                 t.Skip("skipping without -run_concurrent_map_tests")
572         }
573         testenv.MustHaveGoRun(t)
574         output := runTestProg(t, "testprog", "concurrentMapIterateWrite")
575         want := "fatal error: concurrent map iteration and map write"
576         if !strings.HasPrefix(output, want) {
577                 t.Fatalf("output does not start with %q:\n%s", want, output)
578         }
579 }
580
581 type point struct {
582         x, y *int
583 }
584
585 func (p *point) negate() {
586         *p.x = *p.x * -1
587         *p.y = *p.y * -1
588 }
589
590 // Test for issue #10152.
591 func TestPanicInlined(t *testing.T) {
592         defer func() {
593                 r := recover()
594                 if r == nil {
595                         t.Fatalf("recover failed")
596                 }
597                 buf := make([]byte, 2048)
598                 n := runtime.Stack(buf, false)
599                 buf = buf[:n]
600                 if !bytes.Contains(buf, []byte("(*point).negate(")) {
601                         t.Fatalf("expecting stack trace to contain call to (*point).negate()")
602                 }
603         }()
604
605         pt := new(point)
606         pt.negate()
607 }
608
609 // Test for issues #3934 and #20018.
610 // We want to delay exiting until a panic print is complete.
611 func TestPanicRace(t *testing.T) {
612         testenv.MustHaveGoRun(t)
613
614         exe, err := buildTestProg(t, "testprog")
615         if err != nil {
616                 t.Fatal(err)
617         }
618
619         // The test is intentionally racy, and in my testing does not
620         // produce the expected output about 0.05% of the time.
621         // So run the program in a loop and only fail the test if we
622         // get the wrong output ten times in a row.
623         const tries = 10
624 retry:
625         for i := 0; i < tries; i++ {
626                 got, err := testenv.CleanCmdEnv(exec.Command(exe, "PanicRace")).CombinedOutput()
627                 if err == nil {
628                         t.Logf("try %d: program exited successfully, should have failed", i+1)
629                         continue
630                 }
631
632                 if i > 0 {
633                         t.Logf("try %d:\n", i+1)
634                 }
635                 t.Logf("%s\n", got)
636
637                 wants := []string{
638                         "panic: crash",
639                         "PanicRace",
640                         "created by ",
641                 }
642                 for _, want := range wants {
643                         if !bytes.Contains(got, []byte(want)) {
644                                 t.Logf("did not find expected string %q", want)
645                                 continue retry
646                         }
647                 }
648
649                 // Test generated expected output.
650                 return
651         }
652         t.Errorf("test ran %d times without producing expected output", tries)
653 }
654
655 func TestBadTraceback(t *testing.T) {
656         output := runTestProg(t, "testprog", "BadTraceback")
657         for _, want := range []string{
658                 "runtime: unexpected return pc",
659                 "called from 0xbad",
660                 "00000bad",    // Smashed LR in hex dump
661                 "<main.badLR", // Symbolization in hex dump (badLR1 or badLR2)
662         } {
663                 if !strings.Contains(output, want) {
664                         t.Errorf("output does not contain %q:\n%s", want, output)
665                 }
666         }
667 }
668
669 func TestTimePprof(t *testing.T) {
670         fn := runTestProg(t, "testprog", "TimeProf")
671         fn = strings.TrimSpace(fn)
672         defer os.Remove(fn)
673
674         cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-top", "-nodecount=1", fn))
675         cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
676         top, err := cmd.CombinedOutput()
677         t.Logf("%s", top)
678         if err != nil {
679                 t.Error(err)
680         } else if bytes.Contains(top, []byte("ExternalCode")) {
681                 t.Error("profiler refers to ExternalCode")
682         }
683 }
684
685 // Test that runtime.abort does so.
686 func TestAbort(t *testing.T) {
687         // Pass GOTRACEBACK to ensure we get runtime frames.
688         output := runTestProg(t, "testprog", "Abort", "GOTRACEBACK=system")
689         if want := "runtime.abort"; !strings.Contains(output, want) {
690                 t.Errorf("output does not contain %q:\n%s", want, output)
691         }
692         if strings.Contains(output, "BAD") {
693                 t.Errorf("output contains BAD:\n%s", output)
694         }
695         // Check that it's a signal traceback.
696         want := "PC="
697         // For systems that use a breakpoint, check specifically for that.
698         switch runtime.GOARCH {
699         case "386", "amd64":
700                 switch runtime.GOOS {
701                 case "plan9":
702                         want = "sys: breakpoint"
703                 case "windows":
704                         want = "Exception 0x80000003"
705                 default:
706                         want = "SIGTRAP"
707                 }
708         }
709         if !strings.Contains(output, want) {
710                 t.Errorf("output does not contain %q:\n%s", want, output)
711         }
712 }
713
714 // For TestRuntimePanic: test a panic in the runtime package without
715 // involving the testing harness.
716 func init() {
717         if os.Getenv("GO_TEST_RUNTIME_PANIC") == "1" {
718                 defer func() {
719                         if r := recover(); r != nil {
720                                 // We expect to crash, so exit 0
721                                 // to indicate failure.
722                                 os.Exit(0)
723                         }
724                 }()
725                 runtime.PanicForTesting(nil, 1)
726                 // We expect to crash, so exit 0 to indicate failure.
727                 os.Exit(0)
728         }
729 }
730
731 func TestRuntimePanic(t *testing.T) {
732         testenv.MustHaveExec(t)
733         cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestRuntimePanic"))
734         cmd.Env = append(cmd.Env, "GO_TEST_RUNTIME_PANIC=1")
735         out, err := cmd.CombinedOutput()
736         t.Logf("%s", out)
737         if err == nil {
738                 t.Error("child process did not fail")
739         } else if want := "runtime.unexportedPanicForTesting"; !bytes.Contains(out, []byte(want)) {
740                 t.Errorf("output did not contain expected string %q", want)
741         }
742 }
743
744 // Test that g0 stack overflows are handled gracefully.
745 func TestG0StackOverflow(t *testing.T) {
746         testenv.MustHaveExec(t)
747
748         switch runtime.GOOS {
749         case "darwin", "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "android":
750                 t.Skipf("g0 stack is wrong on pthread platforms (see golang.org/issue/26061)")
751         }
752
753         if os.Getenv("TEST_G0_STACK_OVERFLOW") != "1" {
754                 cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestG0StackOverflow", "-test.v"))
755                 cmd.Env = append(cmd.Env, "TEST_G0_STACK_OVERFLOW=1")
756                 out, err := cmd.CombinedOutput()
757                 // Don't check err since it's expected to crash.
758                 if n := strings.Count(string(out), "morestack on g0\n"); n != 1 {
759                         t.Fatalf("%s\n(exit status %v)", out, err)
760                 }
761                 // Check that it's a signal-style traceback.
762                 if runtime.GOOS != "windows" {
763                         if want := "PC="; !strings.Contains(string(out), want) {
764                                 t.Errorf("output does not contain %q:\n%s", want, out)
765                         }
766                 }
767                 return
768         }
769
770         runtime.G0StackOverflow()
771 }
772
773 // Test that panic message is not clobbered.
774 // See issue 30150.
775 func TestDoublePanic(t *testing.T) {
776         output := runTestProg(t, "testprog", "DoublePanic", "GODEBUG=clobberfree=1")
777         wants := []string{"panic: XXX", "panic: YYY"}
778         for _, want := range wants {
779                 if !strings.Contains(output, want) {
780                         t.Errorf("output:\n%s\n\nwant output containing: %s", output, want)
781                 }
782         }
783 }