github.com/x04/go/src@v0.0.0-20200202162449-3d481ceb3525/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 linux netbsd openbsd solaris 6 7 package runtime_test 8 9 import ( 10 "github.com/x04/go/src/bytes" 11 "github.com/x04/go/src/internal/testenv" 12 "github.com/x04/go/src/io" 13 "github.com/x04/go/src/io/ioutil" 14 "github.com/x04/go/src/os" 15 "github.com/x04/go/src/os/exec" 16 "github.com/x04/go/src/path/filepath" 17 "github.com/x04/go/src/runtime" 18 "github.com/x04/go/src/sync" 19 "github.com/x04/go/src/syscall" 20 "github.com/x04/go/src/testing" 21 "github.com/x04/go/src/time" 22 "github.com/x04/go/src/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 ) 162 163 func main() { 164 const count = 4 165 runtime.GOMAXPROCS(count + 1) 166 167 chans := make([]chan bool, count) 168 for i := range chans { 169 chans[i] = make(chan bool) 170 go loop(i, chans[i]) 171 } 172 173 // Wait for all the goroutines to start executing. 174 for _, c := range chans { 175 <-c 176 } 177 178 // Tell our parent that all the goroutines are executing. 179 if _, err := os.NewFile(3, "pipe").WriteString("x"); err != nil { 180 fmt.Fprintf(os.Stderr, "write to pipe failed: %v\n", err) 181 os.Exit(2) 182 } 183 184 select {} 185 } 186 187 func loop(i int, c chan bool) { 188 close(c) 189 for { 190 for j := 0; j < 0x7fffffff; j++ { 191 } 192 } 193 } 194 ` 195 196 func TestPanicSystemstack(t *testing.T) { 197 // Test that GOTRACEBACK=crash prints both the system and user 198 // stack of other threads. 199 200 // The GOTRACEBACK=crash handler takes 0.1 seconds even if 201 // it's not writing a core file and potentially much longer if 202 // it is. Skip in short mode. 203 if testing.Short() { 204 t.Skip("Skipping in short mode (GOTRACEBACK=crash is slow)") 205 } 206 207 if runtime.Sigisblocked(int(syscall.SIGQUIT)) { 208 t.Skip("skipping; SIGQUIT is blocked, see golang.org/issue/19196") 209 } 210 211 t.Parallel() 212 cmd := exec.Command(os.Args[0], "testPanicSystemstackInternal") 213 cmd = testenv.CleanCmdEnv(cmd) 214 cmd.Env = append(cmd.Env, "GOTRACEBACK=crash") 215 pr, pw, err := os.Pipe() 216 if err != nil { 217 t.Fatal("creating pipe: ", err) 218 } 219 cmd.Stderr = pw 220 if err := cmd.Start(); err != nil { 221 t.Fatal("starting command: ", err) 222 } 223 defer cmd.Process.Wait() 224 defer cmd.Process.Kill() 225 if err := pw.Close(); err != nil { 226 t.Log("closing write pipe: ", err) 227 } 228 defer pr.Close() 229 230 // Wait for "x\nx\n" to indicate readiness. 231 buf := make([]byte, 4) 232 _, err = io.ReadFull(pr, buf) 233 if err != nil || string(buf) != "x\nx\n" { 234 t.Fatal("subprocess failed; output:\n", string(buf)) 235 } 236 237 // Send SIGQUIT. 238 if err := cmd.Process.Signal(syscall.SIGQUIT); err != nil { 239 t.Fatal("signaling subprocess: ", err) 240 } 241 242 // Get traceback. 243 tb, err := ioutil.ReadAll(pr) 244 if err != nil { 245 t.Fatal("reading traceback from pipe: ", err) 246 } 247 248 // Traceback should have two testPanicSystemstackInternal's 249 // and two blockOnSystemStackInternal's. 250 if bytes.Count(tb, []byte("testPanicSystemstackInternal")) != 2 { 251 t.Fatal("traceback missing user stack:\n", string(tb)) 252 } else if bytes.Count(tb, []byte("blockOnSystemStackInternal")) != 2 { 253 t.Fatal("traceback missing system stack:\n", string(tb)) 254 } 255 } 256 257 func init() { 258 if len(os.Args) >= 2 && os.Args[1] == "testPanicSystemstackInternal" { 259 // Get two threads running on the system stack with 260 // something recognizable in the stack trace. 261 runtime.GOMAXPROCS(2) 262 go testPanicSystemstackInternal() 263 testPanicSystemstackInternal() 264 } 265 } 266 267 func testPanicSystemstackInternal() { 268 runtime.BlockOnSystemStack() 269 os.Exit(1) // Should be unreachable. 270 } 271 272 func TestSignalExitStatus(t *testing.T) { 273 testenv.MustHaveGoBuild(t) 274 exe, err := buildTestProg(t, "testprog") 275 if err != nil { 276 t.Fatal(err) 277 } 278 err = testenv.CleanCmdEnv(exec.Command(exe, "SignalExitStatus")).Run() 279 if err == nil { 280 t.Error("test program succeeded unexpectedly") 281 } else if ee, ok := err.(*exec.ExitError); !ok { 282 t.Errorf("error (%v) has type %T; expected exec.ExitError", err, err) 283 } else if ws, ok := ee.Sys().(syscall.WaitStatus); !ok { 284 t.Errorf("error.Sys (%v) has type %T; expected syscall.WaitStatus", ee.Sys(), ee.Sys()) 285 } else if !ws.Signaled() || ws.Signal() != syscall.SIGTERM { 286 t.Errorf("got %v; expected SIGTERM", ee) 287 } 288 } 289 290 func TestSignalIgnoreSIGTRAP(t *testing.T) { 291 output := runTestProg(t, "testprognet", "SignalIgnoreSIGTRAP") 292 want := "OK\n" 293 if output != want { 294 t.Fatalf("want %s, got %s\n", want, output) 295 } 296 } 297 298 func TestSignalDuringExec(t *testing.T) { 299 switch runtime.GOOS { 300 case "darwin", "dragonfly", "freebsd", "linux", "netbsd", "openbsd": 301 default: 302 t.Skipf("skipping test on %s", runtime.GOOS) 303 } 304 output := runTestProg(t, "testprognet", "SignalDuringExec") 305 want := "OK\n" 306 if output != want { 307 t.Fatalf("want %s, got %s\n", want, output) 308 } 309 } 310 311 func TestSignalM(t *testing.T) { 312 r, w, errno := runtime.Pipe() 313 if errno != 0 { 314 t.Fatal(syscall.Errno(errno)) 315 } 316 defer func() { 317 runtime.Close(r) 318 runtime.Close(w) 319 }() 320 runtime.Closeonexec(r) 321 runtime.Closeonexec(w) 322 323 var want, got int64 324 var wg sync.WaitGroup 325 ready := make(chan *runtime.M) 326 wg.Add(1) 327 go func() { 328 runtime.LockOSThread() 329 want, got = runtime.WaitForSigusr1(r, w, func(mp *runtime.M) { 330 ready <- mp 331 }) 332 runtime.UnlockOSThread() 333 wg.Done() 334 }() 335 waitingM := <-ready 336 runtime.SendSigusr1(waitingM) 337 338 timer := time.AfterFunc(time.Second, func() { 339 // Write 1 to tell WaitForSigusr1 that we timed out. 340 bw := byte(1) 341 if n := runtime.Write(uintptr(w), unsafe.Pointer(&bw), 1); n != 1 { 342 t.Errorf("pipe write failed: %d", n) 343 } 344 }) 345 defer timer.Stop() 346 347 wg.Wait() 348 if got == -1 { 349 t.Fatal("signalM signal not received") 350 } else if want != got { 351 t.Fatalf("signal sent to M %d, but received on M %d", want, got) 352 } 353 }