-
Notifications
You must be signed in to change notification settings - Fork 0
/
stacktrace.go
74 lines (63 loc) · 1.38 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
67
68
69
70
71
72
73
74
package log
import (
"fmt"
"runtime"
)
type frame uintptr
// pc returns the program counter for this frame;
// multiple frames may have the same PC value.
func (f frame) pc() uintptr { return uintptr(f) - 1 }
// file returns the full path to the file that contains the
// function for this frame's pc.
func (f frame) file() string {
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return "unknown"
}
file, _ := fn.FileLine(f.pc())
return file
}
// line returns the line number of source code of the
// function for this frame's pc.
func (f frame) line() int {
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return 0
}
_, line := fn.FileLine(f.pc())
return line
}
// name returns the name of this function if known.
func (f frame) name() string {
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return "unknown"
}
return fn.Name()
}
func (f frame) marshalText() string {
name := f.name()
if name == "unknown" {
return name
}
return fmt.Sprintf("%s %s:%d", name, f.file(), f.line())
}
type stackTrace []frame
func (s stackTrace) framesString() []string {
arr := make([]string, len(s))
for i, ss := range s {
arr[i] = ss.marshalText()
}
return arr
}
func callers() stackTrace {
const depth = 32
var pcs [depth]uintptr
n := runtime.Callers(3, pcs[:])
st := pcs[0:n]
f := make([]frame, len(st))
for i := 0; i < len(f); i++ {
f[i] = frame((st)[i])
}
return f
}