forked from waskord/UnleashedRecomp_Android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreload_executable.cpp
More file actions
104 lines (91 loc) · 2.71 KB
/
Copy pathpreload_executable.cpp
File metadata and controls
104 lines (91 loc) · 2.71 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
#include "preload_executable.h"
#include <os/logger.h>
// Code from Zelda 64: Recompiled
// https://github.com/Zelda64Recomp/Zelda64Recomp/blob/91db87632c2bfb6995ef1554ec71b11977c621f8/src/main/main.cpp#L440-L514
PreloadContext::~PreloadContext()
{
#ifdef _WIN32
if (preloaded)
{
VirtualUnlock(view, size);
CloseHandle(mappingHandle);
CloseHandle(handle);
}
#endif
}
void PreloadContext::PreloadExecutable()
{
#ifdef _WIN32
wchar_t moduleName[MAX_PATH];
GetModuleFileNameW(NULL, moduleName, MAX_PATH);
handle = CreateFileW(moduleName, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (handle == INVALID_HANDLE_VALUE)
{
LOG_ERROR("Failed to load executable into memory!");
*this = {};
return;
}
LARGE_INTEGER moduleSize;
if (!GetFileSizeEx(handle, &moduleSize))
{
LOG_ERROR("Failed to get size of executable!");
CloseHandle(handle);
*this = {};
return;
}
size = moduleSize.QuadPart;
mappingHandle = CreateFileMappingW(handle, nullptr, PAGE_READONLY, 0, 0, nullptr);
if (mappingHandle == nullptr)
{
LOG_ERROR("Failed to create file mapping of executable!");
CloseHandle(handle);
*this = {};
return;
}
view = MapViewOfFile(mappingHandle, FILE_MAP_READ, 0, 0, 0);
if (view == nullptr)
{
LOG_ERROR("Failed to map view of of executable!");
CloseHandle(mappingHandle);
CloseHandle(handle);
*this = {};
return;
}
DWORD pid = GetCurrentProcessId();
HANDLE processHandle = OpenProcess(PROCESS_SET_QUOTA | PROCESS_QUERY_INFORMATION, FALSE, pid);
if (processHandle == nullptr)
{
LOG_ERROR("Failed to open own process!");
CloseHandle(mappingHandle);
CloseHandle(handle);
*this = {};
return;
}
SIZE_T minimumSetSize, maximumSetSize;
if (!GetProcessWorkingSetSize(processHandle, &minimumSetSize, &maximumSetSize))
{
LOG_ERROR("Failed to get working set size!");
CloseHandle(mappingHandle);
CloseHandle(handle);
*this = {};
return;
}
if (!SetProcessWorkingSetSize(processHandle, minimumSetSize + size, maximumSetSize + size))
{
LOG_ERROR("Failed to set working set size!");
CloseHandle(mappingHandle);
CloseHandle(handle);
*this = {};
return;
}
if (VirtualLock(view, size) == 0)
{
LOGF_ERROR("Failed to lock view of executable! (Error: 0x{:X})\n", GetLastError());
CloseHandle(mappingHandle);
CloseHandle(handle);
*this = {};
return;
}
preloaded = true;
#endif
}