-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSafeWrite.cpp
76 lines (62 loc) · 1.8 KB
/
SafeWrite.cpp
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
// stolen from SKSE
#include "SafeWrite.h"
#include <Windows.h>
void SafeWrite8(UInt32 addr, UInt32 data)
{
UInt32 oldProtect;
VirtualProtect((void *)addr, 4, PAGE_EXECUTE_READWRITE, &oldProtect);
*((UInt8 *)addr) = data;
VirtualProtect((void *)addr, 4, oldProtect, &oldProtect);
}
void SafeWrite16(UInt32 addr, UInt32 data)
{
UInt32 oldProtect;
VirtualProtect((void *)addr, 4, PAGE_EXECUTE_READWRITE, &oldProtect);
*((UInt16 *)addr) = data;
VirtualProtect((void *)addr, 4, oldProtect, &oldProtect);
}
void SafeWrite32(UInt32 addr, UInt32 data)
{
UInt32 oldProtect;
VirtualProtect((void *)addr, 4, PAGE_EXECUTE_READWRITE, &oldProtect);
*((UInt32 *)addr) = data;
VirtualProtect((void *)addr, 4, oldProtect, &oldProtect);
}
void SafeWriteBuf(UInt32 addr, void * data, UInt32 len)
{
UInt32 oldProtect;
VirtualProtect((void *)addr, len, PAGE_EXECUTE_READWRITE, &oldProtect);
memcpy((void *)addr, data, len);
VirtualProtect((void *)addr, len, oldProtect, &oldProtect);
}
void SafeWriteSet(UInt32 addr, byte data, UInt32 len)
{
UInt32 oldProtect;
VirtualProtect((void *)addr, len, PAGE_EXECUTE_READWRITE, &oldProtect);
memset((void*)addr, data, len);
VirtualProtect((void *)addr, len, oldProtect, &oldProtect);
}
void WriteRelJump(UInt32 jumpSrc, UInt32 jumpTgt)
{
// jmp rel32
SafeWrite8(jumpSrc, 0xE9);
SafeWrite32(jumpSrc + 1, jumpTgt - jumpSrc - 1 - 4);
}
void WriteRelCall(UInt32 jumpSrc, UInt32 jumpTgt)
{
// call rel32
SafeWrite8(jumpSrc, 0xE8);
SafeWrite32(jumpSrc + 1, jumpTgt - jumpSrc - 1 - 4);
}
void WriteRelJnz(UInt32 jumpSrc, UInt32 jumpTgt)
{
// jnz rel32
SafeWrite16(jumpSrc, 0x850F);
SafeWrite32(jumpSrc + 2, jumpTgt - jumpSrc - 2 - 4);
}
void WriteRelJle(UInt32 jumpSrc, UInt32 jumpTgt)
{
// jle rel32
SafeWrite16(jumpSrc, 0x8E0F);
SafeWrite32(jumpSrc + 2, jumpTgt - jumpSrc - 2 - 4);
}