stack.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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) StackTrace() StackTrace {
  94. f := make([]Frame, len(*s))
  95. for i := 0; i < len(f); i++ {
  96. f[i] = Frame((*s)[i])
  97. }
  98. return f
  99. }
  100. func callers() *stack {
  101. const depth = 32
  102. var pcs [depth]uintptr
  103. n := runtime.Callers(3, pcs[:])
  104. var st stack = pcs[0:n]
  105. return &st
  106. }
  107. // funcname removes the path prefix component of a function's name reported by func.Name().
  108. func funcname(name string) string {
  109. i := strings.LastIndex(name, "/")
  110. name = name[i+1:]
  111. i = strings.Index(name, ".")
  112. return name[i+1:]
  113. }
  114. func trimGOPATH(name, file string) string {
  115. // Here we want to get the source file path relative to the compile time
  116. // GOPATH. As of Go 1.6.x there is no direct way to know the compiled
  117. // GOPATH at runtime, but we can infer the number of path segments in the
  118. // GOPATH. We note that fn.Name() returns the function name qualified by
  119. // the import path, which does not include the GOPATH. Thus we can trim
  120. // segments from the beginning of the file path until the number of path
  121. // separators remaining is one more than the number of path separators in
  122. // the function name. For example, given:
  123. //
  124. // GOPATH /home/user
  125. // file /home/user/src/pkg/sub/file.go
  126. // fn.Name() pkg/sub.Type.Method
  127. //
  128. // We want to produce:
  129. //
  130. // pkg/sub/file.go
  131. //
  132. // From this we can easily see that fn.Name() has one less path separator
  133. // than our desired output. We count separators from the end of the file
  134. // path until it finds two more than in the function name and then move
  135. // one character forward to preserve the initial path segment without a
  136. // leading separator.
  137. const sep = "/"
  138. goal := strings.Count(name, sep) + 2
  139. i := len(file)
  140. for n := 0; n < goal; n++ {
  141. i = strings.LastIndex(file[:i], sep)
  142. if i == -1 {
  143. // not enough separators found, set i so that the slice expression
  144. // below leaves file unmodified
  145. i = -len(sep)
  146. break
  147. }
  148. }
  149. // get back to 0 or trim the leading separator
  150. file = file[i+len(sep):]
  151. return file
  152. }