stack.go 3.8 KB

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