-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
2324 lines (1985 loc) · 77.6 KB
/
Program.cs
File metadata and controls
2324 lines (1985 loc) · 77.6 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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// killall — Windows 11 Native Process Termination Utility
// .NET 8 / C# 12 — Single-file console application
// Production-grade implementation with three-tier safety model
using System.ComponentModel;
using System.Diagnostics;
using System.Management;
using System.Net;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
namespace Killall;
// ============================================================
// Enums and Records
// ============================================================
internal enum SafetyTier { Immortal, AutoRestart, Allowed }
internal enum KillAction { Kill, Skip, Restart }
internal sealed record ProcessInfo(
int Pid,
int ParentPid,
string Name,
string? CommandLine,
string? ExecutablePath);
internal sealed record KillRequest(
List<ProcessTarget> Targets,
bool KillTree,
bool Force,
bool DryRun,
string Reason);
internal sealed record ProcessTarget(
int Pid,
string Name,
SafetyTier Tier,
KillAction Action,
string? ExecutablePath,
string? CommandLine);
// ============================================================
// Native Methods (P/Invoke)
// ============================================================
internal static class NativeMethods
{
// ---- user32.dll ----
[DllImport("user32.dll", SetLastError = true)]
public static extern bool IsHungAppWindow(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(
IntPtr hWnd, uint Msg, UIntPtr wParam, IntPtr lParam,
uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern int GetWindowTextLength(IntPtr hWnd);
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
public const uint WM_NULL = 0x0000;
public const uint SMTO_ABORTIFHUNG = 0x0002;
// ---- iphlpapi.dll ----
[DllImport("iphlpapi.dll", SetLastError = true)]
public static extern uint GetExtendedTcpTable(
IntPtr pTcpTable, ref int pdwSize, bool bOrder,
int ulAf, TcpTableClass TableClass, uint Reserved);
[DllImport("iphlpapi.dll", SetLastError = true)]
public static extern uint GetExtendedUdpTable(
IntPtr pUdpTable, ref int pdwSize, bool bOrder,
int ulAf, UdpTableClass TableClass, uint Reserved);
public enum TcpTableClass
{
TCP_TABLE_OWNER_PID_ALL = 5
}
public enum UdpTableClass
{
UDP_TABLE_OWNER_PID = 1
}
public const int AF_INET = 2;
public const int AF_INET6 = 23;
public const uint NO_ERROR = 0;
public const uint ERROR_INSUFFICIENT_BUFFER = 122;
public enum TcpState
{
Closed = 1,
Listen = 2,
SynSent = 3,
SynRcvd = 4,
Established = 5,
FinWait1 = 6,
FinWait2 = 7,
CloseWait = 8,
Closing = 9,
LastAck = 10,
TimeWait = 11,
DeleteTcb = 12
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCPROW_OWNER_PID
{
public uint dwState;
public uint dwLocalAddr;
public uint dwLocalPort;
public uint dwRemoteAddr;
public uint dwRemotePort;
public uint dwOwningPid;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_UDPROW_OWNER_PID
{
public uint dwLocalAddr;
public uint dwLocalPort;
public uint dwOwningPid;
}
}
// ============================================================
// Console Output Helpers
// ============================================================
internal static class Output
{
public static void Success(string msg)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(msg);
Console.ResetColor();
}
public static void Warning(string msg)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(msg);
Console.ResetColor();
}
public static void Error(string msg)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(msg);
Console.ResetColor();
}
public static void Info(string msg)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(msg);
Console.ResetColor();
}
public static void Muted(string msg)
{
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine(msg);
Console.ResetColor();
}
public static void Table(string[] headers, List<string[]> rows)
{
if (rows.Count == 0) return;
var widths = new int[headers.Length];
for (int i = 0; i < headers.Length; i++)
widths[i] = headers[i].Length;
foreach (var row in rows)
for (int i = 0; i < Math.Min(row.Length, widths.Length); i++)
widths[i] = Math.Max(widths[i], (row[i] ?? "").Length);
// Header
Console.ForegroundColor = ConsoleColor.White;
for (int i = 0; i < headers.Length; i++)
Console.Write(headers[i].PadRight(widths[i] + 2));
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.DarkGray;
for (int i = 0; i < headers.Length; i++)
Console.Write(new string('─', widths[i]) + " ");
Console.WriteLine();
Console.ResetColor();
// Rows
foreach (var row in rows)
{
for (int i = 0; i < headers.Length; i++)
{
string val = i < row.Length ? (row[i] ?? "") : "";
Console.Write(val.PadRight(widths[i] + 2));
}
Console.WriteLine();
}
}
public static bool Confirm(string prompt)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write($"{prompt} [y/N] ");
Console.ResetColor();
var key = Console.ReadLine()?.Trim().ToLowerInvariant();
return key == "y" || key == "yes";
}
}
// ============================================================
// Safety Service — Three-Tier Protection
// ============================================================
internal static class SafetyService
{
private static readonly HashSet<string> ImmortalProcesses = new(StringComparer.OrdinalIgnoreCase)
{
"System", "Idle", "System Idle Process", "smss", "csrss", "wininit",
"services", "lsass", "winlogon", "svchost", "dwm", "fontdrvhost",
"lsaiso", "MsMpEng", "Registry", "Memory Compression", "MemCompression",
"conhost", "SecurityHealthService", "NtosKrnl", "Kernel32",
"WmiPrvSE", "spoolsv", "wlanext", "WUDFHost",
"Secure System", "ntoskrnl"
};
private static readonly HashSet<string> AutoRestartProcesses = new(StringComparer.OrdinalIgnoreCase)
{
"explorer", "ShellExperienceHost", "StartMenuExperienceHost",
"SearchHost", "SearchApp", "RuntimeBroker", "Taskmgr",
"ApplicationFrameHost", "Widgets", "WidgetService",
"TextInputHost", "SystemSettings"
};
public static SafetyTier Classify(string processName)
{
// Strip .exe suffix for matching
string name = processName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)
? processName[..^4]
: processName;
if (ImmortalProcesses.Contains(name))
return SafetyTier.Immortal;
if (AutoRestartProcesses.Contains(name))
return SafetyTier.AutoRestart;
return SafetyTier.Allowed;
}
public static KillAction GetAction(SafetyTier tier) => tier switch
{
SafetyTier.Immortal => KillAction.Skip,
SafetyTier.AutoRestart => KillAction.Restart,
_ => KillAction.Kill
};
public static async Task RelaunchProcess(ProcessTarget target)
{
string name = target.Name.ToLowerInvariant().Replace(".exe", "");
if (name == "explorer")
{
await RelaunchExplorer();
return;
}
// Many Tier 2 processes auto-restart via Windows infrastructure.
// Give Windows 3 seconds to restart them automatically.
await Task.Delay(3000);
// Verify if the process has restarted
var running = Process.GetProcessesByName(target.Name.Replace(".exe", ""));
if (running.Length > 0)
{
Output.Success($" [ RESTARTED ] {target.Name} (PID {running[0].Id}) — auto-restarted by Windows");
return;
}
// Attempt manual restart if we have the executable path
if (!string.IsNullOrEmpty(target.ExecutablePath) && File.Exists(target.ExecutablePath))
{
try
{
var psi = new ProcessStartInfo(target.ExecutablePath)
{
UseShellExecute = true,
WorkingDirectory = Path.GetDirectoryName(target.ExecutablePath) ?? ""
};
Process.Start(psi);
Output.Success($" [ RESTARTED ] {target.Name} — manually relaunched from {target.ExecutablePath}");
}
catch (Exception ex)
{
Output.Error($" [ FAILED ] Could not restart {target.Name}: {ex.Message}");
}
}
else
{
Output.Warning($" [ WARN ] {target.Name} did not auto-restart and no executable path is available.");
}
}
private static async Task RelaunchExplorer()
{
// Explorer requires special handling with retry logic
for (int attempt = 1; attempt <= 3; attempt++)
{
try
{
var psi = new ProcessStartInfo("explorer.exe")
{
UseShellExecute = true
};
Process.Start(psi);
await Task.Delay(2000);
var running = Process.GetProcessesByName("explorer");
if (running.Length > 0)
{
Output.Success($" [ RESTARTED ] explorer.exe (PID {running[0].Id}) — attempt {attempt}");
return;
}
}
catch (Exception ex)
{
Output.Warning($" Explorer restart attempt {attempt} failed: {ex.Message}");
}
if (attempt < 3)
{
Output.Muted($" Retrying explorer restart ({attempt + 1}/3)...");
await Task.Delay(2000);
}
}
Output.Error(" [ FAILED ] explorer.exe could not be restarted after 3 attempts.");
Output.Warning(" You may need to restart explorer manually: press Ctrl+Shift+Esc → File → Run → explorer.exe");
}
}
// ============================================================
// Process Tree Service
// ============================================================
internal static class ProcessTreeService
{
private static Dictionary<int, ProcessInfo>? _processMap;
private static Dictionary<int, List<int>>? _childMap;
public static void BuildProcessTree()
{
_processMap = new Dictionary<int, ProcessInfo>();
_childMap = new Dictionary<int, List<int>>();
try
{
using var searcher = new ManagementObjectSearcher(
"SELECT ProcessId, ParentProcessId, Name, CommandLine, ExecutablePath FROM Win32_Process");
foreach (ManagementObject obj in searcher.Get())
{
int pid = Convert.ToInt32(obj["ProcessId"]);
int ppid = Convert.ToInt32(obj["ParentProcessId"]);
string name = obj["Name"]?.ToString() ?? "";
string? cmdLine = obj["CommandLine"]?.ToString();
string? exePath = obj["ExecutablePath"]?.ToString();
_processMap[pid] = new ProcessInfo(pid, ppid, name, cmdLine, exePath);
if (!_childMap.ContainsKey(ppid))
_childMap[ppid] = [];
_childMap[ppid].Add(pid);
}
}
catch (Exception ex)
{
Output.Error($"Failed to build process tree via WMI: {ex.Message}");
}
}
public static List<int> GetDescendants(int pid)
{
if (_childMap is null) BuildProcessTree();
var descendants = new List<int>();
var queue = new Queue<int>();
queue.Enqueue(pid);
while (queue.Count > 0)
{
int current = queue.Dequeue();
if (_childMap!.TryGetValue(current, out var children))
{
foreach (int child in children)
{
descendants.Add(child);
queue.Enqueue(child);
}
}
}
return descendants;
}
public static ProcessInfo? GetProcessInfo(int pid)
{
if (_processMap is null) BuildProcessTree();
return _processMap!.GetValueOrDefault(pid);
}
public static string? GetExecutablePath(int pid)
{
return GetProcessInfo(pid)?.ExecutablePath;
}
public static string? GetCommandLine(int pid)
{
return GetProcessInfo(pid)?.CommandLine;
}
public static void InvalidateCache()
{
_processMap = null;
_childMap = null;
}
}
// ============================================================
// Pattern Matcher
// ============================================================
internal static class PatternMatcher
{
public static List<Process> FindMatching(string pattern)
{
var allProcesses = Process.GetProcesses();
var matched = new List<Process>();
// Determine match mode
if (pattern.StartsWith('/') && pattern.EndsWith('/') && pattern.Length > 2)
{
// Regex mode: /pattern/
string regexStr = pattern[1..^1];
var regex = new Regex(regexStr, RegexOptions.IgnoreCase | RegexOptions.Compiled);
foreach (var p in allProcesses)
{
if (regex.IsMatch(p.ProcessName))
matched.Add(p);
else
p.Dispose();
}
}
else if (pattern.Contains('*') || pattern.Contains('?'))
{
// Glob mode: convert to regex
string regexStr = "^" + Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".") + "$";
var regex = new Regex(regexStr, RegexOptions.IgnoreCase | RegexOptions.Compiled);
foreach (var p in allProcesses)
{
if (regex.IsMatch(p.ProcessName))
matched.Add(p);
else
p.Dispose();
}
}
else
{
// Try exact match first
foreach (var p in allProcesses)
{
if (string.Equals(p.ProcessName, pattern, StringComparison.OrdinalIgnoreCase))
matched.Add(p);
}
// If no exact match, fall back to substring/partial match
if (matched.Count == 0)
{
foreach (var p in allProcesses)
{
if (p.ProcessName.Contains(pattern, StringComparison.OrdinalIgnoreCase))
matched.Add(p);
else
p.Dispose();
}
}
else
{
// Dispose non-matched
foreach (var p in allProcesses)
{
if (!matched.Contains(p))
p.Dispose();
}
}
}
return matched;
}
public static bool IsMatch(string processName, string pattern)
{
if (pattern.StartsWith('/') && pattern.EndsWith('/') && pattern.Length > 2)
{
string regexStr = pattern[1..^1];
return Regex.IsMatch(processName, regexStr, RegexOptions.IgnoreCase);
}
if (pattern.Contains('*') || pattern.Contains('?'))
{
string regexStr = "^" + Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".") + "$";
return Regex.IsMatch(processName, regexStr, RegexOptions.IgnoreCase);
}
return string.Equals(processName, pattern, StringComparison.OrdinalIgnoreCase)
|| processName.Contains(pattern, StringComparison.OrdinalIgnoreCase);
}
}
// ============================================================
// Kill Command — Core Execution Engine
// ============================================================
internal static class KillCommand
{
public static async Task<int> Execute(KillRequest request)
{
if (request.Targets.Count == 0)
{
Output.Warning("No processes matched.");
return 3;
}
// Expand tree if requested
var allTargets = new List<ProcessTarget>(request.Targets);
if (request.KillTree)
{
ProcessTreeService.BuildProcessTree();
var expanded = new List<ProcessTarget>();
var seenPids = new HashSet<int>();
foreach (var target in request.Targets)
{
if (seenPids.Add(target.Pid))
expanded.Add(target);
var descendants = ProcessTreeService.GetDescendants(target.Pid);
foreach (int childPid in descendants)
{
if (!seenPids.Add(childPid)) continue;
try
{
var proc = Process.GetProcessById(childPid);
var tier = SafetyService.Classify(proc.ProcessName);
var info = ProcessTreeService.GetProcessInfo(childPid);
expanded.Add(new ProcessTarget(
childPid, proc.ProcessName, tier,
SafetyService.GetAction(tier),
info?.ExecutablePath, info?.CommandLine));
}
catch { /* process already exited */ }
}
}
allTargets = expanded;
}
// Display summary
Console.WriteLine();
Output.Info($" {request.Reason} — {allTargets.Count} process(es) targeted:");
Console.WriteLine();
var rows = new List<string[]>();
foreach (var t in allTargets)
{
string action = t.Action switch
{
KillAction.Skip => "SKIP (Immortal)",
KillAction.Restart => "KILL + RESTART",
KillAction.Kill => "KILL",
_ => "UNKNOWN"
};
rows.Add([t.Pid.ToString(), t.Name, t.Tier.ToString(), action]);
}
Output.Table(["PID", "Name", "Tier", "Action"], rows);
Console.WriteLine();
if (request.DryRun)
{
Output.Muted(" (Dry run — no processes were terminated)");
return 0;
}
// Confirm unless forced
if (!request.Force)
{
int killCount = allTargets.Count(t => t.Action != KillAction.Skip);
if (!Output.Confirm($"Terminate {killCount} process(es)?"))
{
Output.Muted(" Aborted.");
return 0;
}
}
// Sort: kill children first (higher PID tends to be child, but use tree order)
var toKill = allTargets.Where(t => t.Action != KillAction.Skip).ToList();
var toRestart = new List<ProcessTarget>();
int killed = 0;
int failed = 0;
int skipped = allTargets.Count(t => t.Action == KillAction.Skip);
// Log skipped
foreach (var t in allTargets.Where(t => t.Action == KillAction.Skip))
Output.Warning($" [ IMMORTAL ] Skipping {t.Name} (PID {t.Pid}) — protected system core");
// Kill in reverse order (children first when tree mode)
if (request.KillTree)
toKill.Reverse();
foreach (var target in toKill)
{
try
{
var proc = Process.GetProcessById(target.Pid);
proc.Kill(entireProcessTree: false);
await WaitForExitAsync(proc, 5000);
if (target.Action == KillAction.Restart)
{
Output.Success($" [ KILLED ] {target.Name} (PID {target.Pid}) — will restart");
toRestart.Add(target);
}
else
{
Output.Success($" [ KILLED ] {target.Name} (PID {target.Pid})");
}
killed++;
}
catch (ArgumentException)
{
Output.Muted($" [ GONE ] {target.Name} (PID {target.Pid}) — already exited");
killed++;
}
catch (Win32Exception ex)
{
Output.Error($" [ DENIED ] {target.Name} (PID {target.Pid}) — {ex.Message}");
failed++;
}
catch (InvalidOperationException)
{
Output.Muted($" [ GONE ] {target.Name} (PID {target.Pid}) — already exited");
killed++;
}
catch (Exception ex)
{
Output.Error($" [ ERROR ] {target.Name} (PID {target.Pid}) — {ex.Message}");
failed++;
}
}
// Restart Tier 2 processes
foreach (var target in toRestart)
{
await SafetyService.RelaunchProcess(target);
}
// Summary
Console.WriteLine();
Output.Info($" Summary: {killed} killed, {skipped} skipped (immortal), {failed} failed");
if (failed > 0 && killed == 0) return 2;
if (failed > 0) return 1;
return 0;
}
private static async Task WaitForExitAsync(Process proc, int timeoutMs)
{
try
{
using var cts = new CancellationTokenSource(timeoutMs);
await proc.WaitForExitAsync(cts.Token);
}
catch (OperationCanceledException) { }
catch (InvalidOperationException) { }
}
public static List<ProcessTarget> BuildTargets(List<Process> processes)
{
var targets = new List<ProcessTarget>();
ProcessTreeService.BuildProcessTree();
int selfPid = Environment.ProcessId;
foreach (var proc in processes.Where(p => p.Id != selfPid))
{
try
{
var tier = SafetyService.Classify(proc.ProcessName);
var info = ProcessTreeService.GetProcessInfo(proc.Id);
targets.Add(new ProcessTarget(
proc.Id, proc.ProcessName, tier,
SafetyService.GetAction(tier),
info?.ExecutablePath, info?.CommandLine));
}
catch { /* process exited */ }
}
return targets;
}
}
// ============================================================
// Argument Parser
// ============================================================
internal sealed class ArgParser
{
private readonly string[] _args;
public List<string> Positional { get; } = [];
private readonly Dictionary<string, string?> _flags = new(StringComparer.OrdinalIgnoreCase);
public ArgParser(string[] args)
{
_args = args;
Parse();
}
private void Parse()
{
for (int i = 0; i < _args.Length; i++)
{
string arg = _args[i];
if (arg.StartsWith("--") || (arg.StartsWith('-') && arg.Length == 2 && !char.IsDigit(arg[1])))
{
string key = arg.TrimStart('-').ToLowerInvariant();
// Check if next arg is a value (not another flag)
if (i + 1 < _args.Length && !_args[i + 1].StartsWith('-'))
{
_flags[key] = _args[i + 1];
i++;
}
else
{
_flags[key] = null;
}
}
else
{
Positional.Add(arg);
}
}
}
public bool HasFlag(params string[] names)
=> names.Any(n => _flags.ContainsKey(n.TrimStart('-').ToLowerInvariant()));
public string? GetValue(params string[] names)
{
foreach (var n in names)
{
string key = n.TrimStart('-').ToLowerInvariant();
if (_flags.TryGetValue(key, out var val))
return val;
}
return null;
}
public bool Force => HasFlag("force", "f");
public bool DryRun => HasFlag("dry-run", "n");
public bool Tree => HasFlag("tree", "t");
public bool Help => HasFlag("help", "h", "?");
public int GetInt(string name, int defaultValue)
{
var val = GetValue(name);
return val != null && int.TryParse(val, out int result) ? result : defaultValue;
}
public double GetDouble(string name, double defaultValue)
{
var val = GetValue(name);
return val != null && double.TryParse(val, out double result) ? result : defaultValue;
}
}
// ============================================================
// Subcommand: Restart
// ============================================================
internal static class RestartCommand
{
public static async Task<int> Run(string[] args)
{
var parser = new ArgParser(args);
if (parser.Help || parser.Positional.Count == 0)
{
Console.WriteLine("Usage: killall restart <process_name> [--force]");
Console.WriteLine("Forcefully kill and restart a process by name.");
return 0;
}
string pattern = parser.Positional[0];
var processes = PatternMatcher.FindMatching(pattern);
if (processes.Count == 0)
{
Output.Warning($"No processes matching '{pattern}' found.");
return 3;
}
// Capture exe paths before killing
ProcessTreeService.BuildProcessTree();
var restartInfos = new List<(string Name, string? ExePath, string? CmdLine)>();
foreach (var proc in processes)
{
var info = ProcessTreeService.GetProcessInfo(proc.Id);
restartInfos.Add((proc.ProcessName, info?.ExecutablePath, info?.CommandLine));
}
// Kill all instances
var targets = KillCommand.BuildTargets(processes);
var request = new KillRequest(targets, parser.Tree, parser.Force, parser.DryRun,
$"Restart '{pattern}'");
int result = await KillCommand.Execute(request);
if (parser.DryRun) return result;
// Wait for processes to fully exit
await Task.Delay(1000);
// Restart
Console.WriteLine();
Output.Info(" Restarting...");
foreach (var (name, exePath, cmdLine) in restartInfos)
{
if (string.IsNullOrEmpty(exePath) || !File.Exists(exePath))
{
Output.Warning($" Cannot restart {name}: executable path not available.");
continue;
}
try
{
var psi = new ProcessStartInfo(exePath)
{
UseShellExecute = true,
WorkingDirectory = Path.GetDirectoryName(exePath) ?? ""
};
var started = Process.Start(psi);
if (started != null)
Output.Success($" [ STARTED ] {name} (PID {started.Id}) from {exePath}");
}
catch (Exception ex)
{
Output.Error($" [ FAILED ] Could not restart {name}: {ex.Message}");
}
}
return result;
}
}
// ============================================================
// Subcommand: GPU
// ============================================================
internal static class GpuCommand
{
public static async Task<int> Run(string[] args)
{
var parser = new ArgParser(args);
if (parser.Help)
{
Console.WriteLine("Usage: killall gpu [--threshold <percent>] [--force] [--dry-run]");
Console.WriteLine("Terminate all user-level processes currently using the GPU.");
Console.WriteLine();
Console.WriteLine("Options:");
Console.WriteLine(" --threshold N Minimum GPU utilization % to target (default: 1)");
return 0;
}
double threshold = parser.GetDouble("threshold", 1.0);
Output.Info(" Scanning for GPU-using processes...");
var gpuPids = new Dictionary<int, double>();
// Method 1: WMI GPU Performance Counters (Windows 10 1809+)
try
{
using var searcher = new ManagementObjectSearcher(
"SELECT * FROM Win32_PerfFormattedData_GPUPerformanceCounters_GPUEngine");
foreach (ManagementObject obj in searcher.Get())
{
string? instanceName = obj["Name"]?.ToString();
if (instanceName is null) continue;
var match = Regex.Match(instanceName, @"pid_(\d+)_");
if (!match.Success) continue;
int pid = int.Parse(match.Groups[1].Value);
double utilization = Convert.ToDouble(obj["UtilizationPercentage"] ?? 0);
if (gpuPids.ContainsKey(pid))
gpuPids[pid] += utilization;
else
gpuPids[pid] = utilization;
}
}
catch
{
Output.Warning(" GPU performance counters not available. Falling back to module detection.");
}
// Method 2: Fallback — detect processes that loaded GPU-related DLLs
if (gpuPids.Count == 0)
{
gpuPids = DetectGpuByModules();
}
// Filter by threshold and exclude system processes
var selfPid = Environment.ProcessId;
var matchedProcesses = new List<Process>();
foreach (var (pid, util) in gpuPids)
{
if (pid == selfPid || pid == 0) continue;
if (util < threshold && gpuPids.Count > 0 && gpuPids.Values.Max() > 0) continue;
try
{
var proc = Process.GetProcessById(pid);
if (SafetyService.Classify(proc.ProcessName) != SafetyTier.Immortal)
matchedProcesses.Add(proc);
}
catch { /* process gone */ }
}
if (matchedProcesses.Count == 0)
{
Output.Warning(" No user-level GPU-using processes found above threshold.");
return 3;
}
// Show GPU usage table
Console.WriteLine();
var rows = new List<string[]>();
foreach (var proc in matchedProcesses)
{
double util = gpuPids.GetValueOrDefault(proc.Id);
rows.Add([proc.Id.ToString(), proc.ProcessName, $"{util:F1}%"]);
}
Output.Table(["PID", "Name", "GPU %"], rows);
var targets = KillCommand.BuildTargets(matchedProcesses);
return await KillCommand.Execute(new KillRequest(targets, parser.Tree, parser.Force, parser.DryRun,
"GPU-using processes"));
}
private static Dictionary<int, double> DetectGpuByModules()
{
var gpuDlls = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"d3d11.dll", "d3d12.dll", "d3d9.dll", "dxgi.dll",
"vulkan-1.dll", "nvapi64.dll", "amdxc64.dll",
"nvcuda.dll", "cudart64_*.dll", "opencl.dll",
"nvoglv64.dll", "atig6pxx.dll", "atiuxpag.dll"
};
var result = new Dictionary<int, double>();
int selfPid = Environment.ProcessId;
foreach (var proc in Process.GetProcesses())
{