|
| 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 | +"io/ioutil" |
| 9 | +"os" |
| 10 | +"os/exec" |
| 11 | +"path/filepath" |
| 12 | +"testing" |
| 13 | +"text/template" |
| 14 | +) |
| 15 | + |
| 16 | +type crashTest struct { |
| 17 | +Cgo bool |
| 18 | +} |
| 19 | + |
| 20 | +// This test is a separate program, because it is testing |
| 21 | +// both main (m0) and non-main threads (m). |
| 22 | + |
| 23 | +func testCrashHandler(t *testing.T, ct *crashTest) { |
| 24 | +st := template.Must(template.New("crashSource").Parse(crashSource)) |
| 25 | + |
| 26 | +dir, err := ioutil.TempDir("", "go-build") |
| 27 | +if err != nil { |
| 28 | +t.Fatalf("failed to create temp directory: %v", err) |
| 29 | +} |
| 30 | +defer os.RemoveAll(dir) |
| 31 | + |
| 32 | +src := filepath.Join(dir, "main.go") |
| 33 | +f, err := os.Create(src) |
| 34 | +if err != nil { |
| 35 | +t.Fatalf("failed to create %v: %v", src, err) |
| 36 | +} |
| 37 | +err = st.Execute(f, ct) |
| 38 | +if err != nil { |
| 39 | +f.Close() |
| 40 | +t.Fatalf("failed to execute template: %v", err) |
| 41 | +} |
| 42 | +f.Close() |
| 43 | + |
| 44 | +got, err := exec.Command("go", "run", src).CombinedOutput() |
| 45 | +if err != nil { |
| 46 | +t.Fatalf("program exited with error: %v\n%v", err, string(got)) |
| 47 | +} |
| 48 | +want := "main: recovered done\nnew-thread: recovered done\nsecond-new-thread: recovered done\nmain-again: recovered done\n" |
| 49 | +if string(got) != string(want) { |
| 50 | +t.Fatalf("expected %q, but got %q", string(want), string(got)) |
| 51 | +} |
| 52 | +} |
| 53 | + |
| 54 | +func TestCrashHandler(t *testing.T) { |
| 55 | +testCrashHandler(t, &crashTest{Cgo: false}) |
| 56 | +} |
| 57 | + |
| 58 | +const crashSource = ` |
| 59 | +package main |
| 60 | +
|
| 61 | +import ( |
| 62 | +"fmt" |
| 63 | +"runtime" |
| 64 | +) |
| 65 | +
|
| 66 | +{{if .Cgo}} |
| 67 | +import "C" |
| 68 | +{{end}} |
| 69 | +
|
| 70 | +func test(name string) { |
| 71 | +defer func() { |
| 72 | +if x := recover(); x != nil { |
| 73 | +fmt.Printf(" recovered") |
| 74 | +} |
| 75 | +fmt.Printf(" done\n") |
| 76 | +}() |
| 77 | +fmt.Printf("%s:", name) |
| 78 | +var s *string |
| 79 | +_ = *s |
| 80 | +fmt.Print("SHOULD NOT BE HERE") |
| 81 | +} |
| 82 | +
|
| 83 | +func testInNewThread(name string) { |
| 84 | +c := make(chan bool) |
| 85 | +go func() { |
| 86 | +runtime.LockOSThread() |
| 87 | +test(name) |
| 88 | +c <- true |
| 89 | +}() |
| 90 | +<-c |
| 91 | +} |
| 92 | +
|
| 93 | +func main() { |
| 94 | +runtime.LockOSThread() |
| 95 | +test("main") |
| 96 | +testInNewThread("new-thread") |
| 97 | +testInNewThread("second-new-thread") |
| 98 | +test("main-again") |
| 99 | +} |
| 100 | +` |
0 commit comments