-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.go
64 lines (56 loc) · 1.38 KB
/
stack.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package errors
import (
"runtime"
"strings"
)
type StackTracer interface {
StackTrace() []StackFrame
}
var _ StackTracer = (*Error)(nil)
type StackFrame struct {
Message string
Frames []runtime.Frame
}
func newStackFrame(message string, callers []uintptr) StackFrame {
if len(callers) == 0 {
return StackFrame{
Message: message,
}
}
runtimeFrames := runtime.CallersFrames(callers)
frames := make([]runtime.Frame, 0, len(callers))
for frame, more := runtimeFrames.Next(); more; frame, more = runtimeFrames.Next() {
frames = append(frames, frame)
}
return StackFrame{
Message: message,
Frames: frames,
}
}
func cleanStackFrames(stackFrames []StackFrame) {
// Remove the same frames
for i := 1; i < len(stackFrames); i++ {
a, b := stackFrames[i-1], stackFrames[i]
jj := len(a.Frames) - 1
for j, k := len(a.Frames)-1, len(b.Frames)-1; j >= 0 && k >= 0; j, k = j-1, k-1 {
if a.Frames[j].PC != b.Frames[k].PC {
break
}
jj = j - 1
}
// If the frames are the same, remove the frames from the previous stack
if jj < 0 {
stackFrames[i-1].Frames = nil
} else {
stackFrames[i-1].Frames = a.Frames[:jj]
}
}
// Remove the runtime path
if C.runtimePath != "" {
for i := range stackFrames {
for j := range stackFrames[i].Frames {
stackFrames[i].Frames[j].File = strings.TrimPrefix(stackFrames[i].Frames[j].File, C.runtimePath)
}
}
}
}