stack.go 3.7 KB

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