stack.go 4.1 KB

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