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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include "bench_cmd.h"
#include <zencore/except.h>
#include <zencore/filesystem.h>
#include <zencore/fmtutils.h>
#include <zencore/logging.h>
#include <zencore/string.h>
#include <zencore/thread.h>
#include <zencore/timer.h>
#if ZEN_PLATFORM_WINDOWS
# include <stdio.h>
# include <tchar.h>
# include <windows.h>
# include <exception>
namespace zen::bench::util {
// See https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/set.htm
typedef DWORD NTSTATUS;
# define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
# define STATUS_PRIVILEGE_NOT_HELD ((NTSTATUS)0xC0000061L)
typedef enum _SYSTEM_INFORMATION_CLASS
{
SystemMemoryListInformation =
80, // 80, q: SYSTEM_MEMORY_LIST_INFORMATION; s: SYSTEM_MEMORY_LIST_COMMAND (requires SeProfileSingleProcessPrivilege)
} SYSTEM_INFORMATION_CLASS;
// private
typedef enum _SYSTEM_MEMORY_LIST_COMMAND
{
MemoryCaptureAccessedBits,
MemoryCaptureAndResetAccessedBits,
MemoryEmptyWorkingSets,
MemoryFlushModifiedList,
MemoryPurgeStandbyList,
MemoryPurgeLowPriorityStandbyList,
MemoryCommandMax
} SYSTEM_MEMORY_LIST_COMMAND;
BOOL
ObtainPrivilege(HANDLE TokenHandle, LPCSTR lpName, int flags)
{
LUID Luid;
TOKEN_PRIVILEGES CurrentPriv;
TOKEN_PRIVILEGES NewPriv;
DWORD dwBufferLength = 16;
if (LookupPrivilegeValueA(0, lpName, &Luid))
{
NewPriv.PrivilegeCount = 1;
NewPriv.Privileges[0].Luid = Luid;
NewPriv.Privileges[0].Attributes = 0;
if (AdjustTokenPrivileges(TokenHandle,
0,
&NewPriv,
DWORD((LPBYTE) & (NewPriv.Privileges[1]) - (LPBYTE)&NewPriv),
&CurrentPriv,
&dwBufferLength))
{
CurrentPriv.PrivilegeCount = 1;
CurrentPriv.Privileges[0].Luid = Luid;
CurrentPriv.Privileges[0].Attributes = flags != 0 ? 2 : 0;
return AdjustTokenPrivileges(TokenHandle, 0, &CurrentPriv, dwBufferLength, 0, 0);
}
}
return FALSE;
}
typedef NTSTATUS(WINAPI* NtSetSystemInformationFn)(INT, PVOID, ULONG);
typedef NTSTATUS(WINAPI* NtQuerySystemInformationFn)(INT, PVOID, ULONG, PULONG);
struct elevation_required_exception : public std::runtime_error
{
explicit elevation_required_exception(const std::string& What) : std::runtime_error{What} {}
};
void
EmptyStandByList()
{
HMODULE NtDll = LoadLibrary(L"ntdll.dll");
if (!NtDll)
{
zen::ThrowLastError("Could not LoadLibrary ntdll");
}
HANDLE hToken;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, &hToken))
{
zen::ThrowLastError("Could not open current process token");
}
if (!ObtainPrivilege(hToken, "SeProfileSingleProcessPrivilege", 1))
{
zen::ThrowLastError("Unable to obtain SeProfileSingleProcessPrivilege");
}
CloseHandle(hToken);
NtSetSystemInformationFn NtSetSystemInformation = (NtSetSystemInformationFn)GetProcAddress(NtDll, "NtSetSystemInformation");
NtQuerySystemInformationFn NtQuerySystemInformation = (NtQuerySystemInformationFn)GetProcAddress(NtDll, "NtQuerySystemInformation");
if (!NtSetSystemInformation || !NtQuerySystemInformation)
{
throw std::runtime_error("Failed to look up required ntdll functions");
}
SYSTEM_MEMORY_LIST_COMMAND MemoryListCommand = MemoryPurgeStandbyList;
NTSTATUS NtStatus = NtSetSystemInformation(SystemMemoryListInformation, &MemoryListCommand, sizeof(MemoryListCommand));
if (NtStatus == STATUS_PRIVILEGE_NOT_HELD)
{
throw elevation_required_exception("Insufficient privileges to execute the memory list command");
}
else if (!NT_SUCCESS(NtStatus))
{
throw std::runtime_error(fmt::format("Unable to execute the memory list command (status={})", NtStatus));
}
}
} // namespace zen::bench::util
#endif
BenchCommand::BenchCommand()
{
m_Options.add_options()("h,help", "Print help");
m_Options.add_options()("purge",
"Purge standby memory (system cache)",
cxxopts::value<bool>(m_PurgeStandbyLists)->default_value("false"));
m_Options.add_options()("single", "Do not spawn child processes", cxxopts::value<bool>(m_SingleProcess)->default_value("false"));
}
BenchCommand::~BenchCommand() = default;
int
BenchCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv)
{
ZEN_UNUSED(GlobalOptions);
if (!ParseOptions(argc, argv))
{
return 0;
}
#if ZEN_PLATFORM_WINDOWS
if (m_PurgeStandbyLists)
{
bool Ok = false;
zen::Stopwatch Timer;
try
{
zen::bench::util::EmptyStandByList();
Ok = true;
}
catch (zen::bench::util::elevation_required_exception&)
{
ZEN_CONSOLE("purging standby lists requires elevation. Will try launch as elevated process");
}
catch (std::exception& Ex)
{
ZEN_CONSOLE("ERROR: {}", Ex.what());
}
if (!Ok && !m_SingleProcess)
{
try
{
zen::CreateProcOptions Cpo;
Cpo.Flags = zen::CreateProcOptions::Flag_Elevated | zen::CreateProcOptions::Flag_NewConsole;
std::filesystem::path CurExe{zen::GetRunningExecutablePath()};
if (zen::CreateProcResult Cpr = zen::CreateProc(CurExe, fmt::format("bench --purge --single"), Cpo))
{
zen::ProcessHandle ProcHandle;
ProcHandle.Initialize(Cpr);
int ExitCode = ProcHandle.WaitExitCode();
if (ExitCode == 0)
{
Ok = true;
}
else
{
ZEN_CONSOLE("ERROR: Elevated child process failed with return code {}", ExitCode);
}
}
}
catch (std::exception& Ex)
{
ZEN_CONSOLE("ERROR: {}", Ex.what());
}
}
if (Ok)
{
// TODO: could also add reporting on just how much memory was purged
ZEN_CONSOLE("purged standby lists! (took {})", zen::NiceTimeSpanMs(Timer.GetElapsedTimeMs()));
}
}
#endif
return 0;
}
|