-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRAMOptimizerV2.cpp
More file actions
328 lines (280 loc) · 11.8 KB
/
Copy pathRAMOptimizerV2.cpp
File metadata and controls
328 lines (280 loc) · 11.8 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
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
// RAMOptimizer.cpp v2.3
// Limpiador de RAM para Windows via NT APIs nativas
// NO requiere RAMMap ni EmptyStandbyList.exe externos
//
// Compilar con MSVC (Developer Command Prompt):
// cl /O2 /EHsc RAMOptimizerV2.cpp /link advapi32.lib psapi.lib
//
// Uso:
// RAMOptimizerV2.exe -> abre consola, ciclo cada 2h
// RAMOptimizerV2.exe -s -> modo silencioso SIN consola, ciclo cada 2h
// RAMOptimizerV2.exe -i 60 -> ciclo cada 60 minutos
// RAMOptimizerV2.exe -once -> ejecutar una sola limpieza y salir
// RAMOptimizerV2.exe -s -i 120 -> silencioso + cada 2h (para Tarea Programada)
#define _CRT_SECURE_NO_WARNINGS
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#include <winternl.h>
#include <tlhelp32.h>
#include <psapi.h>
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <thread>
#include <chrono>
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "psapi.lib")
#pragma comment(linker, "/SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup")
// ---------------------------------------------------------------------------
// NT API
// ---------------------------------------------------------------------------
typedef enum _SYSTEM_MEMORY_LIST_COMMAND {
MemoryPurgeStandbyList = 4,
MemoryFlushModifiedList = 5,
MemoryPurgeLowPriorityStandbyList = 8
} SYSTEM_MEMORY_LIST_COMMAND;
typedef NTSTATUS(WINAPI* PNtSetSystemInformation)(
ULONG SystemInformationClass,
PVOID SystemInformation,
ULONG SystemInformationLength
);
#define SystemMemoryListInformation 0x50
// ---------------------------------------------------------------------------
// Configuracion global
// ---------------------------------------------------------------------------
std::string LOG_PATH = "C:\\Scripts\\limpieza_ram.log";
int intervalMinutes = 120;
bool silentMode = false;
bool runOnce = false;
const ULONG NP_THRESHOLD_MB = 800;
// ---------------------------------------------------------------------------
// Gestion de consola inteligente
// Comportamiento:
// -s (silent) -> sin consola en absoluto (Tarea Programada)
// desde PowerShell -> adjunta a la consola existente
// doble clic manual -> abre consola nueva
// ---------------------------------------------------------------------------
void setupConsole() {
if (silentMode) return; // Tarea programada: sin consola
// Intentar adjuntarse a la consola del proceso padre (PowerShell/CMD)
if (AttachConsole(ATTACH_PARENT_PROCESS)) {
// Redirigir stdout/stderr a la consola existente
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
// Forzar un salto de linea inicial para no solapar con el prompt
std::cout << "\n";
}
else {
// No hay consola padre — ejecucion manual con doble clic
// Abrir una nueva ventana de consola
AllocConsole();
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
SetConsoleTitleA("RAMOptimizer v2.3");
}
}
// ---------------------------------------------------------------------------
// Logging con timestamp
// ---------------------------------------------------------------------------
void writeLog(const std::string& msg) {
time_t now = time(nullptr);
char ts[32];
struct tm timeinfo;
localtime_s(&timeinfo, &now);
strftime(ts, sizeof(ts), "%Y-%m-%d %H:%M:%S", &timeinfo);
std::ofstream f(LOG_PATH, std::ios::app);
if (f) f << "[" << ts << "] " << msg << "\n";
if (!silentMode)
std::cout << "[" << ts << "] " << msg << "\n";
}
// ---------------------------------------------------------------------------
// Elevar privilegios
// ---------------------------------------------------------------------------
bool enablePrivilege(LPCWSTR privName) {
HANDLE hToken = nullptr;
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
return false;
TOKEN_PRIVILEGES tp = {};
if (!LookupPrivilegeValueW(nullptr, privName, &tp.Privileges[0].Luid)) {
CloseHandle(hToken);
return false;
}
tp.PrivilegeCount = 1;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
BOOL ok = AdjustTokenPrivileges(hToken, FALSE, &tp, 0, nullptr, nullptr);
DWORD err = GetLastError();
CloseHandle(hToken);
return ok && (err == ERROR_SUCCESS);
}
// ---------------------------------------------------------------------------
// Leer NonPaged Pool actual en MB via GetPerformanceInfo (psapi)
// ---------------------------------------------------------------------------
ULONG getNonPagedPoolMB() {
PERFORMANCE_INFORMATION pi = {};
pi.cb = sizeof(pi);
if (!GetPerformanceInfo(&pi, sizeof(pi)))
return 0;
return static_cast<ULONG>(
(static_cast<ULONGLONG>(pi.KernelNonpaged) * pi.PageSize)
/ (1024ULL * 1024ULL)
);
}
// ---------------------------------------------------------------------------
// Operaciones NT sobre listas de memoria
// ---------------------------------------------------------------------------
bool purgeStandbyList(PNtSetSystemInformation fn) {
SYSTEM_MEMORY_LIST_COMMAND cmd = MemoryPurgeStandbyList;
return NT_SUCCESS(fn(SystemMemoryListInformation, &cmd, sizeof(cmd)));
}
bool flushModifiedList(PNtSetSystemInformation fn) {
SYSTEM_MEMORY_LIST_COMMAND cmd = MemoryFlushModifiedList;
return NT_SUCCESS(fn(SystemMemoryListInformation, &cmd, sizeof(cmd)));
}
bool purgeLowPriorityStandby(PNtSetSystemInformation fn) {
SYSTEM_MEMORY_LIST_COMMAND cmd = MemoryPurgeLowPriorityStandbyList;
return NT_SUCCESS(fn(SystemMemoryListInformation, &cmd, sizeof(cmd)));
}
bool trimSystemWorkingSet(PNtSetSystemInformation fn) {
SYSTEM_MEMORY_LIST_COMMAND cmd = static_cast<SYSTEM_MEMORY_LIST_COMMAND>(7);
return NT_SUCCESS(fn(SystemMemoryListInformation, &cmd, sizeof(cmd)));
}
// ---------------------------------------------------------------------------
// Trim Working Sets de todos los procesos de usuario
// ---------------------------------------------------------------------------
void trimWorkingSets() {
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snap == INVALID_HANDLE_VALUE) return;
PROCESSENTRY32W pe = {};
pe.dwSize = sizeof(pe);
SIZE_T totalFreed = 0;
int count = 0;
if (Process32FirstW(snap, &pe)) {
do {
HANDLE hProc = OpenProcess(
PROCESS_SET_QUOTA | PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ,
FALSE, pe.th32ProcessID);
if (hProc) {
PROCESS_MEMORY_COUNTERS pmc = {};
pmc.cb = sizeof(pmc);
SIZE_T wsBefore = 0;
if (GetProcessMemoryInfo(hProc, &pmc, sizeof(pmc)))
wsBefore = pmc.WorkingSetSize;
SetProcessWorkingSetSize(hProc, (SIZE_T)-1, (SIZE_T)-1);
if (GetProcessMemoryInfo(hProc, &pmc, sizeof(pmc))
&& wsBefore > pmc.WorkingSetSize)
totalFreed += (wsBefore - pmc.WorkingSetSize);
CloseHandle(hProc);
count++;
}
} while (Process32NextW(snap, &pe));
}
CloseHandle(snap);
writeLog("Working sets trimmed: " + std::to_string(count) +
" procesos | liberado: " +
std::to_string(totalFreed / (1024 * 1024)) + " MB");
}
// ---------------------------------------------------------------------------
// Ciclo de limpieza principal
// ---------------------------------------------------------------------------
void doClean(PNtSetSystemInformation NtSetSysInfo) {
writeLog("=== Iniciando limpieza de RAM ===");
ULONG npBefore = getNonPagedPoolMB();
writeLog("NonPaged Pool antes: " + std::to_string(npBefore) + " MB");
// 1. Trim working sets de procesos de usuario
trimWorkingSets();
Sleep(500);
// 2. System WS trim (kernel + drivers) — solo si supera el umbral
if (npBefore >= NP_THRESHOLD_MB) {
bool r = trimSystemWorkingSet(NtSetSysInfo);
writeLog(std::string("System WS trim (kernel/drivers): ") +
(r ? "OK" : "FALLO"));
Sleep(400);
}
else {
writeLog("System WS trim: omitido (NonPaged Pool OK, " +
std::to_string(npBefore) + " MB < " +
std::to_string(NP_THRESHOLD_MB) + " MB)");
}
// 3. Flush modified list
bool r1 = flushModifiedList(NtSetSysInfo);
writeLog(std::string("Modified Page List: ") + (r1 ? "OK" : "FALLO"));
Sleep(300);
// 4. Low priority standby
bool r2 = purgeLowPriorityStandby(NtSetSysInfo);
writeLog(std::string("Low Priority Standby: ") + (r2 ? "OK" : "FALLO"));
Sleep(300);
// 5. Standby list completa
bool r3 = purgeStandbyList(NtSetSysInfo);
writeLog(std::string("Standby List: ") + (r3 ? "OK" : "FALLO"));
Sleep(400);
ULONG npAfter = getNonPagedPoolMB();
writeLog("NonPaged Pool despues: " + std::to_string(npAfter) + " MB");
if (npBefore > npAfter)
writeLog("Reduccion NonPaged Pool: -" +
std::to_string(npBefore - npAfter) + " MB");
else
writeLog("NonPaged Pool sin cambio significativo");
writeLog("=== Limpieza completada ===");
}
// ---------------------------------------------------------------------------
// Parseo de argumentos
// IMPORTANTE: parsear ANTES de setupConsole() para detectar -s correctamente
// ---------------------------------------------------------------------------
void parseArgs(int argc, char* argv[]) {
for (int i = 1; i < argc; i++) {
std::string a = argv[i];
if (a == "-s" || a == "--silent") silentMode = true;
if (a == "-once" || a == "--once") runOnce = true;
if ((a == "-i" || a == "--interval") && i + 1 < argc) {
int val = std::atoi(argv[++i]);
intervalMinutes = val < 1 ? 1 : val;
}
if ((a == "-l" || a == "--log") && i + 1 < argc)
LOG_PATH = argv[++i];
}
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
int main(int argc, char* argv[]) {
// 1. Parsear args primero para detectar -s antes de setupConsole
parseArgs(argc, argv);
// 2. Configurar consola segun modo
setupConsole();
HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
if (!hNtdll) { writeLog("ERROR CRITICO: ntdll.dll no disponible"); return 1; }
auto NtSetSysInfo = reinterpret_cast<PNtSetSystemInformation>(
GetProcAddress(hNtdll, "NtSetSystemInformation"));
if (!NtSetSysInfo) {
writeLog("ERROR CRITICO: NtSetSystemInformation no encontrado en ntdll");
return 1;
}
bool p1 = enablePrivilege(SE_PROF_SINGLE_PROCESS_NAME);
bool p2 = enablePrivilege(SE_INC_BASE_PRIORITY_NAME);
bool p3 = enablePrivilege(L"SeDebugPrivilege");
if (!silentMode) {
std::cout << "RAMOptimizer v2.3\n";
std::cout << "Privilegios: SeProfileSingleProcess=" << (p1 ? "OK" : "NO")
<< " SeIncBasePriority=" << (p2 ? "OK" : "NO")
<< " SeDebug=" << (p3 ? "OK" : "NO") << "\n";
std::cout << "Intervalo: " << intervalMinutes
<< " min | Umbral NonPaged: " << NP_THRESHOLD_MB << " MB\n";
std::cout << "Log: " << LOG_PATH << "\n\n";
}
writeLog("RAMOptimizer v2.3 iniciado | intervalo: " +
std::to_string(intervalMinutes) + " min | silent=" +
(silentMode ? "si" : "no") + " | once=" + (runOnce ? "si" : "no"));
if (runOnce) {
doClean(NtSetSysInfo);
return 0;
}
while (true) {
doClean(NtSetSysInfo);
writeLog("Proxima limpieza en " + std::to_string(intervalMinutes) + " min");
std::this_thread::sleep_for(std::chrono::minutes(intervalMinutes));
}
return 0;
}