stack.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. package errors
  2. import (
  3. "fmt"
  4. "io"
  5. "path"
  6. "runtime"
  7. "strings"
  8. )
  9. // Frame represents a program counter inside a stack frame.
  10. type Frame uintptr
  11. // pc returns the program counter for this frame;
  12. // multiple frames may have the same PC value.
  13. func (f Frame) pc() uintptr { return uintptr(f) - 1 }
  14. // file returns the full path to the file that contains the
  15. // function for this Frame's pc.
  16. func (f Frame) file() string {
  17. fn := runtime.FuncForPC(f.pc())
  18. if fn == nil {
  19. return "unknown"
  20. }
  21. file, _ := fn.FileLine(f.pc())
  22. return file
  23. }
  24. // line returns the line number of source code of the
  25. // function for this Frame's pc.
  26. func (f Frame) line() int {
  27. fn := runtime.FuncForPC(f.pc())
  28. if fn == nil {
  29. return 0
  30. }
  31. _, line := fn.FileLine(f.pc())
  32. return line
  33. }
  34. // Format formats the frame according to the fmt.Formatter interface.
  35. //
  36. // %s source file
  37. // %d source line
  38. // %n function name
  39. // %v equivalent to %s:%d
  40. //
  41. // Format accepts flags that alter the printing of some verbs, as follows:
  42. //
  43. // %+s path of source file relative to the compile time GOPATH
  44. // %+v equivalent to %+s:%d
  45. func (f Frame) Format(s fmt.State, verb rune) {
  46. switch verb {
  47. case 's':
  48. switch {
  49. case s.Flag('+'):
  50. pc := f.pc()
  51. fn := runtime.FuncForPC(pc)
  52. if fn == nil {
  53. io.WriteString(s, "unknown")
  54. } else {
  55. file, _ := fn.FileLine(pc)
  56. fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file)
  57. }
  58. default:
  59. io.WriteString(s, path.Base(f.file()))
  60. }
  61. case 'd':
  62. fmt.Fprintf(s, "%d", f.line())
  63. case 'n':
  64. name := runtime.FuncForPC(f.pc()).Name()
  65. io.WriteString(s, funcname(name))
  66. case 'v':
  67. f.Format(s, 's')
  68. io.WriteString(s, ":")
  69. f.Format(s, 'd')
  70. }
  71. }
  72. // StackTrace is stack of Frames from innermost (newest) to outermost (oldest).
  73. type StackTrace []Frame
  74. func (st StackTrace) Format(s fmt.State, verb rune) {
  75. switch verb {
  76. case 'v':
  77. switch {
  78. case s.Flag('+'):
  79. for _, f := range st {
  80. fmt.Fprintf(s, "\n%+v", f)
  81. }
  82. case s.Flag('#'):
  83. fmt.Fprintf(s, "%#v", []Frame(st))
  84. default:
  85. fmt.Fprintf(s, "%v", []Frame(st))
  86. }
  87. case 's':
  88. fmt.Fprintf(s, "%s", []Frame(st))
  89. }
  90. }
  91. // stack represents a stack of program counters.
  92. type stack []uintptr
  93. func (s *stack) Format(st fmt.State, verb rune) {
  94. switch verb {
  95. case 'v':
  96. switch {
  97. case st.Flag('+'):
  98. for _, pc := range *s {
  99. f := Frame(pc)
  100. fmt.Fprintf(st, "\n%+v", f)
  101. }
  102. }
  103. }
  104. }
  105. func (s *stack) StackTrace() StackTrace {
  106. f := make([]Frame, len(*s))
  107. for i := 0; i < len(f); i++ {
  108. f[i] = Frame((*s)[i])
  109. }
  110. return f
  111. }
  112. func callers() *stack {
  113. const depth = 32
  114. var pcs [depth]uintptr
  115. n := runtime.Callers(3, pcs[:])
  116. var st stack = pcs[0:n]
  117. return &st
  118. }
  119. // funcname removes the path prefix component of a function's name reported by func.Name().
  120. func funcname(name string) string {
  121. i := strings.LastIndex(name, "/")
  122. name = name[i+1:]
  123. i = strings.Index(name, ".")
  124. return name[i+1:]
  125. }
  126. func trimGOPATH(name, file string) string {
  127. // Here we want to get the source file path relative to the compile time
  128. // GOPATH. As of Go 1.6.x there is no direct way to know the compiled
  129. // GOPATH at runtime, but we can infer the number of path segments in the
  130. // GOPATH. We note that fn.Name() returns the function name qualified by
  131. // the import path, which does not include the GOPATH. Thus we can trim
  132. // segments from the beginning of the file path until the number of path
  133. // separators remaining is one more than the number of path separators in
  134. // the function name. For example, given:
  135. //
  136. // GOPATH /home/user
  137. // file /home/user/src/pkg/sub/file.go
  138. // fn.Name() pkg/sub.Type.Method
  139. //
  140. // We want to produce:
  141. //
  142. // pkg/sub/file.go
  143. //
  144. // From this we can easily see that fn.Name() has one less path separator
  145. // than our desired output. We count separators from the end of the file
  146. // path until it finds two more than in the function name and then move
  147. // one character forward to preserve the initial path segment without a
  148. // leading separator.
  149. const sep = "/"
  150. goal := strings.Count(name, sep) + 2
  151. i := len(file)
  152. for n := 0; n < goal; n++ {
  153. i = strings.LastIndex(file[:i], sep)
  154. if i == -1 {
  155. // not enough separators found, set i so that the slice expression
  156. // below leaves file unmodified
  157. i = -len(sep)
  158. break
  159. }
  160. }
  161. // get back to 0 or trim the leading separator
  162. file = file[i+len(sep):]
  163. return file
  164. }