-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathmonkey_amd64.go
127 lines (117 loc) · 2.13 KB
/
monkey_amd64.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
package monkey
import (
"runtime"
"strings"
"golang.org/x/arch/x86/x86asm"
)
// Assembles a jump to a function value
func jmpToFunctionValue(to uintptr) []byte {
return []byte{
0x49, 0xBD,
byte(to),
byte(to >> 8),
byte(to >> 16),
byte(to >> 24),
byte(to >> 32),
byte(to >> 40),
byte(to >> 48),
byte(to >> 56), // movabs r13,to
0x41, 0xFF, 0xE5, // jmp r13
}
}
func littleEndian(to uintptr) []byte {
return []byte{
byte(to),
byte(to >> 8),
byte(to >> 16),
byte(to >> 24),
byte(to >> 32),
byte(to >> 40),
byte(to >> 48),
byte(to >> 56),
}
}
// Assembles a jump to a function value
func jmpToGoFn(to uintptr) []byte {
return []byte{
0x48, 0xBA,
byte(to),
byte(to >> 8),
byte(to >> 16),
byte(to >> 24),
byte(to >> 32),
byte(to >> 40),
byte(to >> 48),
byte(to >> 56), // movabs rdx,to
0xFF, 0x22, // jmp QWORD PTR [rdx]
}
}
func jmpTable(g, to uintptr, gofn bool) []byte {
b := []byte{
// movq r13, g
0x49, 0xBD,
byte(g),
byte(g >> 8),
byte(g >> 16),
byte(g >> 24),
byte(g >> 32),
byte(g >> 40),
byte(g >> 48),
byte(g >> 56),
// cmp r12, r13
0x4D, 0x39, 0xEC,
// jne $+(2+12)
0x75, 0x0c,
}
if gofn {
b = append(b, jmpToGoFn(to)...)
} else {
b = append(b, jmpToFunctionValue(to)...)
}
return b
}
func alginPatch(from uintptr) (original []byte) {
f := rawMemoryAccess(from, 32)
s := 0
for {
i, err := x86asm.Decode(f[s:], 64)
if err != nil {
panic(err)
}
original = append(original, f[s:s+i.Len]...)
s += i.Len
if s >= 13 {
return
}
}
}
func getFirstCallFunc(from uintptr) uintptr {
f := rawMemoryAccess(from, 1024)
s := 0
for {
i, err := x86asm.Decode(f[s:], 64)
if err != nil {
panic(err)
}
if i.Op == x86asm.CALL {
arg := i.Args[0]
imm := arg.(x86asm.Rel)
next := from + uintptr(s+i.Len)
var to uintptr
if imm > 0 {
to = next + uintptr(imm)
} else {
to = next - uintptr(-imm)
}
f := runtime.FuncForPC(to)
// 泛型函数的名字中包含 [...]
if strings.Index(f.Name(), "[") > 0 {
return to
}
}
s += i.Len
if s >= 1024 {
panic("Can not find CALL instruction")
}
}
}