Debian Codegraph @

src/runtime/crash_unix_test.go

raw ◀ ▶
Source reconstructed at patch state 1 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
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 //go:build unix
6
7 package runtime_test
8
9 import (
10 "bytes"
11 "internal/testenv"
12 "io"
13 "os"
14 "os/exec"
15 "runtime"
16 "runtime/debug"
17 "strings"
18 "sync"
19 "syscall"
20 "testing"
21 "time"
22 "unsafe"
23 )
24
25 func init() {
26 if runtime.Sigisblocked(int(syscall.SIGQUIT)) {
27 // We can't use SIGQUIT to kill subprocesses because
28 // it's blocked. Use SIGKILL instead. See issue
29 // #19196 for an example of when this happens.
30 testenv.Sigquit = syscall.SIGKILL
31 }
32 }
33
34 func TestBadOpen(t *testing.T) {
35 // make sure we get the correct error code if open fails. Same for
36 // read/write/close on the resulting -1 fd. See issue 10052.
37 nonfile := []byte("/notreallyafile")
38 fd := runtime.Open(&nonfile[0], 0, 0)
39 if fd != -1 {
40 t.Errorf("open(%q)=%d, want -1", nonfile, fd)
41 }
42 var buf [32]byte
43 r := runtime.Read(-1, unsafe.Pointer(&buf[0]), int32(len(buf)))
44 if got, want := r, -int32(syscall.EBADF); got != want {
45 t.Errorf("read()=%d, want %d", got, want)
46 }
47 w := runtime.Write(^uintptr(0), unsafe.Pointer(&buf[0]), int32(len(buf)))
48 if got, want := w, -int32(syscall.EBADF); got != want {
49 t.Errorf("write()=%d, want %d", got, want)
50 }
51 c := runtime.Close(-1)
52 if c != -1 {
53 t.Errorf("close()=%d, want -1", c)
54 }
55 }
56
57 func TestCrashDumpsAllThreads(t *testing.T) {
58 if *flagQuick {
59 t.Skip("-quick")
60 }
61
62 if runtime.GOARCH == "mips64le" {
63 t.Skipf("skipping; flaky on %s", runtime.GOARCH)
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.GOOS == "openbsd" && (runtime.GOARCH == "arm" || runtime.GOARCH == "ppc64") {
73 // This may be ncpu < 2 related...
74 t.Skipf("skipping; test fails on %s/%s - see issue #42464", runtime.GOOS, runtime.GOARCH)
75 }
76
77 if runtime.Sigisblocked(int(syscall.SIGQUIT)) {
78 t.Skip("skipping; SIGQUIT is blocked, see golang.org/issue/19196")
79 }
80
81 testenv.MustHaveGoBuild(t)
82
83 if strings.Contains(os.Getenv("GOFLAGS"), "mayMoreStackPreempt") {
84 // This test occasionally times out in this debug mode. This is probably
85 // revealing a real bug in the scheduler, but since it seems to only
86 // affect this test and this is itself a test of a debug mode, it's not
87 // a high priority.
88 testenv.SkipFlaky(t, 55160)
89 }
90
91 exe, err := buildTestProg(t, "testprog")
92 if err != nil {
93 t.Fatal(err)
94 }
95
96 cmd := testenv.Command(t, exe, "CrashDumpsAllThreads")
97 cmd = testenv.CleanCmdEnv(cmd)
98 cmd.Dir = t.TempDir() // put any core file in tempdir
99 cmd.Env = append(cmd.Env,
100 "GOTRACEBACK=crash",
101 // Set GOGC=off. Because of golang.org/issue/10958, the tight
102 // loops in the test program are not preemptible. If GC kicks
103 // in, it may lock up and prevent main from saying it's ready.
104 "GOGC=off",
105 // Set GODEBUG=asyncpreemptoff=1. If a thread is preempted
106 // when it receives SIGQUIT, it won't show the expected
107 // stack trace. See issue 35356.
108 "GODEBUG=asyncpreemptoff=1",
109 )
110
111 var outbuf bytes.Buffer
112 cmd.Stdout = &outbuf
113 cmd.Stderr = &outbuf
114
115 rp, wp, err := os.Pipe()
116 if err != nil {
117 t.Fatal(err)
118 }
119 defer rp.Close()
120
121 cmd.ExtraFiles = []*os.File{wp}
122
123 if err := cmd.Start(); err != nil {
124 wp.Close()
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.crashDumpsAllThreadsLoop("))
148 if n != 4 {
149 t.Errorf("found %d instances of main.crashDumpsAllThreadsLoop; expected 4", n)
150 t.Logf("%s", out)
151 }
152 }
153
154 func TestPanicSystemstack(t *testing.T) {
155 // Test that GOTRACEBACK=crash prints both the system and user
156 // stack of other threads.
157
158 // The GOTRACEBACK=crash handler takes 0.1 seconds even if
159 // it's not writing a core file and potentially much longer if
160 // it is. Skip in short mode.
161 if testing.Short() {
162 t.Skip("Skipping in short mode (GOTRACEBACK=crash is slow)")
163 }
164
165 if runtime.Sigisblocked(int(syscall.SIGQUIT)) {
166 t.Skip("skipping; SIGQUIT is blocked, see golang.org/issue/19196")
167 }
168
169 t.Parallel()
170 cmd := exec.Command(testenv.Executable(t), "testPanicSystemstackInternal")
171 cmd = testenv.CleanCmdEnv(cmd)
172 cmd.Dir = t.TempDir() // put any core file in tempdir
173 cmd.Env = append(cmd.Env, "GOTRACEBACK=crash")
174 pr, pw, err := os.Pipe()
175 if err != nil {
176 t.Fatal("creating pipe: ", err)
177 }
178 cmd.Stderr = pw
179 if err := cmd.Start(); err != nil {
180 t.Fatal("starting command: ", err)
181 }
182 defer cmd.Process.Wait()
183 defer cmd.Process.Kill()
184 if err := pw.Close(); err != nil {
185 t.Log("closing write pipe: ", err)
186 }
187 defer pr.Close()
188
189 // Wait for "x\nx\n" to indicate almost-readiness.
190 buf := make([]byte, 4)
191 _, err = io.ReadFull(pr, buf)
192 if err != nil || string(buf) != "x\nx\n" {
193 t.Fatal("subprocess failed; output:\n", string(buf))
194 }
195
196 // The child blockers print "x\n" and then block on a lock. Receiving
197 // those bytes only indicates that the child is _about to block_. Since
198 // we don't have a way to know when it is fully blocked, sleep a bit to
199 // make us less likely to lose the race and signal before the child
200 // blocks.
201 time.Sleep(100 * time.Millisecond)
202
203 // Send SIGQUIT.
204 if err := cmd.Process.Signal(syscall.SIGQUIT); err != nil {
205 t.Fatal("signaling subprocess: ", err)
206 }
207
208 // Get traceback.
209 tb, err := io.ReadAll(pr)
210 if err != nil {
211 t.Fatal("reading traceback from pipe: ", err)
212 }
213
214 // Traceback should have two testPanicSystemstackInternal's
215 // and two blockOnSystemStackInternal's.
216 userFunc := "testPanicSystemstackInternal"
217 sysFunc := "blockOnSystemStackInternal"
218 nUser := bytes.Count(tb, []byte(userFunc))
219 nSys := bytes.Count(tb, []byte(sysFunc))
220 if nUser != 2 || nSys != 2 {
221 t.Fatalf("want %d user stack frames in %s and %d system stack frames in %s, got %d and %d:\n%s", 2, userFunc, 2, sysFunc, nUser, nSys, string(tb))
222 }
223
224 // Traceback should not contain "unexpected SPWRITE" when
225 // unwinding the system stacks.
226 if bytes.Contains(tb, []byte("unexpected SPWRITE")) {
227 t.Errorf("unexpected \"unexpected SPWRITE\" in traceback:\n%s", tb)
228 }
229 }
230
231 func init() {
232 if len(os.Args) >= 2 && os.Args[1] == "testPanicSystemstackInternal" {
233 // Complete any in-flight GCs and disable future ones. We're going to
234 // block goroutines on runtime locks, which aren't ever preemptible for the
235 // GC to scan them.
236 runtime.GC()
237 debug.SetGCPercent(-1)
238 // Get two threads running on the system stack with
239 // something recognizable in the stack trace.
240 runtime.GOMAXPROCS(2)
241 go testPanicSystemstackInternal()
242 testPanicSystemstackInternal()
243 }
244 }
245
246 func testPanicSystemstackInternal() {
247 runtime.BlockOnSystemStack()
248 os.Exit(1) // Should be unreachable.
249 }
250
251 func TestSignalExitStatus(t *testing.T) {
252 testenv.MustHaveGoBuild(t)
253 exe, err := buildTestProg(t, "testprog")
254 if err != nil {
255 t.Fatal(err)
256 }
257 err = testenv.CleanCmdEnv(exec.Command(exe, "SignalExitStatus")).Run()
258 if err == nil {
259 t.Error("test program succeeded unexpectedly")
260 } else if ee, ok := err.(*exec.ExitError); !ok {
261 t.Errorf("error (%v) has type %T; expected exec.ExitError", err, err)
262 } else if ws, ok := ee.Sys().(syscall.WaitStatus); !ok {
263 t.Errorf("error.Sys (%v) has type %T; expected syscall.WaitStatus", ee.Sys(), ee.Sys())
264 } else if !ws.Signaled() || ws.Signal() != syscall.SIGTERM {
265 t.Errorf("got %v; expected SIGTERM", ee)
266 }
267 }
268
269 func TestSignalIgnoreSIGTRAP(t *testing.T) {
270 if runtime.GOOS == "openbsd" {
271 testenv.SkipFlaky(t, 49725)
272 }
273
274 output := runTestProg(t, "testprognet", "SignalIgnoreSIGTRAP")
275 want := "OK\n"
276 if output != want {
277 t.Fatalf("want %s, got %s\n", want, output)
278 }
279 }
280
281 func TestSignalDuringExec(t *testing.T) {
282 switch runtime.GOOS {
283 case "darwin", "dragonfly", "freebsd", "linux", "netbsd", "openbsd":
284 default:
285 t.Skipf("skipping test on %s", runtime.GOOS)
286 }
287 output := runTestProg(t, "testprognet", "SignalDuringExec")
288 want := "OK\n"
289 if output != want {
290 t.Fatalf("want %s, got %s\n", want, output)
291 }
292 }
293
294 func TestSignalM(t *testing.T) {
295 r, w, errno := runtime.Pipe()
296 if errno != 0 {
297 t.Fatal(syscall.Errno(errno))
298 }
299 defer func() {
300 runtime.Close(r)
301 runtime.Close(w)
302 }()
303 runtime.Closeonexec(r)
304 runtime.Closeonexec(w)
305
306 var want, got int64
307 var wg sync.WaitGroup
308 ready := make(chan *runtime.M)
309 wg.Add(1)
310 go func() {
311 runtime.LockOSThread()
312 want, got = runtime.WaitForSigusr1(r, w, func(mp *runtime.M) {
313 ready <- mp
314 })
315 runtime.UnlockOSThread()
316 wg.Done()
317 }()
318 waitingM := <-ready
319 runtime.SendSigusr1(waitingM)
320
321 timer := time.AfterFunc(time.Second, func() {
322 // Write 1 to tell WaitForSigusr1 that we timed out.
323 bw := byte(1)
324 if n := runtime.Write(uintptr(w), unsafe.Pointer(&bw), 1); n != 1 {
325 t.Errorf("pipe write failed: %d", n)
326 }
327 })
328 defer timer.Stop()
329
330 wg.Wait()
331 if got == -1 {
332 t.Fatal("signalM signal not received")
333 } else if want != got {
334 t.Fatalf("signal sent to M %d, but received on M %d", want, got)
335 }
336 }