github.com/keysonZZZ/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgDebug/stack.go (about)

     1  package kmgDebug
     2  
     3  import (
     4  	"fmt"
     5  	"runtime"
     6  )
     7  
     8  type StackFuncCall struct {
     9  	File     string
    10  	Line     int
    11  	Pc       uintptr
    12  	FuncName string
    13  }
    14  
    15  type Stack []StackFuncCall
    16  
    17  func (s *Stack) ToString() (output string) {
    18  	output = ""
    19  	for _, call := range *s {
    20  		output += fmt.Sprintf("%s\n\t%s:%d:%x\n", call.FuncName, call.File, call.Line, call.Pc)
    21  	}
    22  	return
    23  }
    24  
    25  func GetCurrentStack(skip int) (stack *Stack) {
    26  	pcs := make([]uintptr, 32)
    27  	thisLen := runtime.Callers(skip+2, pcs)
    28  	s := make(Stack, thisLen)
    29  	stack = &s
    30  	for i := 0; i < thisLen; i++ {
    31  		f := runtime.FuncForPC(pcs[i])
    32  		file, line := f.FileLine(pcs[i])
    33  		(*stack)[i] = StackFuncCall{
    34  			Pc:       pcs[i],
    35  			FuncName: f.Name(),
    36  			File:     file,
    37  			Line:     line - 1,
    38  		}
    39  	}
    40  	return
    41  }
    42  
    43  func GetAllStack() []byte {
    44  	buf := make([]byte, 32*1024)
    45  	runtime.Stack(buf, true)
    46  	return buf
    47  }