-
-
Notifications
You must be signed in to change notification settings - Fork 239
/
stacktrace.go
66 lines (51 loc) · 1.22 KB
/
stacktrace.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
65
66
package httpexpect
import (
"regexp"
"runtime"
)
// Stacktrace entry.
type StacktraceEntry struct {
Pc uintptr // Program counter
File string // File path
Line int // Line number
Func *runtime.Func // Function information
FuncName string // Function name (without package and parenthesis)
FuncPackage string // Function package
FuncOffset uintptr // Program counter offset relative to function start
// True if this is program entry point
// (like main.main or testing.tRunner)
IsEntrypoint bool
}
var stacktraceFuncRe = regexp.MustCompile(`^(.+/[^.]+)\.(.+)$`)
func stacktrace() []StacktraceEntry {
callers := []StacktraceEntry{}
for i := 1; ; i++ {
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
f := runtime.FuncForPC(pc)
if f == nil {
break
}
entry := StacktraceEntry{
Pc: pc,
File: file,
Line: line,
Func: f,
}
if m := stacktraceFuncRe.FindStringSubmatch(f.Name()); m != nil {
entry.FuncName = m[2]
entry.FuncPackage = m[1]
} else {
entry.FuncName = f.Name()
}
entry.FuncOffset = pc - f.Entry()
switch f.Name() {
case "main.main", "testing.tRunner":
entry.IsEntrypoint = true
}
callers = append(callers, entry)
}
return callers
}