-
Notifications
You must be signed in to change notification settings - Fork 23
/
machinecode.go
54 lines (50 loc) · 1.08 KB
/
machinecode.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
package lib
import (
"encoding/hex"
"fmt"
"syscall"
"unsafe"
)
type MachineCode []uint8
func (m MachineCode) String() string {
h := hex.EncodeToString(m)
result := []rune{' ', ' '}
for i, c := range h {
result = append(result, c)
if i%2 == 1 && i+1 < len(h) {
result = append(result, ' ')
}
if i%16 == 15 && i+1 < len(h) {
result = append(result, '\n', ' ', ' ')
}
}
return string(result)
}
func (m MachineCode) Execute() uint {
mmapFunc, err := syscall.Mmap(
-1,
0,
len(m),
syscall.PROT_READ|syscall.PROT_WRITE|syscall.PROT_EXEC, syscall.MAP_PRIVATE|syscall.MAP_ANONYMOUS,
)
if err != nil {
fmt.Printf("mmap err: %v", err)
}
for i, b := range m {
mmapFunc[i] = b
}
type execFunc func() uint
unsafeFunc := (uintptr)(unsafe.Pointer(&mmapFunc))
f := *(*execFunc)(unsafe.Pointer(&unsafeFunc))
value := f()
fmt.Println("\nResult :", value)
fmt.Printf("Hex : %x\n", value)
fmt.Printf("Size : %d bytes\n\n", len(m))
return value
}
func (m MachineCode) Add(m2 MachineCode) MachineCode {
for _, code := range m2 {
m = append(m, code)
}
return m
}