-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkcore.go
133 lines (120 loc) · 2.45 KB
/
kcore.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package main
import (
"debug/elf"
"fmt"
log "log/slog"
"os"
"sync"
"golang.org/x/arch/x86/x86asm"
)
const (
kcorePath string = "/proc/kcore"
)
var (
kcoreOnce sync.Once
kcore *Kcore
)
type Kcore struct {
path string
file *os.File
elf *elf.File
}
type Instruction struct {
Symbol string
Offset uint64
Call bool
CallTarget string
*LineInfo
}
func NewKcore() (*Kcore, error) {
file, err := os.Open(kcorePath)
if err != nil {
return nil, fmt.Errorf("failed to open kcore: %w", err)
}
elf, err := elf.NewFile(file)
if err != nil {
return nil, fmt.Errorf("failed to open kcore: %w", err)
}
return &Kcore{
path: kcorePath,
file: file,
elf: elf,
}, nil
}
func GetKcore() (_ *Kcore, err error) {
kcoreOnce.Do(func() {
kcore, err = NewKcore()
})
return kcore, err
}
func (k *Kcore) ParseInsns(symbol string) (insns map[uint64]*Instruction, err error) {
insns = make(map[uint64]*Instruction)
kdwarf, err := GetKdwarf()
if err != nil {
log.Debug("Failed to get kdwarf", "err", err)
}
ksym, err := KsymByName(symbol)
if err != nil {
return
}
addr := ksym.Addr
this, next := NearestKsym(addr)
leng := next.Addr - this.Addr
for _, prog := range k.elf.Progs {
if prog.Vaddr <= addr && prog.Vaddr+prog.Memsz >= addr {
bytes := make([]byte, leng)
if _, err = k.file.ReadAt(bytes, int64(prog.Off+addr-prog.Vaddr)); err != nil {
log.Debug("Failed to read kcore", "err", err)
continue
}
if len(bytes) == 0 {
continue
}
off := 0
for {
inst, err := x86asm.Decode(bytes, 64)
if err != nil {
inst = x86asm.Inst{Len: 1}
off += 1
} else {
insn := Instruction{
Symbol: symbol,
Offset: uint64(off),
}
if inst.Op == x86asm.CALL {
insn.Call = true
for _, arg := range inst.Args {
if arg == nil {
break
}
rel, ok := arg.(x86asm.Rel)
if !ok {
reg, ok := arg.(x86asm.Reg)
if ok {
insn.CallTarget = reg.String()
break
}
}
callee := addr + uint64(off) + uint64(rel) + uint64(inst.Len)
ksym, err := KsymByAddr(callee)
if err == nil {
insn.CallTarget = ksym.Name
}
break
}
}
if kdwarf != nil {
insn.LineInfo, _ = kdwarf.GetLineInfo(symbol, uint64(off))
}
insns[uint64(off)] = &insn
}
bytes = bytes[inst.Len:]
off += inst.Len
if len(bytes) == 0 {
break
}
}
}
}
return
}