Source file
src/runtime/runtime-gdb_test.go
1
2
3
4
5 package runtime_test
6
7 import (
8 "bytes"
9 "flag"
10 "fmt"
11 "internal/goexperiment"
12 "internal/testenv"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "regexp"
17 "runtime"
18 "strconv"
19 "strings"
20 "testing"
21 "time"
22 )
23
24
25
26
27
28
29
30 func checkGdbEnvironment(t *testing.T) {
31 testenv.MustHaveGoBuild(t)
32 switch runtime.GOOS {
33 case "darwin":
34 t.Skip("gdb does not work on darwin")
35 case "netbsd":
36 t.Skip("gdb does not work with threads on NetBSD; see https://golang.org/issue/22893 and https://gnats.netbsd.org/52548")
37 case "linux":
38 if runtime.GOARCH == "ppc64" {
39 t.Skip("skipping gdb tests on linux/ppc64; see https://golang.org/issue/17366")
40 }
41 if runtime.GOARCH == "mips" {
42 t.Skip("skipping gdb tests on linux/mips; see https://golang.org/issue/25939")
43 }
44
45 if strings.HasSuffix(testenv.Builder(), "-alpine") {
46 t.Skip("skipping gdb tests on alpine; see https://golang.org/issue/54352")
47 }
48 case "freebsd":
49 t.Skip("skipping gdb tests on FreeBSD; see https://golang.org/issue/29508")
50 case "aix":
51 if testing.Short() {
52 t.Skip("skipping gdb tests on AIX; see https://golang.org/issue/35710")
53 }
54 case "plan9":
55 t.Skip("there is no gdb on Plan 9")
56 }
57 }
58
59 func checkGdbVersion(t *testing.T) {
60
61 out, err := exec.Command("gdb", "--version").CombinedOutput()
62 if err != nil {
63 t.Skipf("skipping: error executing gdb: %v", err)
64 }
65 re := regexp.MustCompile(`([0-9]+)\.([0-9]+)`)
66 matches := re.FindSubmatch(out)
67 if len(matches) < 3 {
68 t.Skipf("skipping: can't determine gdb version from\n%s\n", out)
69 }
70 major, err1 := strconv.Atoi(string(matches[1]))
71 minor, err2 := strconv.Atoi(string(matches[2]))
72 if err1 != nil || err2 != nil {
73 t.Skipf("skipping: can't determine gdb version: %v, %v", err1, err2)
74 }
75
76
77 if major < 10 {
78 t.Skipf("skipping: gdb version %d.%d too old", major, minor)
79 }
80 if major < 12 || (major == 12 && minor < 1) {
81 t.Logf("gdb version <12.1 is known to crash due to a SIGWINCH received in non-interactive mode; if you see a crash, some test may be sending SIGWINCH to the whole process group. See go.dev/issue/58932.")
82 }
83 t.Logf("gdb version %d.%d", major, minor)
84 }
85
86 func checkGdbPython(t *testing.T) {
87 if runtime.GOOS == "solaris" || runtime.GOOS == "illumos" {
88 t.Skip("skipping gdb python tests on illumos and solaris; see golang.org/issue/20821")
89 }
90 args := []string{"-nx", "-q", "--batch", "-iex", "python import sys; print('go gdb python support')"}
91 gdbArgsFixup(args)
92 cmd := exec.Command("gdb", args...)
93 out, err := cmd.CombinedOutput()
94
95 if err != nil {
96 t.Skipf("skipping due to issue running gdb: %v", err)
97 }
98 if strings.TrimSpace(string(out)) != "go gdb python support" {
99 t.Skipf("skipping due to lack of python gdb support: %s", out)
100 }
101 }
102
103
104
105 func checkCleanBacktrace(t *testing.T, backtrace string) {
106 backtrace = strings.TrimSpace(backtrace)
107 lines := strings.Split(backtrace, "\n")
108 if len(lines) == 0 {
109 t.Fatalf("empty backtrace")
110 }
111 for i, l := range lines {
112 if !strings.HasPrefix(l, fmt.Sprintf("#%v ", i)) {
113 t.Fatalf("malformed backtrace at line %v: %v", i, l)
114 }
115 }
116
117 }
118
119
120
121
122
123
124
125
126
127 func checkPtraceScope(t *testing.T) {
128 if runtime.GOOS != "linux" {
129 return
130 }
131
132
133
134 path := "/proc/sys/kernel/yama/ptrace_scope"
135 if _, err := os.Stat(path); os.IsNotExist(err) {
136 return
137 }
138
139 data, err := os.ReadFile(path)
140 if err != nil {
141 t.Fatalf("failed to read file: %v", err)
142 }
143 value, err := strconv.Atoi(strings.TrimSpace(string(data)))
144 if err != nil {
145 t.Fatalf("failed converting value to int: %v", err)
146 }
147 switch value {
148 case 3:
149 t.Skip("skipping ptrace: Operation not permitted")
150 case 2:
151 if os.Geteuid() != 0 {
152 t.Skip("skipping ptrace: Operation not permitted with non-root user")
153 }
154 }
155 }
156
157 var helloSource = `
158 import "fmt"
159 import "runtime"
160 var gslice []string
161 // TODO(prattmic): Stack allocated maps initialized inline appear "optimized out" in GDB.
162 var smallmapvar map[string]string
163 func main() {
164 smallmapvar = make(map[string]string)
165 // NOTE: the maps below are allocated large to ensure that they are not
166 // "optimized out".
167 mapvar := make(map[string]string, 10)
168 slicemap := make(map[string][]string, 10)
169 chanint := make(chan int, 10)
170 chanstr := make(chan string, 10)
171 chanint <- 99
172 chanint <- 11
173 chanstr <- "spongepants"
174 chanstr <- "squarebob"
175 smallmapvar["abc"] = "def"
176 mapvar["abc"] = "def"
177 mapvar["ghi"] = "jkl"
178 slicemap["a"] = []string{"b","c","d"}
179 slicemap["e"] = []string{"f","g","h"}
180 strvar := "abc"
181 ptrvar := &strvar
182 slicevar := make([]string, 0, 16)
183 slicevar = append(slicevar, mapvar["abc"])
184 fmt.Println("hi")
185 runtime.KeepAlive(ptrvar)
186 _ = ptrvar // set breakpoint here
187 gslice = slicevar
188 fmt.Printf("%v, %v, %v\n", slicemap, <-chanint, <-chanstr)
189 runtime.KeepAlive(smallmapvar)
190 runtime.KeepAlive(mapvar)
191 } // END_OF_PROGRAM
192 `
193
194 func lastLine(src []byte) int {
195 eop := []byte("END_OF_PROGRAM")
196 for i, l := range bytes.Split(src, []byte("\n")) {
197 if bytes.Contains(l, eop) {
198 return i
199 }
200 }
201 return 0
202 }
203
204 func gdbArgsFixup(args []string) {
205 if runtime.GOOS != "windows" {
206 return
207 }
208
209
210 var quote bool
211 for i, arg := range args {
212 if arg == "-iex" || arg == "-ex" {
213 quote = true
214 } else if quote {
215 if strings.ContainsRune(arg, ' ') {
216 args[i] = `"` + arg + `"`
217 }
218 quote = false
219 }
220 }
221 }
222
223 func TestGdbPython(t *testing.T) {
224 testGdbPython(t, false)
225 }
226
227 func TestGdbPythonCgo(t *testing.T) {
228 if strings.HasPrefix(runtime.GOARCH, "mips") {
229 testenv.SkipFlaky(t, 37794)
230 }
231 testGdbPython(t, true)
232 }
233
234 func testGdbPython(t *testing.T, cgo bool) {
235 if cgo {
236 testenv.MustHaveCGO(t)
237 }
238
239 checkGdbEnvironment(t)
240 t.Parallel()
241 checkGdbVersion(t)
242 checkGdbPython(t)
243 checkPtraceScope(t)
244
245 dir := t.TempDir()
246
247 var buf bytes.Buffer
248 buf.WriteString("package main\n")
249 if cgo {
250 buf.WriteString(`import "C"` + "\n")
251 }
252 buf.WriteString(helloSource)
253
254 src := buf.Bytes()
255
256
257 var bp int
258 lines := bytes.Split(src, []byte("\n"))
259 for i, line := range lines {
260 if bytes.Contains(line, []byte("breakpoint")) {
261 bp = i
262 break
263 }
264 }
265
266 err := os.WriteFile(filepath.Join(dir, "main.go"), src, 0644)
267 if err != nil {
268 t.Fatalf("failed to create file: %v", err)
269 }
270 nLines := lastLine(src)
271
272 cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", "a.exe", "main.go")
273 cmd.Dir = dir
274 out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
275 if err != nil {
276 t.Fatalf("building source %v\n%s", err, out)
277 }
278
279 args := []string{"-nx", "-q", "--batch",
280 "-iex", "add-auto-load-safe-path " + filepath.Join(testenv.GOROOT(t), "src", "runtime"),
281 "-ex", "set startup-with-shell off",
282 "-ex", "set print thread-events off",
283 }
284 if cgo {
285
286
287
288
289
290 args = append(args,
291 "-ex", "source "+filepath.Join(testenv.GOROOT(t), "src", "runtime", "runtime-gdb.py"),
292 )
293 } else {
294 args = append(args,
295 "-ex", "info auto-load python-scripts",
296 )
297 }
298 args = append(args,
299 "-ex", "set python print-stack full",
300 "-ex", fmt.Sprintf("br main.go:%d", bp),
301 "-ex", "run",
302 "-ex", "echo BEGIN info goroutines\n",
303 "-ex", "info goroutines",
304 "-ex", "echo END\n",
305 "-ex", "echo BEGIN print smallmapvar\n",
306 "-ex", "print smallmapvar",
307 "-ex", "echo END\n",
308 "-ex", "echo BEGIN print mapvar\n",
309 "-ex", "print mapvar",
310 "-ex", "echo END\n",
311 "-ex", "echo BEGIN print slicemap\n",
312 "-ex", "print slicemap",
313 "-ex", "echo END\n",
314 "-ex", "echo BEGIN print strvar\n",
315 "-ex", "print strvar",
316 "-ex", "echo END\n",
317 "-ex", "echo BEGIN print chanint\n",
318 "-ex", "print chanint",
319 "-ex", "echo END\n",
320 "-ex", "echo BEGIN print chanstr\n",
321 "-ex", "print chanstr",
322 "-ex", "echo END\n",
323 "-ex", "echo BEGIN info locals\n",
324 "-ex", "info locals",
325 "-ex", "echo END\n",
326 "-ex", "echo BEGIN goroutine 1 bt\n",
327 "-ex", "goroutine 1 bt",
328 "-ex", "echo END\n",
329 "-ex", "echo BEGIN goroutine all bt\n",
330 "-ex", "goroutine all bt",
331 "-ex", "echo END\n",
332 "-ex", "clear main.go:15",
333 "-ex", fmt.Sprintf("br main.go:%d", nLines),
334 "-ex", "c",
335 "-ex", "echo BEGIN goroutine 1 bt at the end\n",
336 "-ex", "goroutine 1 bt",
337 "-ex", "echo END\n",
338 filepath.Join(dir, "a.exe"),
339 )
340 gdbArgsFixup(args)
341 got, err := exec.Command("gdb", args...).CombinedOutput()
342 t.Logf("gdb output:\n%s", got)
343 if err != nil {
344 t.Fatalf("gdb exited with error: %v", err)
345 }
346
347 got = bytes.ReplaceAll(got, []byte("\r\n"), []byte("\n"))
348
349 partRe := regexp.MustCompile(`(?ms)^BEGIN ([^\n]*)\n(.*?)\nEND`)
350 blocks := map[string]string{}
351 for _, subs := range partRe.FindAllSubmatch(got, -1) {
352 blocks[string(subs[1])] = string(subs[2])
353 }
354
355 infoGoroutinesRe := regexp.MustCompile(`\*\s+\d+\s+running\s+`)
356 if bl := blocks["info goroutines"]; !infoGoroutinesRe.MatchString(bl) {
357 t.Fatalf("info goroutines failed: %s", bl)
358 }
359
360 printSmallMapvarRe := regexp.MustCompile(`^\$[0-9]+ = map\[string\]string = {\[(0x[0-9a-f]+\s+)?"abc"\] = (0x[0-9a-f]+\s+)?"def"}$`)
361 if bl := blocks["print smallmapvar"]; !printSmallMapvarRe.MatchString(bl) {
362 t.Fatalf("print smallmapvar failed: %s", bl)
363 }
364
365 printMapvarRe1 := regexp.MustCompile(`^\$[0-9]+ = map\[string\]string = {\[(0x[0-9a-f]+\s+)?"abc"\] = (0x[0-9a-f]+\s+)?"def", \[(0x[0-9a-f]+\s+)?"ghi"\] = (0x[0-9a-f]+\s+)?"jkl"}$`)
366 printMapvarRe2 := regexp.MustCompile(`^\$[0-9]+ = map\[string\]string = {\[(0x[0-9a-f]+\s+)?"ghi"\] = (0x[0-9a-f]+\s+)?"jkl", \[(0x[0-9a-f]+\s+)?"abc"\] = (0x[0-9a-f]+\s+)?"def"}$`)
367 if bl := blocks["print mapvar"]; !printMapvarRe1.MatchString(bl) &&
368 !printMapvarRe2.MatchString(bl) {
369 t.Fatalf("print mapvar failed: %s", bl)
370 }
371
372
373 sliceMapSfx1 := `map[string][]string = {["e"] = []string = {"f", "g", "h"}, ["a"] = []string = {"b", "c", "d"}}`
374 sliceMapSfx2 := `map[string][]string = {["a"] = []string = {"b", "c", "d"}, ["e"] = []string = {"f", "g", "h"}}`
375 if bl := strings.ReplaceAll(blocks["print slicemap"], " ", " "); !strings.HasSuffix(bl, sliceMapSfx1) && !strings.HasSuffix(bl, sliceMapSfx2) {
376 t.Fatalf("print slicemap failed: %s", bl)
377 }
378
379 chanIntSfx := `chan int = {99, 11}`
380 if bl := strings.ReplaceAll(blocks["print chanint"], " ", " "); !strings.HasSuffix(bl, chanIntSfx) {
381 t.Fatalf("print chanint failed: %s", bl)
382 }
383
384 chanStrSfx := `chan string = {"spongepants", "squarebob"}`
385 if bl := strings.ReplaceAll(blocks["print chanstr"], " ", " "); !strings.HasSuffix(bl, chanStrSfx) {
386 t.Fatalf("print chanstr failed: %s", bl)
387 }
388
389 strVarRe := regexp.MustCompile(`^\$[0-9]+ = (0x[0-9a-f]+\s+)?"abc"$`)
390 if bl := blocks["print strvar"]; !strVarRe.MatchString(bl) {
391 t.Fatalf("print strvar failed: %s", bl)
392 }
393
394
395
396
397
398
399
400
401
402
403
404
405
406 if bl := blocks["info locals"]; !strings.Contains(bl, "slicevar") ||
407 !strings.Contains(bl, "mapvar") ||
408 !strings.Contains(bl, "strvar") {
409 t.Fatalf("info locals failed: %s", bl)
410 }
411
412
413 checkCleanBacktrace(t, blocks["goroutine 1 bt"])
414 checkCleanBacktrace(t, blocks["goroutine 1 bt at the end"])
415
416 btGoroutine1Re := regexp.MustCompile(`(?m)^#0\s+(0x[0-9a-f]+\s+in\s+)?main\.main.+at`)
417 if bl := blocks["goroutine 1 bt"]; !btGoroutine1Re.MatchString(bl) {
418 t.Fatalf("goroutine 1 bt failed: %s", bl)
419 }
420
421 if bl := blocks["goroutine all bt"]; !btGoroutine1Re.MatchString(bl) {
422 t.Fatalf("goroutine all bt failed: %s", bl)
423 }
424
425 btGoroutine1AtTheEndRe := regexp.MustCompile(`(?m)^#0\s+(0x[0-9a-f]+\s+in\s+)?main\.main.+at`)
426 if bl := blocks["goroutine 1 bt at the end"]; !btGoroutine1AtTheEndRe.MatchString(bl) {
427 t.Fatalf("goroutine 1 bt at the end failed: %s", bl)
428 }
429 }
430
431 const backtraceSource = `
432 package main
433
434 //go:noinline
435 func aaa() bool { return bbb() }
436
437 //go:noinline
438 func bbb() bool { return ccc() }
439
440 //go:noinline
441 func ccc() bool { return ddd() }
442
443 //go:noinline
444 func ddd() bool { return f() }
445
446 //go:noinline
447 func eee() bool { return true }
448
449 var f = eee
450
451 func main() {
452 _ = aaa()
453 }
454 `
455
456
457
458 func TestGdbBacktrace(t *testing.T) {
459 if runtime.GOOS == "netbsd" {
460 testenv.SkipFlaky(t, 15603)
461 }
462 if flag.Lookup("test.parallel").Value.(flag.Getter).Get().(int) < 2 {
463
464
465
466
467
468
469 testenv.SkipFlaky(t, 37405)
470 }
471
472 checkGdbEnvironment(t)
473 t.Parallel()
474 checkGdbVersion(t)
475 checkPtraceScope(t)
476
477 dir := t.TempDir()
478
479
480 src := filepath.Join(dir, "main.go")
481 err := os.WriteFile(src, []byte(backtraceSource), 0644)
482 if err != nil {
483 t.Fatalf("failed to create file: %v", err)
484 }
485 cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", "a.exe", "main.go")
486 cmd.Dir = dir
487 out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
488 if err != nil {
489 t.Fatalf("building source %v\n%s", err, out)
490 }
491
492
493 start := time.Now()
494 args := []string{"-nx", "-batch",
495 "-iex", "add-auto-load-safe-path " + filepath.Join(testenv.GOROOT(t), "src", "runtime"),
496 "-ex", "set startup-with-shell off",
497 "-ex", "break main.eee",
498 "-ex", "run",
499 "-ex", "backtrace",
500 "-ex", "continue",
501 filepath.Join(dir, "a.exe"),
502 }
503 gdbArgsFixup(args)
504 cmd = testenv.Command(t, "gdb", args...)
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524 cmd.Cancel = func() error {
525 t.Logf("GDB command timed out after %v: %v", time.Since(start), cmd)
526 return cmd.Process.Kill()
527 }
528
529 got, err := cmd.CombinedOutput()
530 t.Logf("gdb output:\n%s", got)
531 if err != nil {
532 noProcessRE := regexp.MustCompile(`Couldn't get [a-zA-Z_ -]* ?registers: No such process\.`)
533 switch {
534 case bytes.Contains(got, []byte("internal-error: wait returned unexpected status 0x0")):
535
536 testenv.SkipFlaky(t, 43068)
537 case noProcessRE.Match(got),
538 bytes.Contains(got, []byte("Unable to fetch general registers.: No such process.")),
539 bytes.Contains(got, []byte("reading register pc (#64): No such process.")):
540
541 testenv.SkipFlaky(t, 50838)
542 case bytes.Contains(got, []byte("waiting for new child: No child processes.")):
543
544 testenv.SkipFlaky(t, 60553)
545 case bytes.Contains(got, []byte(" exited normally]\n")):
546
547
548 testenv.SkipFlaky(t, 37405)
549 }
550 t.Fatalf("gdb exited with error: %v", err)
551 }
552
553
554 bt := []string{
555 "eee",
556 "ddd",
557 "ccc",
558 "bbb",
559 "aaa",
560 "main",
561 }
562 for i, name := range bt {
563 s := fmt.Sprintf("#%v.*main\\.%v", i, name)
564 re := regexp.MustCompile(s)
565 if found := re.Find(got) != nil; !found {
566 t.Fatalf("could not find '%v' in backtrace", s)
567 }
568 }
569 }
570
571 const autotmpTypeSource = `
572 package main
573
574 type astruct struct {
575 a, b int
576 }
577
578 func main() {
579 var iface interface{} = map[string]astruct{}
580 var iface2 interface{} = []astruct{}
581 println(iface, iface2)
582 }
583 `
584
585
586
587 func TestGdbAutotmpTypes(t *testing.T) {
588 checkGdbEnvironment(t)
589 t.Parallel()
590 checkGdbVersion(t)
591 checkPtraceScope(t)
592
593 if runtime.GOOS == "aix" && testing.Short() {
594 t.Skip("TestGdbAutotmpTypes is too slow on aix/ppc64")
595 }
596
597 dir := t.TempDir()
598
599
600 src := filepath.Join(dir, "main.go")
601 err := os.WriteFile(src, []byte(autotmpTypeSource), 0644)
602 if err != nil {
603 t.Fatalf("failed to create file: %v", err)
604 }
605 cmd := exec.Command(testenv.GoToolPath(t), "build", "-gcflags=all=-N -l", "-o", "a.exe", "main.go")
606 cmd.Dir = dir
607 out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
608 if err != nil {
609 t.Fatalf("building source %v\n%s", err, out)
610 }
611
612
613 args := []string{"-nx", "-batch",
614 "-iex", "add-auto-load-safe-path " + filepath.Join(testenv.GOROOT(t), "src", "runtime"),
615 "-ex", "set startup-with-shell off",
616
617
618
619 "-ex", "set scheduler-locking off",
620 "-ex", "break main.main",
621 "-ex", "run",
622 "-ex", "step",
623 "-ex", "info types astruct",
624 filepath.Join(dir, "a.exe"),
625 }
626 gdbArgsFixup(args)
627 got, err := exec.Command("gdb", args...).CombinedOutput()
628 t.Logf("gdb output:\n%s", got)
629 if err != nil {
630 t.Fatalf("gdb exited with error: %v", err)
631 }
632
633 sgot := string(got)
634
635
636 types := []string{
637 "[]main.astruct",
638 "main.astruct",
639 "groupReference<string,main.astruct>",
640 "table<string,main.astruct>",
641 "map<string,main.astruct>",
642 "map<string,main.astruct> * map[string]main.astruct",
643 }
644 for _, name := range types {
645 if !strings.Contains(sgot, name) {
646 t.Fatalf("could not find %q in 'info typrs astruct' output", name)
647 }
648 }
649 }
650
651 const constsSource = `
652 package main
653
654 const aConstant int = 42
655 const largeConstant uint64 = ^uint64(0)
656 const minusOne int64 = -1
657
658 func main() {
659 println("hello world")
660 }
661 `
662
663 func TestGdbConst(t *testing.T) {
664 checkGdbEnvironment(t)
665 t.Parallel()
666 checkGdbVersion(t)
667 checkPtraceScope(t)
668
669 dir := t.TempDir()
670
671
672 src := filepath.Join(dir, "main.go")
673 err := os.WriteFile(src, []byte(constsSource), 0644)
674 if err != nil {
675 t.Fatalf("failed to create file: %v", err)
676 }
677 cmd := exec.Command(testenv.GoToolPath(t), "build", "-gcflags=all=-N -l", "-o", "a.exe", "main.go")
678 cmd.Dir = dir
679 out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
680 if err != nil {
681 t.Fatalf("building source %v\n%s", err, out)
682 }
683
684
685 args := []string{"-nx", "-batch",
686 "-iex", "add-auto-load-safe-path " + filepath.Join(testenv.GOROOT(t), "src", "runtime"),
687 "-ex", "set startup-with-shell off",
688 "-ex", "break main.main",
689 "-ex", "run",
690 "-ex", "print main.aConstant",
691 "-ex", "print main.largeConstant",
692 "-ex", "print main.minusOne",
693 "-ex", "print 'runtime.mSpanInUse'",
694 "-ex", "print 'runtime._PageSize'",
695 filepath.Join(dir, "a.exe"),
696 }
697 gdbArgsFixup(args)
698 got, err := exec.Command("gdb", args...).CombinedOutput()
699 t.Logf("gdb output:\n%s", got)
700 if err != nil {
701 t.Fatalf("gdb exited with error: %v", err)
702 }
703
704 sgot := strings.ReplaceAll(string(got), "\r\n", "\n")
705
706 if !strings.Contains(sgot, "\n$1 = 42\n$2 = 18446744073709551615\n$3 = -1\n$4 = 1 '\\001'\n$5 = 8192") {
707 t.Fatalf("output mismatch")
708 }
709 }
710
711 const panicSource = `
712 package main
713
714 import "runtime/debug"
715
716 func main() {
717 debug.SetTraceback("crash")
718 crash()
719 }
720
721 func crash() {
722 panic("panic!")
723 }
724 `
725
726
727
728 func TestGdbPanic(t *testing.T) {
729 checkGdbEnvironment(t)
730 t.Parallel()
731 checkGdbVersion(t)
732 checkPtraceScope(t)
733
734 if runtime.GOOS == "windows" {
735 t.Skip("no signals on windows")
736 }
737
738 dir := t.TempDir()
739
740
741 src := filepath.Join(dir, "main.go")
742 err := os.WriteFile(src, []byte(panicSource), 0644)
743 if err != nil {
744 t.Fatalf("failed to create file: %v", err)
745 }
746 cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", "a.exe", "main.go")
747 cmd.Dir = dir
748 out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
749 if err != nil {
750 t.Fatalf("building source %v\n%s", err, out)
751 }
752
753
754 args := []string{"-nx", "-batch",
755 "-iex", "add-auto-load-safe-path " + filepath.Join(testenv.GOROOT(t), "src", "runtime"),
756 "-ex", "set startup-with-shell off",
757 "-ex", "run",
758 "-ex", "backtrace",
759 filepath.Join(dir, "a.exe"),
760 }
761 gdbArgsFixup(args)
762 got, err := exec.Command("gdb", args...).CombinedOutput()
763 t.Logf("gdb output:\n%s", got)
764 if err != nil {
765 t.Fatalf("gdb exited with error: %v", err)
766 }
767
768
769 bt := []string{
770 `crash`,
771 `main`,
772 }
773 for _, name := range bt {
774 s := fmt.Sprintf("(#.* .* in )?main\\.%v", name)
775 re := regexp.MustCompile(s)
776 if found := re.Find(got) != nil; !found {
777 t.Fatalf("could not find '%v' in backtrace", s)
778 }
779 }
780 }
781
782 const InfCallstackSource = `
783 package main
784 import "C"
785 import "time"
786
787 func loop() {
788 for i := 0; i < 1000; i++ {
789 time.Sleep(time.Millisecond*5)
790 }
791 }
792
793 func main() {
794 go loop()
795 time.Sleep(time.Second * 1)
796 }
797 `
798
799
800
801
802 func TestGdbInfCallstack(t *testing.T) {
803 checkGdbEnvironment(t)
804
805 testenv.MustHaveCGO(t)
806 if runtime.GOARCH != "arm64" {
807 t.Skip("skipping infinite callstack test on non-arm64 arches")
808 }
809
810 t.Parallel()
811 checkGdbVersion(t)
812 checkPtraceScope(t)
813
814 dir := t.TempDir()
815
816
817 src := filepath.Join(dir, "main.go")
818 err := os.WriteFile(src, []byte(InfCallstackSource), 0644)
819 if err != nil {
820 t.Fatalf("failed to create file: %v", err)
821 }
822 cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", "a.exe", "main.go")
823 cmd.Dir = dir
824 out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
825 if err != nil {
826 t.Fatalf("building source %v\n%s", err, out)
827 }
828
829
830 breakSym := "setg_gcc"
831 bt := []string{
832 `setg_gcc`,
833 `crosscall1`,
834 `threadentry`,
835 }
836 if goexperiment.CgoBindings && (runtime.GOOS == "linux" || runtime.GOOS == "darwin") {
837
838 breakSym = "'runtime.setg'"
839 bt = []string{
840 `runtime\.setg`,
841 `threadentry`,
842 `threadentry`,
843 `x_cgo_threadentry`,
844 }
845 }
846 args := []string{"-nx", "-batch",
847 "-iex", "add-auto-load-safe-path " + filepath.Join(testenv.GOROOT(t), "src", "runtime"),
848 "-ex", "set startup-with-shell off",
849 "-ex", "break " + breakSym,
850 "-ex", "run",
851 "-ex", fmt.Sprintf("backtrace %d", len(bt)),
852 "-ex", "disable 1",
853 "-ex", "continue",
854 filepath.Join(dir, "a.exe"),
855 }
856 gdbArgsFixup(args)
857 got, err := exec.Command("gdb", args...).CombinedOutput()
858 t.Logf("gdb output:\n%s", got)
859 if err != nil {
860 t.Fatalf("gdb exited with error: %v", err)
861 }
862
863
864 for i, name := range bt {
865 s := fmt.Sprintf("#%v.*%v", i, name)
866 re := regexp.MustCompile(s)
867 if found := re.Find(got) != nil; !found {
868 t.Fatalf("could not find '%v' in backtrace", s)
869 }
870 }
871 }
872
View as plain text