github.com/guyezi/gofrontend@v0.0.0-20200228202240-7a62a49e62c0/libgo/go/runtime/crash_unix_test.go (about) 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 // +build aix darwin dragonfly freebsd hurd linux netbsd openbsd solaris 6 7 package runtime_test 8 9 import ( 10 "bytes" 11 "internal/testenv" 12 "io" 13 "io/ioutil" 14 "os" 15 "os/exec" 16 "path/filepath" 17 "runtime" 18 "sync" 19 "syscall" 20 "testing" 21 "time" 22 "unsafe" 23 ) 24 25 // sigquit is the signal to send to kill a hanging testdata program. 26 // Send SIGQUIT to get a stack trace. 27 var sigquit = syscall.SIGQUIT 28 29 func init() { 30 if runtime.Sigisblocked(int(syscall.SIGQUIT)) { 31 // We can't use SIGQUIT to kill subprocesses because 32 // it's blocked. Use SIGKILL instead. See issue 33 // #19196 for an example of when this happens. 34 sigquit = syscall.SIGKILL 35 } 36 } 37 38 func TestBadOpen(t *testing.T) { 39 // make sure we get the correct error code if open fails. Same for 40 // read/write/close on the resulting -1 fd. See issue 10052. 41 nonfile := []byte("/notreallyafile") 42 fd := runtime.Open(&nonfile[0], 0, 0) 43 if fd != -1 { 44 t.Errorf("open(%q)=%d, want -1", nonfile, fd) 45 } 46 var buf [32]byte 47 r := runtime.Read(-1, unsafe.Pointer(&buf[0]), int32(len(buf))) 48 if got, want := r, -int32(syscall.EBADF); got != want { 49 t.Errorf("read()=%d, want %d", got, want) 50 } 51 w := runtime.Write(^uintptr(0), unsafe.Pointer(&buf[0]), int32(len(buf))) 52 if got, want := w, -int32(syscall.EBADF); got != want { 53 t.Errorf("write()=%d, want %d", got, want) 54 } 55 c := runtime.Close(-1) 56 if c != -1 { 57 t.Errorf("close()=%d, want -1", c) 58 } 59 } 60 61 func TestCrashDumpsAllThreads(t *testing.T) { 62 if *flagQuick { 63 t.Skip("-quick") 64 } 65 66 switch runtime.GOOS { 67 case "darwin", "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "illumos", "solaris": 68 default: 69 t.Skipf("skipping; not supported on %v", runtime.GOOS) 70 } 71 72 if runtime.Sigisblocked(int(syscall.SIGQUIT)) { 73 t.Skip("skipping; SIGQUIT is blocked, see golang.org/issue/19196") 74 } 75 76 // We don't use executeTest because we need to kill the 77 // program while it is running. 78 79 testenv.MustHaveGoBuild(t) 80 81 t.Parallel() 82 83 dir, err := ioutil.TempDir("", "go-build") 84 if err != nil { 85 t.Fatalf("failed to create temp directory: %v", err) 86 } 87 defer os.RemoveAll(dir) 88 89 if err := ioutil.WriteFile(filepath.Join(dir, "main.go"), []byte(crashDumpsAllThreadsSource), 0666); err != nil { 90 t.Fatalf("failed to create Go file: %v", err) 91 } 92 93 cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", "a.exe", "main.go") 94 cmd.Dir = dir 95 out, err := testenv.CleanCmdEnv(cmd).CombinedOutput() 96 if err != nil { 97 t.Fatalf("building source: %v\n%s", err, out) 98 } 99 100 cmd = exec.Command(filepath.Join(dir, "a.exe")) 101 cmd = testenv.CleanCmdEnv(cmd) 102 cmd.Env = append(cmd.Env, 103 "GOTRACEBACK=crash", 104 // Set GOGC=off. Because of golang.org/issue/10958, the tight 105 // loops in the test program are not preemptible. If GC kicks 106 // in, it may lock up and prevent main from saying it's ready. 107 "GOGC=off", 108 // Set GODEBUG=asyncpreemptoff=1. If a thread is preempted 109 // when it receives SIGQUIT, it won't show the expected 110 // stack trace. See issue 35356. 111 "GODEBUG=asyncpreemptoff=1", 112 ) 113 114 var outbuf bytes.Buffer 115 cmd.Stdout = &outbuf 116 cmd.Stderr = &outbuf 117 118 rp, wp, err := os.Pipe() 119 if err != nil { 120 t.Fatal(err) 121 } 122 cmd.ExtraFiles = []*os.File{wp} 123 124 if err := cmd.Start(); err != nil { 125 t.Fatalf("starting program: %v", err) 126 } 127 128 if err := wp.Close(); err != nil { 129 t.Logf("closing write pipe: %v", err) 130 } 131 if _, err := rp.Read(make([]byte, 1)); err != nil { 132 t.Fatalf("reading from pipe: %v", err) 133 } 134 135 if err := cmd.Process.Signal(syscall.SIGQUIT); err != nil { 136 t.Fatalf("signal: %v", err) 137 } 138 139 // No point in checking the error return from Wait--we expect 140 // it to fail. 141 cmd.Wait() 142 143 // We want to see a stack trace for each thread. 144 // Before https://golang.org/cl/2811 running threads would say 145 // "goroutine running on other thread; stack unavailable". 146 out = outbuf.Bytes() 147 n := bytes.Count(out, []byte("main.loop")) 148 if n != 4 { 149 t.Errorf("found %d instances of main.loop; expected 4", n) 150 t.Logf("%s", out) 151 } 152 } 153 154 const crashDumpsAllThreadsSource = ` 155 package main 156 157 import ( 158 "fmt" 159 "os" 160 "runtime" 161 "time" 162 ) 163 164 func main() { 165 const count = 4 166 runtime.GOMAXPROCS(count + 1) 167 168 chans := make([]chan bool, count) 169 for i := range chans { 170 chans[i] = make(chan bool) 171 go loop(i, chans[i]) 172 } 173 174 // Wait for all the goroutines to start executing. 175 for _, c := range chans { 176 <-c 177 } 178 179 time.Sleep(time.Millisecond) 180 181 // Tell our parent that all the goroutines are executing. 182 if _, err := os.NewFile(3, "pipe").WriteString("x"); err != nil { 183 fmt.Fprintf(os.Stderr, "write to pipe failed: %v\n", err) 184 os.Exit(2) 185 } 186 187 select {} 188 } 189 190 func loop(i int, c chan bool) { 191 close(c) 192 for { 193 for j := 0; j < 0x7fffffff; j++ { 194 } 195 } 196 } 197 ` 198 199 func TestPanicSystemstack(t *testing.T) { 200 // Test that GOTRACEBACK=crash prints both the system and user 201 // stack of other threads. 202 203 // The GOTRACEBACK=crash handler takes 0.1 seconds even if 204 // it's not writing a core file and potentially much longer if 205 // it is. Skip in short mode. 206 if testing.Short() { 207 t.Skip("Skipping in short mode (GOTRACEBACK=crash is slow)") 208 } 209 210 if runtime.Sigisblocked(int(syscall.SIGQUIT)) { 211 t.Skip("skipping; SIGQUIT is blocked, see golang.org/issue/19196") 212 } 213 214 t.Parallel() 215 cmd := exec.Command(os.Args[0], "testPanicSystemstackInternal") 216 cmd = testenv.CleanCmdEnv(cmd) 217 cmd.Env = append(cmd.Env, "GOTRACEBACK=crash") 218 pr, pw, err := os.Pipe() 219 if err != nil { 220 t.Fatal("creating pipe: ", err) 221 } 222 cmd.Stderr = pw 223 if err := cmd.Start(); err != nil { 224 t.Fatal("starting command: ", err) 225 } 226 defer cmd.Process.Wait() 227 defer cmd.Process.Kill() 228 if err := pw.Close(); err != nil { 229 t.Log("closing write pipe: ", err) 230 } 231 defer pr.Close() 232 233 // Wait for "x\nx\n" to indicate readiness. 234 buf := make([]byte, 4) 235 _, err = io.ReadFull(pr, buf) 236 if err != nil || string(buf) != "x\nx\n" { 237 t.Fatal("subprocess failed; output:\n", string(buf)) 238 } 239 240 // Send SIGQUIT. 241 if err := cmd.Process.Signal(syscall.SIGQUIT); err != nil { 242 t.Fatal("signaling subprocess: ", err) 243 } 244 245 // Get traceback. 246 tb, err := ioutil.ReadAll(pr) 247 if err != nil { 248 t.Fatal("reading traceback from pipe: ", err) 249 } 250 251 // Traceback should have two testPanicSystemstackInternal's 252 // and two blockOnSystemStackInternal's. 253 if bytes.Count(tb, []byte("testPanicSystemstackInternal")) != 2 { 254 t.Fatal("traceback missing user stack:\n", string(tb)) 255 } else if bytes.Count(tb, []byte("blockOnSystemStackInternal")) != 2 { 256 t.Fatal("traceback missing system stack:\n", string(tb)) 257 } 258 } 259 260 func init() { 261 if len(os.Args) >= 2 && os.Args[1] == "testPanicSystemstackInternal" { 262 // Get two threads running on the system stack with 263 // something recognizable in the stack trace. 264 runtime.GOMAXPROCS(2) 265 go testPanicSystemstackInternal() 266 testPanicSystemstackInternal() 267 } 268 } 269 270 func testPanicSystemstackInternal() { 271 runtime.BlockOnSystemStack() 272 os.Exit(1) // Should be unreachable. 273 } 274 275 func TestSignalExitStatus(t *testing.T) { 276 testenv.MustHaveGoBuild(t) 277 exe, err := buildTestProg(t, "testprog") 278 if err != nil { 279 t.Fatal(err) 280 } 281 err = testenv.CleanCmdEnv(exec.Command(exe, "SignalExitStatus")).Run() 282 if err == nil { 283 t.Error("test program succeeded unexpectedly") 284 } else if ee, ok := err.(*exec.ExitError); !ok { 285 t.Errorf("error (%v) has type %T; expected exec.ExitError", err, err) 286 } else if ws, ok := ee.Sys().(syscall.WaitStatus); !ok { 287 t.Errorf("error.Sys (%v) has type %T; expected syscall.WaitStatus", ee.Sys(), ee.Sys()) 288 } else if !ws.Signaled() || ws.Signal() != syscall.SIGTERM { 289 t.Errorf("got %v; expected SIGTERM", ee) 290 } 291 } 292 293 func TestSignalIgnoreSIGTRAP(t *testing.T) { 294 output := runTestProg(t, "testprognet", "SignalIgnoreSIGTRAP") 295 want := "OK\n" 296 if output != want { 297 t.Fatalf("want %s, got %s\n", want, output) 298 } 299 } 300 301 func TestSignalDuringExec(t *testing.T) { 302 switch runtime.GOOS { 303 case "darwin", "dragonfly", "freebsd", "linux", "netbsd", "openbsd": 304 default: 305 t.Skipf("skipping test on %s", runtime.GOOS) 306 } 307 output := runTestProg(t, "testprognet", "SignalDuringExec") 308 want := "OK\n" 309 if output != want { 310 t.Fatalf("want %s, got %s\n", want, output) 311 } 312 } 313 314 func TestSignalM(t *testing.T) { 315 if runtime.Compiler == "gccgo" { 316 t.Skip("no signalM for gccgo") 317 } 318 319 r, w, errno := runtime.Pipe() 320 if errno != 0 { 321 t.Fatal(syscall.Errno(errno)) 322 } 323 defer func() { 324 runtime.Close(r) 325 runtime.Close(w) 326 }() 327 runtime.Closeonexec(r) 328 runtime.Closeonexec(w) 329 330 var want, got int64 331 var wg sync.WaitGroup 332 ready := make(chan *runtime.M) 333 wg.Add(1) 334 go func() { 335 runtime.LockOSThread() 336 want, got = runtime.WaitForSigusr1(r, w, func(mp *runtime.M) { 337 ready <- mp 338 }) 339 runtime.UnlockOSThread() 340 wg.Done() 341 }() 342 waitingM := <-ready 343 runtime.SendSigusr1(waitingM) 344 345 timer := time.AfterFunc(time.Second, func() { 346 // Write 1 to tell WaitForSigusr1 that we timed out. 347 bw := byte(1) 348 if n := runtime.Write(uintptr(w), unsafe.Pointer(&bw), 1); n != 1 { 349 t.Errorf("pipe write failed: %d", n) 350 } 351 }) 352 defer timer.Stop() 353 354 wg.Wait() 355 if got == -1 { 356 t.Fatal("signalM signal not received") 357 } else if want != got { 358 t.Fatalf("signal sent to M %d, but received on M %d", want, got) 359 } 360 }