-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkillall.cpp
More file actions
899 lines (840 loc) · 36.5 KB
/
killall.cpp
File metadata and controls
899 lines (840 loc) · 36.5 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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
/*
* killall.cpp — Windows Process Termination Tool
*/
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0600
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <tlhelp32.h>
#include <psapi.h>
#include <iphlpapi.h>
#include <wbemidl.h>
#include <objbase.h>
#include <comdef.h>
#include <shellapi.h>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <regex>
#include <set>
#include <string>
#include <vector>
#include <functional>
#include <sstream>
#include <cctype>
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "psapi.lib")
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "wbemuuid.lib")
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "oleaut32.lib")
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "shell32.lib")
// ─── ANSI colours (always on — we enable VT mode) ─────────────────────────
static void enableColour() {
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(h, &mode);
SetConsoleMode(h, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
// Also stderr
h = GetStdHandle(STD_ERROR_HANDLE);
GetConsoleMode(h, &mode);
SetConsoleMode(h, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
}
#define RED(s) "\x1b[31m" s "\x1b[0m"
#define GREEN(s) "\x1b[32m" s "\x1b[0m"
#define YELLOW(s) "\x1b[33m" s "\x1b[0m"
#define CYAN(s) "\x1b[36m" s "\x1b[0m"
#define BOLD(s) "\x1b[1m" s "\x1b[0m"
// ─── Utilities ─────────────────────────────────────────────────────────────
static std::string toLower(std::string s) {
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
return s;
}
static std::wstring toWide(const std::string& s) {
if (s.empty()) return {};
int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, nullptr, 0);
std::wstring w(n - 1, 0);
MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, &w[0], n);
return w;
}
static std::string toNarrow(const std::wstring& w) {
if (w.empty()) return {};
int n = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, nullptr, 0, nullptr, nullptr);
std::string s(n - 1, 0);
WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, &s[0], n, nullptr, nullptr);
return s;
}
// glob match: * = any sequence, ? = any char (case-insensitive)
static bool globMatch(const std::string& pat, const std::string& str) {
std::string p = toLower(pat), s = toLower(str);
size_t pi = 0, si = 0, star = std::string::npos, match = 0;
while (si < s.size()) {
if (pi < p.size() && (p[pi] == s[si] || p[pi] == '?')) { pi++; si++; }
else if (pi < p.size() && p[pi] == '*') { star = pi++; match = si; }
else if (star != std::string::npos) { pi = star + 1; si = ++match; }
else return false;
}
while (pi < p.size() && p[pi] == '*') pi++;
return pi == p.size();
}
// ─── Pattern object ────────────────────────────────────────────────────────
struct Pattern {
enum Type { SUBSTRING, GLOB, REGEX } type;
std::string raw;
std::regex re;
explicit Pattern(const std::string& pat) : raw(pat), type(SUBSTRING) {
if (pat.size() >= 2 && pat.front() == '/' && pat.back() == '/') {
type = REGEX;
std::string inner = pat.substr(1, pat.size() - 2);
try { re = std::regex(inner, std::regex::icase | std::regex::ECMAScript); }
catch (...) { type = SUBSTRING; }
} else if (pat.find('*') != std::string::npos ||
pat.find('?') != std::string::npos) {
type = GLOB;
}
}
bool match(const std::string& name) const {
switch (type) {
case SUBSTRING: return toLower(name).find(toLower(raw)) != std::string::npos;
case GLOB: return globMatch(raw, name);
case REGEX: return std::regex_search(name, re);
}
return false;
}
};
// ─── Process info struct ───────────────────────────────────────────────────
struct ProcInfo {
DWORD pid = 0;
DWORD ppid = 0;
std::string name;
std::string exePath;
SIZE_T workingSetBytes = 0;
double cpuPercent = 0.0;
};
// ─── Enumerate all processes ───────────────────────────────────────────────
static std::vector<ProcInfo> enumProcesses() {
std::vector<ProcInfo> procs;
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snap == INVALID_HANDLE_VALUE) return procs;
PROCESSENTRY32W pe; pe.dwSize = sizeof(pe);
if (Process32FirstW(snap, &pe)) {
do {
ProcInfo p;
p.pid = pe.th32ProcessID;
p.ppid = pe.th32ParentProcessID;
p.name = toLower(toNarrow(pe.szExeFile));
procs.push_back(p);
} while (Process32NextW(snap, &pe));
}
CloseHandle(snap);
return procs;
}
// get memory and exe path
static void enrichBasic(ProcInfo& p) {
HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, p.pid);
if (!h) h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, p.pid);
if (!h) return;
wchar_t buf[MAX_PATH * 2] = {};
DWORD sz = (DWORD)(sizeof(buf) / sizeof(wchar_t));
if (QueryFullProcessImageNameW(h, 0, buf, &sz)) p.exePath = toNarrow(buf);
PROCESS_MEMORY_COUNTERS pmc = {};
if (GetProcessMemoryInfo(h, &pmc, sizeof(pmc))) p.workingSetBytes = pmc.WorkingSetSize;
CloseHandle(h);
}
// ─── WMI command-line cache ────────────────────────────────────────────────
static std::map<DWORD, std::string> g_cmdlineCache;
static bool g_cmdlineCacheBuilt = false;
static void buildCmdlineCache() {
if (g_cmdlineCacheBuilt) return;
g_cmdlineCacheBuilt = true;
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
IWbemLocator* pLoc = nullptr;
if (FAILED(CoCreateInstance(CLSID_WbemLocator, nullptr, CLSCTX_INPROC_SERVER,
IID_IWbemLocator, (void**)&pLoc)) || !pLoc) return;
IWbemServices* pSvc = nullptr;
BSTR ns = SysAllocString(L"ROOT\\CIMV2");
pLoc->ConnectServer(ns, nullptr, nullptr, nullptr, 0, nullptr, nullptr, &pSvc);
SysFreeString(ns);
if (!pSvc) { pLoc->Release(); return; }
CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE,
nullptr, RPC_C_AUTHN_LEVEL_CALL,
RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_NONE);
IEnumWbemClassObject* pEnum = nullptr;
BSTR wql = SysAllocString(L"WQL");
BSTR query = SysAllocString(L"SELECT ProcessId, CommandLine FROM Win32_Process");
pSvc->ExecQuery(wql, query, WBEM_FLAG_FORWARD_ONLY, nullptr, &pEnum);
SysFreeString(wql); SysFreeString(query);
if (pEnum) {
IWbemClassObject* obj = nullptr; ULONG ret = 0;
while (pEnum->Next(WBEM_INFINITE, 1, &obj, &ret) == WBEM_S_NO_ERROR) {
VARIANT vPid, vCmd; VariantInit(&vPid); VariantInit(&vCmd);
obj->Get(L"ProcessId", 0, &vPid, nullptr, nullptr);
obj->Get(L"CommandLine", 0, &vCmd, nullptr, nullptr);
DWORD pid = (DWORD)V_UI4(&vPid);
if (vCmd.vt == VT_BSTR && vCmd.bstrVal)
g_cmdlineCache[pid] = toNarrow(vCmd.bstrVal);
VariantClear(&vPid); VariantClear(&vCmd);
obj->Release();
}
pEnum->Release();
}
pSvc->Release(); pLoc->Release();
}
static std::string getCmdline(DWORD pid) {
buildCmdlineCache();
auto it = g_cmdlineCache.find(pid);
return it != g_cmdlineCache.end() ? it->second : "";
}
// ─── Loaded modules ────────────────────────────────────────────────────────
static bool processHasModule(DWORD pid, const std::string& modPat) {
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid);
if (snap == INVALID_HANDLE_VALUE) return false;
MODULEENTRY32W me; me.dwSize = sizeof(me);
bool found = false;
if (Module32FirstW(snap, &me)) {
Pattern pat(modPat);
do {
std::string mn = toLower(toNarrow(me.szModule));
std::string mp = toLower(toNarrow(me.szExePath));
if (pat.match(mn) || pat.match(mp)) { found = true; break; }
} while (Module32NextW(snap, &me));
}
CloseHandle(snap);
return found;
}
// ─── Network / ports ──────────────────────────────────────────────────────
static bool processHasPort(DWORD pid, int portLo, int portHi) {
// TCP IPv4
DWORD sz = 0;
GetExtendedTcpTable(nullptr, &sz, FALSE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
std::vector<BYTE> buf(sz);
if (GetExtendedTcpTable(buf.data(), &sz, FALSE, AF_INET,
TCP_TABLE_OWNER_PID_ALL, 0) == NO_ERROR) {
auto* t = reinterpret_cast<MIB_TCPTABLE_OWNER_PID*>(buf.data());
for (DWORD i = 0; i < t->dwNumEntries; i++) {
if (t->table[i].dwOwningPid == pid) {
int lp = (int)ntohs((u_short)t->table[i].dwLocalPort);
int rp = (int)ntohs((u_short)t->table[i].dwRemotePort);
if ((lp >= portLo && lp <= portHi) || (rp >= portLo && rp <= portHi))
return true;
}
}
}
// TCP IPv6
sz = 0;
GetExtendedTcpTable(nullptr, &sz, FALSE, AF_INET6, TCP_TABLE_OWNER_PID_ALL, 0);
buf.resize(sz);
if (sz > 0 && GetExtendedTcpTable(buf.data(), &sz, FALSE, AF_INET6,
TCP_TABLE_OWNER_PID_ALL, 0) == NO_ERROR) {
auto* t = reinterpret_cast<MIB_TCP6TABLE_OWNER_PID*>(buf.data());
for (DWORD i = 0; i < t->dwNumEntries; i++) {
if (t->table[i].dwOwningPid == pid) {
int lp = (int)ntohs((u_short)t->table[i].dwLocalPort);
int rp = (int)ntohs((u_short)t->table[i].dwRemotePort);
if ((lp >= portLo && lp <= portHi) || (rp >= portLo && rp <= portHi))
return true;
}
}
}
// UDP IPv4
sz = 0;
GetExtendedUdpTable(nullptr, &sz, FALSE, AF_INET, UDP_TABLE_OWNER_PID, 0);
buf.resize(sz);
if (sz > 0 && GetExtendedUdpTable(buf.data(), &sz, FALSE, AF_INET,
UDP_TABLE_OWNER_PID, 0) == NO_ERROR) {
auto* t = reinterpret_cast<MIB_UDPTABLE_OWNER_PID*>(buf.data());
for (DWORD i = 0; i < t->dwNumEntries; i++) {
if (t->table[i].dwOwningPid == pid) {
int lp = (int)ntohs((u_short)t->table[i].dwLocalPort);
if (lp >= portLo && lp <= portHi) return true;
}
}
}
return false;
}
static bool processHasAnyNetwork(DWORD pid) { return processHasPort(pid, 1, 65535); }
// ─── Window title ──────────────────────────────────────────────────────────
struct WinEnumCtx { DWORD pid; std::string pat; bool found; };
static BOOL CALLBACK enumWinProc(HWND hwnd, LPARAM lp) {
auto* ctx = reinterpret_cast<WinEnumCtx*>(lp);
DWORD wpid = 0;
GetWindowThreadProcessId(hwnd, &wpid);
if (wpid == ctx->pid) {
wchar_t title[512] = {};
GetWindowTextW(hwnd, title, 511);
Pattern p(ctx->pat);
if (p.match(toNarrow(title))) { ctx->found = true; return FALSE; }
}
return TRUE;
}
static bool processHasWindow(DWORD pid, const std::string& pat) {
WinEnumCtx ctx = { pid, pat, false };
EnumWindows(enumWinProc, reinterpret_cast<LPARAM>(&ctx));
return ctx.found;
}
// ─── Hung detection ────────────────────────────────────────────────────────
struct HungCtx { DWORD pid; bool hung; };
static BOOL CALLBACK enumHungProc(HWND hwnd, LPARAM lp) {
auto* ctx = reinterpret_cast<HungCtx*>(lp);
DWORD wpid = 0;
GetWindowThreadProcessId(hwnd, &wpid);
if (wpid == ctx->pid && IsWindow(hwnd) && IsWindowVisible(hwnd)) {
if (SendMessageTimeout(hwnd, WM_NULL, 0, 0, SMTO_ABORTIFHUNG, 2000, nullptr) == 0) {
ctx->hung = true;
return FALSE;
}
}
return TRUE;
}
static bool isProcessHung(DWORD pid) {
HungCtx ctx = { pid, false };
EnumWindows(enumHungProc, reinterpret_cast<LPARAM>(&ctx));
return ctx.hung;
}
// ─── CPU usage (two-snapshot) ─────────────────────────────────────────────
static std::map<DWORD, double> measureCpuUsage(int sampleSecs,
const std::vector<ProcInfo>& allProcs) {
std::map<DWORD, ULONGLONG> t1;
for (auto& p : allProcs) {
HANDLE h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, p.pid);
if (!h) continue;
FILETIME ct, et, kt, ut;
if (GetProcessTimes(h, &ct, &et, &kt, &ut)) {
ULARGE_INTEGER k, u;
k.LowPart = kt.dwLowDateTime; k.HighPart = kt.dwHighDateTime;
u.LowPart = ut.dwLowDateTime; u.HighPart = ut.dwHighDateTime;
t1[p.pid] = k.QuadPart + u.QuadPart;
}
CloseHandle(h);
}
ULONGLONG wall1 = GetTickCount64();
printf(YELLOW(" Sampling CPU for %d second(s)...\n"), sampleSecs);
Sleep((DWORD)(sampleSecs * 1000));
ULONGLONG wall2 = GetTickCount64();
ULONGLONG wallDiff = (wall2 - wall1) * 10000ULL; // ms -> 100ns
SYSTEM_INFO si; GetSystemInfo(&si);
int cpuCount = (int)si.dwNumberOfProcessors;
std::map<DWORD, double> result;
for (auto& p : allProcs) {
if (t1.find(p.pid) == t1.end()) continue;
HANDLE h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, p.pid);
if (!h) continue;
FILETIME ct, et, kt, ut;
if (GetProcessTimes(h, &ct, &et, &kt, &ut)) {
ULARGE_INTEGER k, u;
k.LowPart = kt.dwLowDateTime; k.HighPart = kt.dwHighDateTime;
u.LowPart = ut.dwLowDateTime; u.HighPart = ut.dwHighDateTime;
ULONGLONG diff = (k.QuadPart + u.QuadPart) - t1[p.pid];
if (wallDiff > 0)
result[p.pid] = (double)diff / (double)wallDiff * 100.0;
}
CloseHandle(h);
}
return result;
}
// ─── GPU detection (module-based) ─────────────────────────────────────────
static bool processUsesGPU(DWORD pid) {
static const char* gpuMods[] = {
"d3d11.dll","d3d12.dll","d3d9.dll","dxgi.dll",
"nvoglv64.dll","nvoglv32.dll","ig4icd64.dll","atig6pxx.dll",
"vulkan-1.dll","opengl32.dll","nvcuda.dll","nvml.dll",
"atioglxx.dll","atigktxx.dll",nullptr
};
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid);
if (snap == INVALID_HANDLE_VALUE) return false;
MODULEENTRY32W me; me.dwSize = sizeof(me);
bool found = false;
if (Module32FirstW(snap, &me)) {
do {
std::string mn = toLower(toNarrow(me.szModule));
for (int i = 0; gpuMods[i]; i++)
if (mn == gpuMods[i]) { found = true; break; }
} while (!found && Module32NextW(snap, &me));
}
CloseHandle(snap);
return found;
}
// ─── LLM detection ────────────────────────────────────────────────────────
static const char* LLM_KEYWORDS[] = {
"ollama","llama","koboldcpp","textgen","lmstudio","lm studio",
"jan","gpt4all","oobabooga","open-webui","localai","vllm",
"xinference","fastchat","exllama","rwkv","whisper",
"lm_studio","anythingllm","msty","llamaedge","cortex",nullptr
};
// cmdline substrings that identify AI/image-gen python processes
static const char* AI_CMDLINE_KEYWORDS[] = {
// model files
".gguf", ".ggml", ".safetensors", ".ckpt",
// image gen launchers
"fooocus", "stable-diffusion", "stable_diffusion",
"webui.py", "launch.py", "comfyui", "comfy_ui",
"invokeai", "automatic1111", "sdnext", "vladmandic",
"kohya", "sd-scripts", "novelai", "naifu",
"deforum", "diffusers", "txt2img", "img2img",
// LLM launchers
"server.py", "llama_cpp", "llama-cpp",
"entry_with_update.py",
nullptr
};
static bool isLLMProcess(const ProcInfo& p) {
std::string n = toLower(p.name);
if (n.size() > 4 && n.substr(n.size()-4) == ".exe") n = n.substr(0,n.size()-4);
for (int i = 0; LLM_KEYWORDS[i]; i++)
if (n.find(LLM_KEYWORDS[i]) != std::string::npos) return true;
std::string cmd = toLower(getCmdline(p.pid));
if (cmd.empty()) return false;
for (int i = 0; AI_CMDLINE_KEYWORDS[i]; i++)
if (cmd.find(AI_CMDLINE_KEYWORDS[i]) != std::string::npos) return true;
return false;
}
// ─── Game detection ───────────────────────────────────────────────────────
static const char* GAME_MODS[] = {
"steam_api.dll","steam_api64.dll","unityplayer.dll",
"physxloader.dll","bink2w64.dll","easyanticheat.dll",
"nvngx_dlss.dll","battleye.dll",nullptr
};
static const char* GAME_NAMES[] = {
// launchers & stores
"steam","epicgameslauncher","upc","galaxyclient","blizzard",
"eadesktop","riotclientservices","playnite","parsec",
// Xbox / Microsoft Gaming
"xboxpcapp","xboxgamebar","xboxpctray","xboxappft",
"gamingservices","gamingservicesnet","xgpuenergy",
"gamingtcui","gamedvr",
// Minecraft (Store + Java)
"minecraft","minecraftlauncher","minecraftdungeons",
"javaw", // Minecraft Java Edition
"mcplaceholderstub",
nullptr
};
static bool isGameProcess(const ProcInfo& p) {
std::string n = toLower(p.name);
if (n.size() > 4 && n.substr(n.size()-4) == ".exe") n = n.substr(0,n.size()-4);
for (int i = 0; GAME_NAMES[i]; i++)
if (n.find(GAME_NAMES[i]) != std::string::npos) return true;
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, p.pid);
if (snap == INVALID_HANDLE_VALUE) return false;
MODULEENTRY32W me; me.dwSize = sizeof(me);
bool found = false;
if (Module32FirstW(snap, &me)) {
do {
std::string mn = toLower(toNarrow(me.szModule));
for (int i = 0; GAME_MODS[i]; i++)
if (mn == GAME_MODS[i]) { found = true; break; }
} while (!found && Module32NextW(snap, &me));
}
CloseHandle(snap);
return found;
}
// ─── Process tree ─────────────────────────────────────────────────────────
static std::set<DWORD> getProcessTree(DWORD rootPid,
const std::vector<ProcInfo>& all) {
std::set<DWORD> tree;
std::vector<DWORD> queue = { rootPid };
while (!queue.empty()) {
DWORD cur = queue.back(); queue.pop_back();
if (!tree.insert(cur).second) continue;
for (auto& p : all)
if (p.ppid == cur && p.pid != cur)
queue.push_back(p.pid);
}
return tree;
}
// ─── Kill a PID ───────────────────────────────────────────────────────────
static bool killPid(DWORD pid) {
if (pid == 0 || pid == 4) return false;
HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
if (!h) { fprintf(stderr, " " RED("Access denied") " PID %lu\n", (unsigned long)pid); return false; }
bool ok = TerminateProcess(h, 1) != 0;
CloseHandle(h);
return ok;
}
// ─── Resolve parent name/pid ───────────────────────────────────────────────
static DWORD resolveParentPid(const std::string& spec,
const std::vector<ProcInfo>& all) {
char* end = nullptr;
long n = strtol(spec.c_str(), &end, 10);
if (end && *end == '\0') return (DWORD)n;
std::string lo = toLower(spec);
for (auto& p : all)
if (p.name.find(lo) != std::string::npos) return p.pid;
return 0;
}
// ─── Args struct ──────────────────────────────────────────────────────────
struct Args {
std::string pattern;
std::string subcommand;
std::string subArg;
bool killTree = false;
bool force = false;
bool dryRun = false;
bool help = false;
std::string cmdlinePat;
std::string modulePat;
std::string portSpec;
std::string windowPat;
std::string parentSpec;
int top = 0;
int sampleSecs = 2;
int gpuThreshold = 0;
};
static void printHelp() {
printf(
BOLD("killall") " \xe2\x80\x94 Windows Process Termination Tool\n\n"
BOLD("USAGE\n")
" killall <pattern> [options]\n"
" killall <subcommand> [options]\n\n"
BOLD("PATTERN MATCHING\n")
" name Exact/substring match (case-insensitive)\n"
" part Substring match\n"
" note* Glob wildcard\n"
" /regex/ Regex match\n\n"
BOLD("OPTIONS\n")
" -t, --tree Kill process tree\n"
" -f, --force Skip confirmation\n"
" -n, --dry-run Show what would be killed\n"
" --cmdline <pat> Match command-line substring or /regex/\n"
" --module <dll> Match loaded module/DLL\n"
" --port <N|A-B> Match TCP/UDP port or range\n"
" --window <title> Match window title substring or /regex/\n"
" --parent <pid|name> Match children of a parent process\n"
" --top <N> Limit ramhog/cpuhog to top N offenders\n"
" --sample <N> CPU sampling interval (seconds)\n"
" -h, --help Show help\n\n"
BOLD("SUBCOMMANDS\n")
" hung Kill hung/frozen apps\n"
" networkapps Kill processes with network connections\n"
" ramhog <MB> Kill processes using >N MB RAM\n"
" cpuhog <percent> Kill processes using >N%% CPU\n"
" gpu [--threshold N] Kill GPU-using processes\n"
" llm Kill local AI/LLM processes\n"
" game Kill game processes and launchers\n"
" restart <name> Kill and restart a process\n\n"
BOLD("EXAMPLES\n")
" killall notepad\n"
" killall chrome --tree\n"
" killall --port 8080\n"
" killall --cmdline /server/\n"
" killall hung\n"
" killall ramhog 2048\n"
" killall cpuhog 90 --top 3\n"
);
}
// ─── Parse CLI args ────────────────────────────────────────────────────────
static const char* SUBCMDS[] = {
"hung","networkapps","ramhog","cpuhog","gpu","llm","game","restart",nullptr
};
static bool isSubcmd(const std::string& s) {
for (int i = 0; SUBCMDS[i]; i++)
if (s == SUBCMDS[i]) return true;
return false;
}
static Args parseArgs(int argc, char** argv) {
Args a;
std::vector<std::string> pos;
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if (arg=="-h"||arg=="--help") a.help = true;
else if (arg=="-t"||arg=="--tree") a.killTree = true;
else if (arg=="-f"||arg=="--force") a.force = true;
else if (arg=="-n"||arg=="--dry-run") a.dryRun = true;
else if ((arg=="--cmdline" )&&i+1<argc) a.cmdlinePat = argv[++i];
else if ((arg=="--module" )&&i+1<argc) a.modulePat = argv[++i];
else if ((arg=="--port" )&&i+1<argc) a.portSpec = argv[++i];
else if ((arg=="--window" )&&i+1<argc) a.windowPat = argv[++i];
else if ((arg=="--parent" )&&i+1<argc) a.parentSpec = argv[++i];
else if ((arg=="--top" )&&i+1<argc) a.top = atoi(argv[++i]);
else if ((arg=="--sample" )&&i+1<argc) a.sampleSecs = atoi(argv[++i]);
else if ((arg=="--threshold")&&i+1<argc) a.gpuThreshold=atoi(argv[++i]);
else if (arg[0] != '-') pos.push_back(arg);
}
if (!pos.empty()) {
if (isSubcmd(toLower(pos[0]))) {
a.subcommand = toLower(pos[0]);
if (pos.size() > 1) a.subArg = pos[1];
} else {
a.pattern = pos[0];
}
}
return a;
}
// ─── Confirm + execute kills ───────────────────────────────────────────────
static int doKill(std::vector<ProcInfo> targets, const Args& a,
const std::vector<ProcInfo>& allProcs) {
if (targets.empty()) {
printf(YELLOW(" No matching processes found.\n"));
return 0;
}
// Expand to process tree
std::set<DWORD> killSet;
if (a.killTree) {
for (auto& p : targets) {
auto tree = getProcessTree(p.pid, allProcs);
killSet.insert(tree.begin(), tree.end());
}
} else {
for (auto& p : targets) killSet.insert(p.pid);
}
// Collect enriched info — skip self
DWORD selfPid = GetCurrentProcessId();
bool skippedSelf = killSet.count(selfPid) > 0;
killSet.erase(selfPid);
std::vector<ProcInfo> finalList;
for (auto pid : killSet)
for (auto& p : allProcs)
if (p.pid == pid) { finalList.push_back(p); break; }
for (auto& p : finalList) enrichBasic(const_cast<ProcInfo&>(p));
if (skippedSelf)
printf(" " YELLOW("Skipped") " killall.exe (self)\n");
// Print list
printf(BOLD(" Processes to %s:\n"), a.dryRun ? "show (dry-run)" : "kill");
for (auto& p : finalList)
printf(" " CYAN("%-32s") " PID %-6lu RAM %.1f MB\n",
p.name.c_str(), (unsigned long)p.pid,
p.workingSetBytes / (1024.0 * 1024.0));
if (a.dryRun) return 0;
bool proceed = a.force;
if (!proceed) {
printf(BOLD(" Kill %zu process(es)? [y/N] "), finalList.size());
fflush(stdout);
int c = getchar();
proceed = (c == 'y' || c == 'Y');
}
if (!proceed) { printf(" Aborted.\n"); return 0; }
// Kill children before parents
std::sort(finalList.begin(), finalList.end(),
[](const ProcInfo& a, const ProcInfo& b){ return a.ppid > b.ppid; });
int killed = 0, failed = 0;
for (auto& p : finalList) {
if (killPid(p.pid)) {
printf(" " GREEN("Killed") " %-32s PID %lu\n",
p.name.c_str(), (unsigned long)p.pid);
killed++;
} else {
printf(" " RED("Failed") " %-32s PID %lu\n",
p.name.c_str(), (unsigned long)p.pid);
failed++;
}
}
printf(BOLD(" Done:") " %d killed, %d failed.\n", killed, failed);
return killed;
}
// ─── Filter processes for pattern mode ────────────────────────────────────
static std::vector<ProcInfo> filterProcs(const std::vector<ProcInfo>& all,
const Args& a) {
int portLo = 0, portHi = 0;
bool filterPort = !a.portSpec.empty();
if (filterPort) {
auto dash = a.portSpec.find('-');
if (dash != std::string::npos) {
portLo = atoi(a.portSpec.substr(0, dash).c_str());
portHi = atoi(a.portSpec.substr(dash+1).c_str());
} else { portLo = portHi = atoi(a.portSpec.c_str()); }
}
DWORD parentPid = 0;
if (!a.parentSpec.empty()) parentPid = resolveParentPid(a.parentSpec, all);
std::vector<ProcInfo> results;
for (auto& p : all) {
if (p.pid == 0 || p.pid == 4) continue;
if (!a.pattern.empty()) {
Pattern pat(a.pattern);
std::string noExt = p.name;
if (noExt.size() > 4 && noExt.substr(noExt.size()-4) == ".exe")
noExt = noExt.substr(0, noExt.size()-4);
if (!pat.match(p.name) && !pat.match(noExt)) continue;
}
if (!a.cmdlinePat.empty()) {
Pattern cpat(a.cmdlinePat);
if (!cpat.match(getCmdline(p.pid))) continue;
}
if (!a.modulePat.empty())
if (!processHasModule(p.pid, a.modulePat)) continue;
if (filterPort)
if (!processHasPort(p.pid, portLo, portHi)) continue;
if (!a.windowPat.empty())
if (!processHasWindow(p.pid, a.windowPat)) continue;
if (parentPid != 0)
if (p.ppid != parentPid) continue;
results.push_back(p);
}
return results;
}
// ─── Subcommands ──────────────────────────────────────────────────────────
static int cmdHung(const Args& a, const std::vector<ProcInfo>& all) {
printf(BOLD(" Checking for hung processes...\n"));
std::vector<ProcInfo> hung;
for (auto& p : all) {
if (p.pid == 0 || p.pid == 4) continue;
if (isProcessHung(p.pid)) hung.push_back(p);
}
printf(" Found %zu hung process(es).\n", hung.size());
return doKill(hung, a, all);
}
static int cmdNetworkApps(const Args& a, const std::vector<ProcInfo>& all) {
printf(BOLD(" Finding processes with network connections...\n"));
std::vector<ProcInfo> net;
for (auto& p : all) {
if (p.pid == 0 || p.pid == 4) continue;
if (processHasAnyNetwork(p.pid)) net.push_back(p);
}
printf(" Found %zu networked process(es).\n", net.size());
return doKill(net, a, all);
}
static int cmdRamHog(const Args& a, const std::vector<ProcInfo>& all) {
if (a.subArg.empty()) {
fprintf(stderr, RED(" Error:") " ramhog requires <MB> argument\n");
return 1;
}
size_t limitBytes = (size_t)_atoi64(a.subArg.c_str()) * 1024 * 1024;
printf(BOLD(" Finding processes using > %s MB RAM...\n"), a.subArg.c_str());
std::vector<ProcInfo> hogs;
for (auto p : all) {
if (p.pid == 0 || p.pid == 4) continue;
enrichBasic(p);
if (p.workingSetBytes > limitBytes) hogs.push_back(p);
}
std::sort(hogs.begin(), hogs.end(),
[](const ProcInfo& a, const ProcInfo& b){
return a.workingSetBytes > b.workingSetBytes; });
if (a.top > 0 && (int)hogs.size() > a.top) hogs.resize((size_t)a.top);
printf(" Found %zu ram-hog process(es).\n", hogs.size());
return doKill(hogs, a, all);
}
static int cmdCpuHog(const Args& a, const std::vector<ProcInfo>& all) {
if (a.subArg.empty()) {
fprintf(stderr, RED(" Error:") " cpuhog requires <percent> argument\n");
return 1;
}
double limit = atof(a.subArg.c_str());
int secs = a.sampleSecs > 0 ? a.sampleSecs : 2;
printf(BOLD(" Finding processes using > %.1f%% CPU...\n"), limit);
auto cpuMap = measureCpuUsage(secs, all);
std::vector<ProcInfo> hogs;
for (auto p : all) {
if (p.pid == 0 || p.pid == 4) continue;
auto it = cpuMap.find(p.pid);
if (it == cpuMap.end()) continue;
p.cpuPercent = it->second;
if (p.cpuPercent >= limit) hogs.push_back(p);
}
std::sort(hogs.begin(), hogs.end(),
[](const ProcInfo& a, const ProcInfo& b){
return a.cpuPercent > b.cpuPercent; });
if (a.top > 0 && (int)hogs.size() > a.top) hogs.resize((size_t)a.top);
printf(" Found %zu cpu-hog process(es).\n", hogs.size());
// Print with CPU column
printf(BOLD(" Processes to %s:\n"), a.dryRun ? "show (dry-run)" : "kill");
for (auto& p : hogs)
printf(" " CYAN("%-32s") " PID %-6lu CPU %.1f%%\n",
p.name.c_str(), (unsigned long)p.pid, p.cpuPercent);
if (a.dryRun) return 0;
bool proceed = a.force;
if (!proceed) {
printf(BOLD(" Kill %zu process(es)? [y/N] "), hogs.size());
fflush(stdout);
int c = getchar();
proceed = (c == 'y' || c == 'Y');
}
if (!proceed) { printf(" Aborted.\n"); return 0; }
int killed = 0;
for (auto& p : hogs) {
if (killPid(p.pid)) {
printf(" " GREEN("Killed") " %-32s PID %lu CPU %.1f%%\n",
p.name.c_str(), (unsigned long)p.pid, p.cpuPercent);
killed++;
}
}
return killed;
}
static int cmdGpu(const Args& a, const std::vector<ProcInfo>& all) {
printf(BOLD(" Finding GPU-using processes...\n"));
std::vector<ProcInfo> gpu;
for (auto& p : all) {
if (p.pid == 0 || p.pid == 4) continue;
if (processUsesGPU(p.pid)) gpu.push_back(p);
}
printf(" Found %zu GPU process(es).\n", gpu.size());
return doKill(gpu, a, all);
}
static int cmdLlm(const Args& a, const std::vector<ProcInfo>& all) {
printf(BOLD(" Finding local LLM/AI processes...\n"));
std::vector<ProcInfo> llms;
for (auto& p : all) {
if (p.pid == 0 || p.pid == 4) continue;
if (isLLMProcess(p)) llms.push_back(p);
}
printf(" Found %zu LLM process(es).\n", llms.size());
return doKill(llms, a, all);
}
static int cmdGame(const Args& a, const std::vector<ProcInfo>& all) {
printf(BOLD(" Finding game processes...\n"));
std::vector<ProcInfo> games;
for (auto& p : all) {
if (p.pid == 0 || p.pid == 4) continue;
if (isGameProcess(p)) games.push_back(p);
}
printf(" Found %zu game process(es).\n", games.size());
return doKill(games, a, all);
}
static int cmdRestart(const Args& a, const std::vector<ProcInfo>& all) {
if (a.subArg.empty()) {
fprintf(stderr, RED(" Error:") " restart requires <name>\n");
return 1;
}
std::string nameArg = toLower(a.subArg);
std::vector<ProcInfo> targets;
for (auto p : all) {
std::string n = p.name;
if (n.size() > 4 && n.substr(n.size()-4) == ".exe") n = n.substr(0,n.size()-4);
if (n.find(nameArg) != std::string::npos) {
enrichBasic(p);
targets.push_back(p);
}
}
if (targets.empty()) { printf(YELLOW(" No matching process found.\n")); return 0; }
std::string exePath = targets[0].exePath;
printf(BOLD(" Will restart: ") "%s\n", exePath.c_str());
Args ka = a; ka.force = true;
doKill(targets, ka, all);
Sleep(1200);
if (!exePath.empty()) {
HINSTANCE r = ShellExecuteA(nullptr, "open", exePath.c_str(),
nullptr, nullptr, SW_SHOWNORMAL);
if ((intptr_t)r > 32)
printf(GREEN(" Restarted") " %s\n", exePath.c_str());
else
fprintf(stderr, RED(" Failed to restart") " %s\n", exePath.c_str());
}
return 0;
}
// ─── Main ─────────────────────────────────────────────────────────────────
int main(int argc, char** argv) {
enableColour();
Args a = parseArgs(argc, argv);
if (a.help || argc == 1) { printHelp(); return 0; }
auto allProcs = enumProcesses();
if (!a.subcommand.empty()) {
if (a.subcommand == "hung") return cmdHung(a, allProcs);
else if (a.subcommand == "networkapps") return cmdNetworkApps(a, allProcs);
else if (a.subcommand == "ramhog") return cmdRamHog(a, allProcs);
else if (a.subcommand == "cpuhog") return cmdCpuHog(a, allProcs);
else if (a.subcommand == "gpu") return cmdGpu(a, allProcs);
else if (a.subcommand == "llm") return cmdLlm(a, allProcs);
else if (a.subcommand == "game") return cmdGame(a, allProcs);
else if (a.subcommand == "restart") return cmdRestart(a, allProcs);
}
bool hasFilter = !a.pattern.empty() || !a.cmdlinePat.empty() ||
!a.modulePat.empty()|| !a.portSpec.empty() ||
!a.windowPat.empty()|| !a.parentSpec.empty();
if (!hasFilter) {
fprintf(stderr, RED(" Error:") " no pattern or filter specified. Use -h for help.\n");
return 1;
}
auto targets = filterProcs(allProcs, a);
return doKill(targets, a, allProcs);
}