stack.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. package errors
  2. import (
  3. "fmt"
  4. "io"
  5. "path"
  6. "runtime"
  7. "strconv"
  8. "strings"
  9. )
  10. // Frame represents a program counter inside a stack frame.
  11. // For historical reasons if Frame is interpreted as a uintptr
  12. // its value represents the program counter + 1.
  13. type Frame uintptr
  14. // pc returns the program counter for this frame;
  15. // multiple frames may have the same PC value.
  16. func (f Frame) pc() uintptr { return uintptr(f) - 1 }
  17. // file returns the full path to the file that contains the
  18. // function for this Frame's pc.
  19. func (f Frame) file() string {
  20. fn := runtime.FuncForPC(f.pc())
  21. if fn == nil {
  22. return "unknown"
  23. }
  24. file, _ := fn.FileLine(f.pc())
  25. return file
  26. }
  27. // line returns the line number of source code of the
  28. // function for this Frame's pc.
  29. func (f Frame) line() int {
  30. fn := runtime.FuncForPC(f.pc())
  31. if fn == nil {
  32. return 0
  33. }
  34. _, line := fn.FileLine(f.pc())
  35. return line
  36. }
  37. // name returns the name of this function, if known.
  38. func (f Frame) name() string {
  39. fn := runtime.FuncForPC(f.pc())
  40. if fn == nil {
  41. return "unknown"
  42. }
  43. return fn.Name()
  44. }
  45. // Format formats the frame according to the fmt.Formatter interface.
  46. //
  47. // %s source file
  48. // %d source line
  49. // %n function name
  50. // %v equivalent to %s:%d
  51. //
  52. // Format accepts flags that alter the printing of some verbs, as follows:
  53. //
  54. // %+s function name and path of source file relative to the compile time
  55. // GOPATH separated by \n\t (<funcname>\n\t<path>)
  56. // %+v equivalent to %+s:%d
  57. func (f Frame) Format(s fmt.State, verb rune) {
  58. switch verb {
  59. case 's':
  60. switch {
  61. case s.Flag('+'):
  62. io.WriteString(s, f.name())
  63. io.WriteString(s, "\n\t")
  64. io.WriteString(s, f.file())
  65. default:
  66. io.WriteString(s, path.Base(f.file()))
  67. }
  68. case 'd':
  69. io.WriteString(s, strconv.Itoa(f.line()))
  70. case 'n':
  71. io.WriteString(s, funcname(f.name()))
  72. case 'v':
  73. f.Format(s, 's')
  74. io.WriteString(s, ":")
  75. f.Format(s, 'd')
  76. }
  77. }
  78. // MarshalText formats a stacktrace Frame as a text string. The output is the
  79. // same as that of fmt.Sprintf("%+v", f), but without newlines or tabs.
  80. func (f Frame) MarshalText() ([]byte, error) {
  81. name := f.name()
  82. if name == "unknown" {
  83. return []byte(name), nil
  84. }
  85. return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil
  86. }
  87. // StackTrace is stack of Frames from innermost (newest) to outermost (oldest).
  88. type StackTrace []Frame
  89. // Format formats the stack of Frames according to the fmt.Formatter interface.
  90. //
  91. // %s lists source files for each Frame in the stack
  92. // %v lists the source file and line number for each Frame in the stack
  93. //
  94. // Format accepts flags that alter the printing of some verbs, as follows:
  95. //
  96. // %+v Prints filename, function, and line number for each Frame in the stack.
  97. func (st StackTrace) Format(s fmt.State, verb rune) {
  98. switch verb {
  99. case 'v':
  100. switch {
  101. case s.Flag('+'):
  102. for _, f := range st {
  103. io.WriteString(s, "\n")
  104. f.Format(s, verb)
  105. }
  106. case s.Flag('#'):
  107. fmt.Fprintf(s, "%#v", []Frame(st))
  108. default:
  109. st.formatSlice(s, verb)
  110. }
  111. case 's':
  112. st.formatSlice(s, verb)
  113. }
  114. }
  115. // formatSlice will format this StackTrace into the given buffer as a slice of
  116. // Frame, only valid when called with '%s' or '%v'.
  117. func (st StackTrace) formatSlice(s fmt.State, verb rune) {
  118. io.WriteString(s, "[")
  119. for i, f := range st {
  120. if i > 0 {
  121. io.WriteString(s, " ")
  122. }
  123. f.Format(s, verb)
  124. }
  125. io.WriteString(s, "]")
  126. }
  127. // stack represents a stack of program counters.
  128. type stack []uintptr
  129. func (s *stack) Format(st fmt.State, verb rune) {
  130. switch verb {
  131. case 'v':
  132. switch {
  133. case st.Flag('+'):
  134. for _, pc := range *s {
  135. f := Frame(pc)
  136. fmt.Fprintf(st, "\n%+v", f)
  137. }
  138. }
  139. }
  140. }
  141. func (s *stack) StackTrace() StackTrace {
  142. f := make([]Frame, len(*s))
  143. for i := 0; i < len(f); i++ {
  144. f[i] = Frame((*s)[i])
  145. }
  146. return f
  147. }
  148. func callers() *stack {
  149. const depth = 32
  150. var pcs [depth]uintptr
  151. n := runtime.Callers(3, pcs[:])
  152. var st stack = pcs[0:n]
  153. return &st
  154. }
  155. // funcname removes the path prefix component of a function's name reported by func.Name().
  156. func funcname(name string) string {
  157. i := strings.LastIndex(name, "/")
  158. name = name[i+1:]
  159. i = strings.Index(name, ".")
  160. return name[i+1:]
  161. }