Source file src/runtime/debug/stack_test.go

     1  // Copyright 2011 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 debug_test
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"internal/testenv"
    11  	"log"
    12  	"os"
    13  	"os/exec"
    14  	"path/filepath"
    15  	"runtime"
    16  	"runtime/debug"
    17  	. "runtime/debug"
    18  	"strings"
    19  	"testing"
    20  )
    21  
    22  func TestMain(m *testing.M) {
    23  	switch os.Getenv("GO_RUNTIME_DEBUG_TEST_ENTRYPOINT") {
    24  	case "dumpgoroot":
    25  		fmt.Println(runtime.GOROOT())
    26  		os.Exit(0)
    27  
    28  	case "setcrashoutput":
    29  		f, err := os.Create(os.Getenv("CRASHOUTPUT"))
    30  		if err != nil {
    31  			log.Fatal(err)
    32  		}
    33  		if err := SetCrashOutput(f, debug.CrashOptions{}); err != nil {
    34  			log.Fatal(err) // e.g. EMFILE
    35  		}
    36  		println("hello")
    37  		panic("oops")
    38  	}
    39  
    40  	// default: run the tests.
    41  	os.Exit(m.Run())
    42  }
    43  
    44  type T int
    45  
    46  func (t *T) ptrmethod() []byte {
    47  	return Stack()
    48  }
    49  func (t T) method() []byte {
    50  	return t.ptrmethod()
    51  }
    52  
    53  /*
    54  The traceback should look something like this, modulo line numbers and hex constants.
    55  Don't worry much about the base levels, but check the ones in our own package.
    56  
    57  	goroutine 10 [running]:
    58  	runtime/debug.Stack(0x0, 0x0, 0x0)
    59  		/Users/r/go/src/runtime/debug/stack.go:28 +0x80
    60  	runtime/debug.(*T).ptrmethod(0xc82005ee70, 0x0, 0x0, 0x0)
    61  		/Users/r/go/src/runtime/debug/stack_test.go:15 +0x29
    62  	runtime/debug.T.method(0x0, 0x0, 0x0, 0x0)
    63  		/Users/r/go/src/runtime/debug/stack_test.go:18 +0x32
    64  	runtime/debug.TestStack(0xc8201ce000)
    65  		/Users/r/go/src/runtime/debug/stack_test.go:37 +0x38
    66  	testing.tRunner(0xc8201ce000, 0x664b58)
    67  		/Users/r/go/src/testing/testing.go:456 +0x98
    68  	created by testing.RunTests
    69  		/Users/r/go/src/testing/testing.go:561 +0x86d
    70  */
    71  func TestStack(t *testing.T) {
    72  	b := T(0).method()
    73  	lines := strings.Split(string(b), "\n")
    74  	if len(lines) < 6 {
    75  		t.Fatal("too few lines")
    76  	}
    77  
    78  	// If built with -trimpath, file locations should start with package paths.
    79  	// Otherwise, file locations should start with a GOROOT/src prefix
    80  	// (for whatever value of GOROOT is baked into the binary, not the one
    81  	// that may be set in the environment).
    82  	fileGoroot := ""
    83  	if envGoroot := os.Getenv("GOROOT"); envGoroot != "" {
    84  		// Since GOROOT is set explicitly in the environment, we can't be certain
    85  		// that it is the same GOROOT value baked into the binary, and we can't
    86  		// change the value in-process because runtime.GOROOT uses the value from
    87  		// initial (not current) environment. Spawn a subprocess to determine the
    88  		// real baked-in GOROOT.
    89  		t.Logf("found GOROOT %q from environment; checking embedded GOROOT value", envGoroot)
    90  		cmd := exec.Command(testenv.Executable(t))
    91  		cmd.Env = append(os.Environ(), "GOROOT=", "GO_RUNTIME_DEBUG_TEST_ENTRYPOINT=dumpgoroot")
    92  		out, err := cmd.Output()
    93  		if err != nil {
    94  			t.Fatal(err)
    95  		}
    96  		fileGoroot = string(bytes.TrimSpace(out))
    97  	} else {
    98  		// Since GOROOT is not set in the environment, its value (if any) must come
    99  		// from the path embedded in the binary.
   100  		fileGoroot = runtime.GOROOT()
   101  	}
   102  	filePrefix := ""
   103  	if fileGoroot != "" {
   104  		filePrefix = filepath.ToSlash(fileGoroot) + "/src/"
   105  	}
   106  
   107  	n := 0
   108  	frame := func(file, code string) {
   109  		t.Helper()
   110  
   111  		line := lines[n]
   112  		if !strings.Contains(line, code) {
   113  			t.Errorf("expected %q in %q", code, line)
   114  		}
   115  		n++
   116  
   117  		line = lines[n]
   118  
   119  		wantPrefix := "\t" + filePrefix + file
   120  		if !strings.HasPrefix(line, wantPrefix) {
   121  			t.Errorf("in line %q, expected prefix %q", line, wantPrefix)
   122  		}
   123  		n++
   124  	}
   125  	n++
   126  
   127  	frame("runtime/debug/stack.go", "runtime/debug.Stack")
   128  	frame("runtime/debug/stack_test.go", "runtime/debug_test.(*T).ptrmethod")
   129  	frame("runtime/debug/stack_test.go", "runtime/debug_test.T.method")
   130  	frame("runtime/debug/stack_test.go", "runtime/debug_test.TestStack")
   131  	frame("testing/testing.go", "")
   132  }
   133  
   134  func TestSetCrashOutput(t *testing.T) {
   135  	crashOutput := filepath.Join(t.TempDir(), "crash.out")
   136  
   137  	cmd := exec.Command(testenv.Executable(t))
   138  	cmd.Stderr = new(strings.Builder)
   139  	cmd.Env = append(os.Environ(), "GO_RUNTIME_DEBUG_TEST_ENTRYPOINT=setcrashoutput", "CRASHOUTPUT="+crashOutput)
   140  	err := cmd.Run()
   141  	stderr := fmt.Sprint(cmd.Stderr)
   142  	if err == nil {
   143  		t.Fatalf("child process succeeded unexpectedly (stderr: %s)", stderr)
   144  	}
   145  	t.Logf("child process finished with error %v and stderr <<%s>>", err, stderr)
   146  
   147  	// Read the file the child process should have written.
   148  	// It should contain a crash report such as this:
   149  	//
   150  	// panic: oops
   151  	//
   152  	// goroutine 1 [running]:
   153  	// runtime/debug_test.TestMain(0x1400007e0a0)
   154  	// 	GOROOT/src/runtime/debug/stack_test.go:33 +0x18c
   155  	// main.main()
   156  	// 	_testmain.go:71 +0x170
   157  	data, err := os.ReadFile(crashOutput)
   158  	if err != nil {
   159  		t.Fatalf("child process failed to write crash report: %v", err)
   160  	}
   161  	crash := string(data)
   162  	t.Logf("crash = <<%s>>", crash)
   163  	t.Logf("stderr = <<%s>>", stderr)
   164  
   165  	// Check that the crash file and the stderr both contain the panic and stack trace.
   166  	for _, want := range []string{
   167  		"panic: oops",
   168  		"goroutine 1",
   169  		"debug_test.TestMain",
   170  	} {
   171  		if !strings.Contains(crash, want) {
   172  			t.Errorf("crash output does not contain %q", want)
   173  		}
   174  		if !strings.Contains(stderr, want) {
   175  			t.Errorf("stderr output does not contain %q", want)
   176  		}
   177  	}
   178  
   179  	// Check that stderr, but not crash, contains the output of println().
   180  	printlnOnly := "hello"
   181  	if strings.Contains(crash, printlnOnly) {
   182  		t.Errorf("crash output contains %q, but should not", printlnOnly)
   183  	}
   184  	if !strings.Contains(stderr, printlnOnly) {
   185  		t.Errorf("stderr output does not contain %q, but should", printlnOnly)
   186  	}
   187  }
   188  

View as plain text