-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathallocmethod_windows.go
More file actions
108 lines (90 loc) · 1.96 KB
/
Copy pathallocmethod_windows.go
File metadata and controls
108 lines (90 loc) · 1.96 KB
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
//go:build windows
package runsc
import (
"golang.org/x/sys/windows"
"github.com/mjwhitta/errors"
w32 "github.com/mjwhitta/win/api"
)
// Consts for supported allocation methods.
const (
HeapAlloc AllocMethod = iota + 1
NtAllocateVirtualMemory
NtCreateSection
)
var allocMethods map[AllocMethod]aFunc = map[AllocMethod]aFunc{
HeapAlloc: allocHeap,
NtAllocateVirtualMemory: allocStack,
NtCreateSection: allocSection,
}
func allocHeap(s *state) (*state, error) {
var e error
if s.l.pid != 0 {
e = errors.New("cannot allocate via Heap in remote process")
return nil, e
}
s.heap, e = w32.HeapCreate(
w32.Winnt.HeapCreateEnableExecute,
0,
0, // Can grow as needed
)
if e != nil {
e = errors.Newf("failed to create memory: %w", e)
return nil, e
}
s.addr, e = w32.HeapAlloc(
s.heap,
w32.Winnt.HeapZeroMemory,
uintptr(s.sz),
)
if e != nil {
e = errors.Newf("failed to allocate memory: %w", e)
return nil, e
}
return s, nil
}
func allocSection(s *state) (*state, error) {
var e error
var rwx uintptr
rwx = w32.Winnt.SectionMapRead
rwx |= w32.Winnt.SectionMapWrite
rwx |= w32.Winnt.SectionMapExecute
// Get handle for section object
e = w32.NtCreateSection(
&s.section,
rwx,
s.sz,
w32.Winnt.PageExecuteReadwrite,
w32.Winnt.SecCommit,
)
if e != nil {
e = errors.Newf("failed to allocate memory: %w", e)
return nil, e
}
// Create RW view
s.addr, e = w32.NtMapViewOfSection(
s.section,
windows.CurrentProcess(),
s.sz,
w32.Accctrl.SubContainersOnlyInherit,
w32.Winnt.PageReadwrite,
)
if e != nil {
e = errors.Newf("failed to access memory as RW: %w", e)
return nil, e
}
return s, nil
}
func allocStack(s *state) (*state, error) {
var e error
s.addr, e = w32.NtAllocateVirtualMemory(
s.proc,
s.sz,
w32.Winnt.MemCommit|w32.Winnt.MemReserve,
w32.Winnt.PageExecuteReadwrite,
)
if e != nil {
e = errors.Newf("failed to allocate memory: %w", e)
return nil, e
}
return s, nil
}