Debian Codegraph @

stack.go

raw symbols SCIP
1 package errors
2
3 import (
4 "bytes"
5 "fmt"
6 "io"
7 "path"
8 "runtime"
9 "strconv"
10 "strings"
11 )
12
13 // Frame represents a program counter inside a stack frame.
14 // For historical reasons if Frame is interpreted as a uintptr
15 // its value represents the program counter + 1.
16 type Frame uintptr
17
18 // pc returns the program counter for this frame;
19 // multiple frames may have the same PC value.
20 func (f Frame) pc() uintptr { return uintptr(f) - 1 }
21
22 // file returns the full path to the file that contains the
23 // function for this Frame's pc.
24 func (f Frame) file() string {
25 fn := runtime.FuncForPC(f.pc())
26 if fn == nil {
27 return "unknown"
28 }
29 file, _ := fn.FileLine(f.pc())
30 return file
31 }
32
33 // line returns the line number of source code of the
34 // function for this Frame's pc.
35 func (f Frame) line() int {
36 fn := runtime.FuncForPC(f.pc())
37 if fn == nil {
38 return 0
39 }
40 _, line := fn.FileLine(f.pc())
41 return line
42 }
43
44 // name returns the name of this function, if known.
45 func (f Frame) name() string {
46 fn := runtime.FuncForPC(f.pc())
47 if fn == nil {
48 return "unknown"
49 }
50 return fn.Name()
51 }
52
53 // Format formats the frame according to the fmt.Formatter interface.
54 //
55 // %s source file
56 // %d source line
57 // %n function name
58 // %v equivalent to %s:%d
59 //
60 // Format accepts flags that alter the printing of some verbs, as follows:
61 //
62 // %+s function name and path of source file relative to the compile time
63 // GOPATH separated by \n\t (<funcname>\n\t<path>)
64 // %+v equivalent to %+s:%d
65 func (f Frame) Format(s fmt.State, verb rune) {
66 switch verb {
67 case 's':
68 switch {
69 case s.Flag('+'):
70 io.WriteString(s, f.name())
71 io.WriteString(s, "\n\t")
72 io.WriteString(s, f.file())
73 default:
74 io.WriteString(s, path.Base(f.file()))
75 }
76 case 'd':
77 io.WriteString(s, strconv.Itoa(f.line()))
78 case 'n':
79 io.WriteString(s, funcname(f.name()))
80 case 'v':
81 f.Format(s, 's')
82 io.WriteString(s, ":")
83 f.Format(s, 'd')
84 }
85 }
86
87 // MarshalText formats a stacktrace Frame as a text string. The output is the
88 // same as that of fmt.Sprintf("%+v", f), but without newlines or tabs.
89 func (f Frame) MarshalText() ([]byte, error) {
90 name := f.name()
91 if name == "unknown" {
92 return []byte(name), nil
93 }
94 return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil
95 }
96
97 func (f Frame) MarshalJSON() ([]byte, error) {
98 name := f.name()
99 w := bytes.NewBuffer(nil)
100 if name == "unknown" {
101 w.WriteByte('"')
102 w.WriteString(name)
103 w.WriteByte('"')
104 return w.Bytes(), nil
105 }
106 w.WriteByte('{')
107 w.WriteString("\"function\": ")
108 w.WriteByte('"')
109 w.WriteString(funcname(name))
110 w.WriteByte('"')
111 w.WriteByte(',')
112 w.WriteString("\"file\": ")
113 w.WriteByte('"')
114 w.WriteString(f.file())
115 w.WriteByte('"')
116 w.WriteByte(',')
117 w.WriteString("\"line\": ")
118 w.WriteString(fmt.Sprintf("%d", f.line()))
119 w.WriteByte('}')
120 return w.Bytes(), nil
121 }
122
123 // StackTrace is stack of Frames from innermost (newest) to outermost (oldest).
124 type StackTrace []Frame
125
126 // Format formats the stack of Frames according to the fmt.Formatter interface.
127 //
128 // %s lists source files for each Frame in the stack
129 // %v lists the source file and line number for each Frame in the stack
130 //
131 // Format accepts flags that alter the printing of some verbs, as follows:
132 //
133 // %+v Prints filename, function, and line number for each Frame in the stack.
134 func (st StackTrace) Format(s fmt.State, verb rune) {
135 switch verb {
136 case 'v':
137 switch {
138 case s.Flag('+'):
139 for _, f := range st {
140 io.WriteString(s, "\n")
141 f.Format(s, verb)
142 }
143 case s.Flag('#'):
144 fmt.Fprintf(s, "%#v", []Frame(st))
145 default:
146 st.formatSlice(s, verb)
147 }
148 case 's':
149 st.formatSlice(s, verb)
150 }
151 }
152
153 func (st StackTrace) MarshalJSON() ([]byte, error) {
154 w := bytes.NewBuffer(nil)
155 w.WriteByte('[')
156 for i, f := range st {
157 b, _ := f.MarshalJSON()
158 w.Write(b)
159 if i == len(st)-1 {
160 break
161 }
162 w.WriteByte(',')
163 }
164 w.WriteByte(']')
165 return w.Bytes(), nil
166 }
167
168 // formatSlice will format this StackTrace into the given buffer as a slice of
169 // Frame, only valid when called with '%s' or '%v'.
170 func (st StackTrace) formatSlice(s fmt.State, verb rune) {
171 io.WriteString(s, "[")
172 for i, f := range st {
173 if i > 0 {
174 io.WriteString(s, " ")
175 }
176 f.Format(s, verb)
177 }
178 io.WriteString(s, "]")
179 }
180
181 // stack represents a stack of program counters.
182 type stack []uintptr
183
184 func (s *stack) Format(st fmt.State, verb rune) {
185 switch verb {
186 case 'v':
187 switch {
188 case st.Flag('+'):
189 for _, pc := range *s {
190 f := Frame(pc)
191 fmt.Fprintf(st, "\n%+v", f)
192 }
193 }
194 }
195 }
196
197 func (s *stack) StackTrace() StackTrace {
198 f := make([]Frame, len(*s))
199 for i := 0; i < len(f); i++ {
200 f[i] = Frame((*s)[i])
201 }
202 return f
203 }
204
205 func callers(skip int) *stack {
206 const depth = 32
207 var pcs [depth]uintptr
208 n := runtime.Callers(skip+3, pcs[:])
209 var st stack = pcs[0:n]
210 return &st
211 }
212
213 // funcname removes the path prefix component of a function's name reported by func.Name().
214 func funcname(name string) string {
215 i := strings.LastIndex(name, "/")
216 name = name[i+1:]
217 i = strings.Index(name, ".")
218 return name[i+1:]
219 }