Debian Codegraph @

stacktrace.go

raw
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4 // Some code from the runtime/debug package of the Go standard library.
5
6 package raven
7
8 import (
9 "bytes"
10 "go/build"
11 "io/ioutil"
12 "path/filepath"
13 "runtime"
14 "strings"
15 "sync"
16
17 "github.com/pkg/errors"
18 )
19
20 // https://docs.getsentry.com/hosted/clientdev/interfaces/#failure-interfaces
21 type Stacktrace struct {
22 // Required
23 Frames []*StacktraceFrame `json:"frames"`
24 }
25
26 func (s *Stacktrace) Class() string { return "stacktrace" }
27
28 func (s *Stacktrace) Culprit() string {
29 for i := len(s.Frames) - 1; i >= 0; i-- {
30 frame := s.Frames[i]
31 if frame.InApp == true && frame.Module != "" && frame.Function != "" {
32 return frame.Module + "." + frame.Function
33 }
34 }
35 return ""
36 }
37
38 type StacktraceFrame struct {
39 // At least one required
40 Filename string `json:"filename,omitempty"`
41 Function string `json:"function,omitempty"`
42 Module string `json:"module,omitempty"`
43
44 // Optional
45 Lineno int `json:"lineno,omitempty"`
46 Colno int `json:"colno,omitempty"`
47 AbsolutePath string `json:"abs_path,omitempty"`
48 ContextLine string `json:"context_line,omitempty"`
49 PreContext []string `json:"pre_context,omitempty"`
50 PostContext []string `json:"post_context,omitempty"`
51 InApp bool `json:"in_app"`
52 }
53
54 // Try to get stacktrace from err as an interface of github.com/pkg/errors, or else NewStacktrace()
55 func GetOrNewStacktrace(err error, skip int, context int, appPackagePrefixes []string) *Stacktrace {
56 stacktracer, errHasStacktrace := err.(interface {
57 StackTrace() errors.StackTrace
58 })
59 if errHasStacktrace {
60 var frames []*StacktraceFrame
61 for _, f := range stacktracer.StackTrace() {
62 pc := uintptr(f) - 1
63 fn := runtime.FuncForPC(pc)
64 var fName string
65 var file string
66 var line int
67 if fn != nil {
68 file, line = fn.FileLine(pc)
69 fName = fn.Name()
70 } else {
71 file = "unknown"
72 fName = "unknown"
73 }
74 frame := NewStacktraceFrame(pc, fName, file, line, context, appPackagePrefixes)
75 if frame != nil {
76 frames = append([]*StacktraceFrame{frame}, frames...)
77 }
78 }
79 return &Stacktrace{Frames: frames}
80 } else {
81 return NewStacktrace(skip+1, context, appPackagePrefixes)
82 }
83 }
84
85 // Intialize and populate a new stacktrace, skipping skip frames.
86 //
87 // context is the number of surrounding lines that should be included for context.
88 // Setting context to 3 would try to get seven lines. Setting context to -1 returns
89 // one line with no surrounding context, and 0 returns no context.
90 //
91 // appPackagePrefixes is a list of prefixes used to check whether a package should
92 // be considered "in app".
93 func NewStacktrace(skip int, context int, appPackagePrefixes []string) *Stacktrace {
94 var frames []*StacktraceFrame
95
96 callerPcs := make([]uintptr, 100)
97 numCallers := runtime.Callers(skip+2, callerPcs)
98
99 // If there are no callers, the entire stacktrace is nil
100 if numCallers == 0 {
101 return nil
102 }
103
104 callersFrames := runtime.CallersFrames(callerPcs)
105
106 for {
107 fr, more := callersFrames.Next()
108 if fr.Func != nil {
109 frame := NewStacktraceFrame(fr.PC, fr.Function, fr.File, fr.Line, context, appPackagePrefixes)
110 if frame != nil {
111 frames = append(frames, frame)
112 }
113 }
114 if !more {
115 break
116 }
117 }
118 // If there are no frames, the entire stacktrace is nil
119 if len(frames) == 0 {
120 return nil
121 }
122 // Optimize the path where there's only 1 frame
123 if len(frames) == 1 {
124 return &Stacktrace{frames}
125 }
126 // Sentry wants the frames with the oldest first, so reverse them
127 for i, j := 0, len(frames)-1; i < j; i, j = i+1, j-1 {
128 frames[i], frames[j] = frames[j], frames[i]
129 }
130 return &Stacktrace{frames}
131 }
132
133 // Build a single frame using data returned from runtime.Caller.
134 //
135 // context is the number of surrounding lines that should be included for context.
136 // Setting context to 3 would try to get seven lines. Setting context to -1 returns
137 // one line with no surrounding context, and 0 returns no context.
138 //
139 // appPackagePrefixes is a list of prefixes used to check whether a package should
140 // be considered "in app".
141 func NewStacktraceFrame(pc uintptr, fName, file string, line, context int, appPackagePrefixes []string) *StacktraceFrame {
142 frame := &StacktraceFrame{AbsolutePath: file, Filename: trimPath(file), Lineno: line, InApp: false}
143 frame.Module, frame.Function = functionName(fName)
144
145 // `runtime.goexit` is effectively a placeholder that comes from
146 // runtime/asm_amd64.s and is meaningless.
147 if frame.Module == "runtime" && frame.Function == "goexit" {
148 return nil
149 }
150
151 if frame.Module == "main" {
152 frame.InApp = true
153 } else {
154 for _, prefix := range appPackagePrefixes {
155 if strings.HasPrefix(frame.Module, prefix) && !strings.Contains(frame.Module, "vendor") && !strings.Contains(frame.Module, "third_party") {
156 frame.InApp = true
157 }
158 }
159 }
160
161 if context > 0 {
162 contextLines, lineIdx := sourceCodeLoader.Load(file, line, context)
163 if len(contextLines) > 0 {
164 for i, line := range contextLines {
165 switch {
166 case i < lineIdx:
167 frame.PreContext = append(frame.PreContext, string(line))
168 case i == lineIdx:
169 frame.ContextLine = string(line)
170 default:
171 frame.PostContext = append(frame.PostContext, string(line))
172 }
173 }
174 }
175 } else if context == -1 {
176 contextLine, _ := sourceCodeLoader.Load(file, line, 0)
177 if len(contextLine) > 0 {
178 frame.ContextLine = string(contextLine[0])
179 }
180 }
181 return frame
182 }
183
184 // Retrieve the name of the package and function containing the PC.
185 func functionName(fName string) (pack string, name string) {
186 name = fName
187 // We get this:
188 // runtime/debug.*T·ptrmethod
189 // and want this:
190 // pack = runtime/debug
191 // name = *T.ptrmethod
192 if idx := strings.LastIndex(name, "."); idx != -1 {
193 pack = name[:idx]
194 name = name[idx+1:]
195 }
196 name = strings.Replace(name, "·", ".", -1)
197 return
198 }
199
200 type SourceCodeLoader interface {
201 Load(filename string, line, context int) ([][]byte, int)
202 }
203
204 var sourceCodeLoader SourceCodeLoader = &fsLoader{cache: make(map[string][][]byte)}
205
206 func SetSourceCodeLoader(loader SourceCodeLoader) {
207 sourceCodeLoader = loader
208 }
209
210 type fsLoader struct {
211 mu sync.Mutex
212 cache map[string][][]byte
213 }
214
215 func (fs *fsLoader) Load(filename string, line, context int) ([][]byte, int) {
216 fs.mu.Lock()
217 defer fs.mu.Unlock()
218 lines, ok := fs.cache[filename]
219 if !ok {
220 data, err := ioutil.ReadFile(filename)
221 if err != nil {
222 // cache errors as nil slice: code below handles it correctly
223 // otherwise when missing the source or running as a different user, we try
224 // reading the file on each error which is unnecessary
225 fs.cache[filename] = nil
226 return nil, 0
227 }
228 lines = bytes.Split(data, []byte{'\n'})
229 fs.cache[filename] = lines
230 }
231
232 if lines == nil {
233 // cached error from ReadFile: return no lines
234 return nil, 0
235 }
236
237 line-- // stack trace lines are 1-indexed
238 start := line - context
239 var idx int
240 if start < 0 {
241 start = 0
242 idx = line
243 } else {
244 idx = context
245 }
246 end := line + context + 1
247 if line >= len(lines) {
248 return nil, 0
249 }
250 if end > len(lines) {
251 end = len(lines)
252 }
253 return lines[start:end], idx
254 }
255
256 var trimPaths []string
257
258 // Try to trim the GOROOT or GOPATH prefix off of a filename
259 func trimPath(filename string) string {
260 for _, prefix := range trimPaths {
261 if trimmed := strings.TrimPrefix(filename, prefix); len(trimmed) < len(filename) {
262 return trimmed
263 }
264 }
265 return filename
266 }
267
268 func init() {
269 // Collect all source directories, and make sure they
270 // end in a trailing "separator"
271 for _, prefix := range build.Default.SrcDirs() {
272 if prefix[len(prefix)-1] != filepath.Separator {
273 prefix += string(filepath.Separator)
274 }
275 trimPaths = append(trimPaths, prefix)
276 }
277 }