Source file src/runtime/runtime-gdb_test.go

     1  // Copyright 2015 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  	"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  // NOTE: In some configurations, GDB will segfault when sent a SIGWINCH signal.
    25  // Some runtime tests send SIGWINCH to the entire process group, so those tests
    26  // must never run in parallel with GDB tests.
    27  //
    28  // See issue 39021 and https://sourceware.org/bugzilla/show_bug.cgi?id=26056.
    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  		// Disable GDB tests on alpine until issue #54352 resolved.
    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  	// Issue 11214 reports various failures with older versions of gdb.
    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  	// The Go toolchain now generates DWARF 5 by default, which needs
    76  	// a GDB version of 10 or above.
    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  // checkCleanBacktrace checks that the given backtrace is well formed and does
   104  // not contain any error messages from GDB.
   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  	// TODO(mundaym): check for unknown frames (e.g. "??").
   117  }
   118  
   119  // checkPtraceScope checks the value of the kernel parameter ptrace_scope,
   120  // skips the test when gdb cannot attach to the target process via ptrace.
   121  // See issue 69932
   122  //
   123  // 0 - Default attach security permissions.
   124  // 1 - Restricted attach. Only child processes plus normal permissions.
   125  // 2 - Admin-only attach. Only executables with CAP_SYS_PTRACE.
   126  // 3 - No attach. No process may call ptrace at all. Irrevocable.
   127  func checkPtraceScope(t *testing.T) {
   128  	if runtime.GOOS != "linux" {
   129  		return
   130  	}
   131  
   132  	// If the Linux kernel does not have the YAMA module enabled,
   133  	// there will be no ptrace_scope file, which does not affect the tests.
   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  	// On Windows, some gdb flavors expect -ex and -iex arguments
   209  	// containing spaces to be double quoted.
   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  	// Locate breakpoint line
   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  		// When we build the cgo version of the program, the system's
   286  		// linker is used. Some external linkers, like GNU gold,
   287  		// compress the .debug_gdb_scripts into .zdebug_gdb_scripts.
   288  		// Until gold and gdb can work together, temporarily load the
   289  		// python script directly.
   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", // clear the previous break point
   333  		"-ex", fmt.Sprintf("br main.go:%d", nLines), // new break point at the end of main
   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")) // normalize line endings
   348  	// Extract named BEGIN...END blocks from output
   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  	// 2 orders, and possible differences in spacing.
   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  	// The exact format of composite values has changed over time.
   395  	// For issue 16338: ssa decompose phase split a slice into
   396  	// a collection of scalar vars holding its fields. In such cases
   397  	// the DWARF variable location expression should be of the
   398  	// form "var.field" and not just "field".
   399  	// However, the newer dwarf location list code reconstituted
   400  	// aggregates from their fields and reverted their printing
   401  	// back to its original form.
   402  	// Only test that all variables are listed in 'info locals' since
   403  	// different versions of gdb print variables in different
   404  	// order and with differing amount of information and formats.
   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  	// Check that the backtraces are well formed.
   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  // TestGdbBacktrace tests that gdb can unwind the stack correctly
   457  // using only the DWARF debug info.
   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  		// It is possible that this test will hang for a long time due to an
   464  		// apparent GDB bug reported in https://go.dev/issue/37405.
   465  		// If test parallelism is high enough, that might be ok: the other parallel
   466  		// tests will finish, and then this test will finish right before it would
   467  		// time out. However, if test are running sequentially, a hang in this test
   468  		// would likely cause the remaining tests to run out of time.
   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  	// Build the source code.
   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  	// Execute gdb commands.
   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  	// Work around the GDB hang reported in https://go.dev/issue/37405.
   507  	// Sometimes (rarely), the GDB process hangs completely when the Go program
   508  	// exits, and we suspect that the bug is on the GDB side.
   509  	//
   510  	// The default Cancel function added by testenv.Command will mark the test as
   511  	// failed if it is in danger of timing out, but we want to instead mark it as
   512  	// skipped. Change the Cancel function to kill the process and merely log
   513  	// instead of failing the test.
   514  	//
   515  	// (This approach does not scale: if the test parallelism is less than or
   516  	// equal to the number of tests that run right up to the deadline, then the
   517  	// remaining parallel tests are likely to time out. But as long as it's just
   518  	// this one flaky test, it's probably fine..?)
   519  	//
   520  	// If there is no deadline set on the test at all, relying on the timeout set
   521  	// by testenv.Command will cause the test to hang indefinitely, but that's
   522  	// what “no deadline” means, after all — and it's probably the right behavior
   523  	// anyway if someone is trying to investigate and fix the GDB bug.
   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  			// GDB bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28551
   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  			// GDB bug: https://sourceware.org/bugzilla/show_bug.cgi?id=9086
   541  			testenv.SkipFlaky(t, 50838)
   542  		case bytes.Contains(got, []byte("waiting for new child: No child processes.")):
   543  			// GDB bug: Sometimes it fails to wait for a clone child.
   544  			testenv.SkipFlaky(t, 60553)
   545  		case bytes.Contains(got, []byte(" exited normally]\n")):
   546  			// GDB bug: Sometimes the inferior exits fine,
   547  			// but then GDB hangs.
   548  			testenv.SkipFlaky(t, 37405)
   549  		}
   550  		t.Fatalf("gdb exited with error: %v", err)
   551  	}
   552  
   553  	// Check that the backtrace matches the source code.
   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  // TestGdbAutotmpTypes ensures that types of autotmp variables appear in .debug_info
   586  // See bug #17830.
   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  	// Build the source code.
   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  	// Execute gdb commands.
   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  		// Some gdb may set scheduling-locking as "step" by default. This prevents background tasks
   617  		// (e.g GC) from completing which may result in a hang when executing the step command.
   618  		// See #49852.
   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  	// Check that the backtrace matches the source code.
   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  	// Build the source code.
   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  	// Execute gdb commands.
   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  // TestGdbPanic tests that gdb can unwind the stack correctly
   727  // from SIGABRTs from Go panics.
   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  	// Build the source code.
   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  	// Execute gdb commands.
   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  	// Check that the backtrace matches the source code.
   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  // TestGdbInfCallstack tests that gdb can unwind the callstack of cgo programs
   800  // on arm64 platforms without endless frames of function 'crossfunc1'.
   801  // https://golang.org/issue/37238
   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  	// Build the source code.
   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  	// Execute gdb commands.
   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  		// 'runtime.setg' is hit on the newly created pthread inside threadentry.
   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  	// Check that the backtrace matches the 3 innermost frames on the new pthread.
   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