Repository navigation
Expand file tree
/
Copy pathGameInputTool.cs
More file actions
1473 lines (1317 loc) · 66.2 KB
/
Copy pathGameInputTool.cs
File metadata and controls
1473 lines (1317 loc) · 66.2 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
// ============================================================================
// GameInputTool - Microsoft GameInput 服务强制停用 / 删除工具
//
// 编译(无需 Visual Studio):
// C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe ^
// /target:exe /platform:anycpu /optimize+ /out:GameInputTool.exe ^
// /win32manifest:app.manifest ^
// /reference:System.dll /reference:System.Windows.Forms.dll /reference:System.Drawing.dll ^
// GameInputTool.cs GuiForm.cs
//
// 双击运行会自动弹出 UAC(manifest 声明 requireAdministrator)。
//
// 启动方式:
// 无参数 打开常驻日志窗口(推荐;窗口不会自动关闭)
// -Mode <模式> 命令行模式(传统用法,行为与以前一致)
//
// 模式:
// Audit 只检测不修改
// Soft 停用 + 摘除触发器(保留服务注册项,完全可逆)
// Full 服务层 + 删除 DLL
// Nuclear 全部清理(含 0 字节墓碑)
// Watch 监视 N 分钟,检验服务是否会复活
// ============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using Microsoft.Win32;
using System.Windows.Forms;
namespace GameInputTool
{
internal enum Status { Ok, Skip, Warn, Fail }
internal sealed class Result
{
public string Step, Target, Detail;
public Status Level;
}
internal static class Program
{
// ── 关键常量 ────────────────────────────────────────────────────
private const string SvcName = "GameInputSvc";
private const string SvcKeyPath = @"SYSTEM\CurrentControlSet\Services\" + SvcName;
private const string SessionMgrPath = @"SYSTEM\CurrentControlSet\Control\Session Manager";
private static readonly string[] TargetFiles =
{
@"C:\Windows\System32\GameInput.dll",
@"C:\Windows\System32\GameInputInbox.dll",
@"C:\Windows\SysWOW64\GameInput.dll",
};
// 服务主程序。两种形态必须动态归类:
// 非 0 字节 = 正常的服务二进制(WinSxS 硬链接投影)→ 步骤 4 删除
// 0 字节 = 被安全软件替换成的墓碑(属性含未文档化 0x80000)→ 步骤 5 清理
private const string SvcBinary = @"C:\Windows\System32\GameInputSvc.exe";
// 固定为 0 字节"墓碑"的残留路径:同名路径被替换成空文件,属主 BUILTIN\Administrators,
// 属性带未文档化的 0x80000,是安全软件(火绒)的文件保护产物。
// 这两个路径不是服务二进制,不存在"真实文件"形态。
private static readonly string[] Tombstones =
{
@"C:\Program Files\Microsoft GameInput",
@"C:\Program Files (x86)\Microsoft Gameinput",
};
private static readonly List<Result> Results = new List<Result>();
private static string _logFile;
private static string _mode = "Audit";
private static bool _includeTombstones, _includeWinSxS, _noBackup, _force;
private static int _watchMinutes = 5;
private static string _backupDir;
private static string _logDir;
// ── GUI 支持 ────────────────────────────────────────────────────
// _gui 为真时:输出同时镜像到窗口;确认改用对话框;不再阻塞等回车。
private static bool _gui;
private static GuiForm _form;
// 用户点“停止”后置位;长循环(Watch)会检查它并提前退出。
private static volatile bool _cancelRequested;
/// <summary>当前日志文件的完整路径(供 GUI 显示/打开)。</summary>
internal static string CurrentLogFile { get { return _logFile; } }
/// <summary>日志目录(供 GUI 打开文件夹)。</summary>
internal static string LogDir { get { return _logDir; } }
/// <summary>已登记的结果集合(供 GUI 汇总)。</summary>
internal static List<Result> AllResults { get { return Results; } }
/// <summary>请求停止当前操作。Watch 循环等长任务会尽快退出。</summary>
internal static void RequestCancel() { _cancelRequested = true; }
// ════════════════════════════════════════════════════════════════
// 输出通道
// 所有控制台输出都必须经这里,才能在 GUI 模式下同步进窗口。
// ════════════════════════════════════════════════════════════════
/// <summary>带颜色输出一行(GUI 模式下同时镜像到窗口)。</summary>
internal static void Out(string text, ConsoleColor color)
{
try
{
Console.ForegroundColor = color;
Console.WriteLine(text);
Console.ResetColor();
}
catch { /* 控制台不可用时(GUI 子系统)忽略 */ }
if (_gui && _form != null) _form.AppendText(text + Environment.NewLine, color);
}
/// <summary>无颜色输出一行。</summary>
private static void Out(string text) { Out(text, ConsoleColor.Gray); }
/// <summary>输出空行。</summary>
private static void Out() { Out("", ConsoleColor.Gray); }
// ════════════════════════════════════════════════════════════════
// P/Invoke - 服务控制
// ════════════════════════════════════════════════════════════════
[StructLayout(LayoutKind.Sequential)]
private struct SERVICE_STATUS
{
public uint dwServiceType, dwCurrentState, dwControlsAccepted,
dwWin32ExitCode, dwServiceSpecificExitCode,
dwCheckPoint, dwWaitHint;
}
[StructLayout(LayoutKind.Sequential)]
private struct SERVICE_STATUS_PROCESS
{
public uint dwServiceType, dwCurrentState, dwControlsAccepted,
dwWin32ExitCode, dwServiceSpecificExitCode,
dwCheckPoint, dwWaitHint, dwProcessId, dwServiceFlags;
}
private const uint SC_MANAGER_CONNECT = 0x0001;
private const uint SERVICE_QUERY_STATUS = 0x0004;
private const uint SERVICE_STOP = 0x0020;
private const uint SERVICE_CHANGE_CONFIG = 0x0002;
private const uint SERVICE_START = 0x0010;
private const uint SERVICE_CONTROL_STOP = 0x00000001;
private const uint SERVICE_DISABLED = 0x00000004;
private const int SC_STATUS_PROCESS_INFO = 0;
private const uint SERVICE_STOPPED = 0x0001;
private const uint SERVICE_START_PENDING = 0x0002;
private const uint SERVICE_STOP_PENDING = 0x0003;
private const uint SERVICE_RUNNING = 0x0004;
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr OpenSCManager(string machine, string database, uint access);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr OpenService(IntPtr hSCM, string name, uint access);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool QueryServiceStatus(IntPtr hSvc, ref SERVICE_STATUS st);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool QueryServiceStatusEx(IntPtr hSvc, int level,
ref SERVICE_STATUS_PROCESS buf, int cbBufSize, out int needed);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool ControlService(IntPtr hSvc, uint ctrl, ref SERVICE_STATUS st);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool DeleteService(IntPtr hSvc);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool ChangeServiceConfig(IntPtr hSvc, uint type, uint startType,
int errCtrl, string path, string loadOrderGroup, IntPtr tagId,
string dependencies, string account, string password, string displayName);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool StartService(IntPtr hSvc, int numArgs, IntPtr args);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool CloseServiceHandle(IntPtr h);
// ════════════════════════════════════════════════════════════════
// 日志 / 结果
// ════════════════════════════════════════════════════════════════
private static void WriteLog(string msg, Status? level = null)
{
ConsoleColor c = ConsoleColor.Gray;
string tag = "INFO";
if (level.HasValue)
{
switch (level.Value)
{
case Status.Ok: c = ConsoleColor.Green; tag = "OK "; break;
case Status.Skip: c = ConsoleColor.DarkGray; tag = "SKIP"; break;
case Status.Warn: c = ConsoleColor.Yellow; tag = "WARN"; break;
case Status.Fail: c = ConsoleColor.Red; tag = "FAIL"; break;
}
}
Out(string.Format("[{0}] [{1}] {2}", DateTime.Now.ToString("HH:mm:ss"), tag, msg), c);
if (_logFile != null)
{
try { File.AppendAllText(_logFile,
string.Format("[{0}] [{1}] {2}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), tag, msg),
Encoding.UTF8); }
catch { /* 日志失败不影响主流程 */ }
}
}
private static void AddResult(string step, string target, Status lvl, string detail)
{
Results.Add(new Result { Step = step, Target = target, Detail = detail, Level = lvl });
WriteLog(string.Format("{0} :: {1} :: {2}", step, target, detail), lvl);
}
// ════════════════════════════════════════════════════════════════
// 基础设施
// ════════════════════════════════════════════════════════════════
private static bool IsAdmin()
{
try
{
using (var id = WindowsIdentity.GetCurrent())
return new WindowsPrincipal(id).IsInRole(WindowsBuiltInRole.Administrator);
}
catch { return false; }
}
/// <summary>Existence test that treats a 0-byte file as existing.</summary>
private static bool Exists(string path)
{
if (File.Exists(path)) return true;
try { return (File.GetAttributes(path) & FileAttributes.Directory) == 0; }
catch { return false; }
}
private static string RunTool(string exe, string args, out int exitCode)
{
try
{
var psi = new ProcessStartInfo(exe, args)
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
};
using (var p = Process.Start(psi))
{
string o = p.StandardOutput.ReadToEnd() + p.StandardError.ReadToEnd();
p.WaitForExit(60000);
exitCode = p.ExitCode;
return o.Trim();
}
}
catch (Exception ex) { exitCode = -1; return ex.Message; }
}
private static string GetRegValueString(string subKey, string name)
{
try
{
using (var k = Registry.LocalMachine.OpenSubKey(subKey))
{
if (k == null) return null;
object v = k.GetValue(name);
return v == null ? null : v.ToString();
}
}
catch { return null; }
}
// ════════════════════════════════════════════════════════════════
// 服务状态
// ════════════════════════════════════════════════════════════════
private sealed class SvcInfo
{
public bool Registered;
public uint State; // SERVICE_*
public uint ProcessId;
public uint Win32Exit;
public int RegStart = -1; // Start 值
}
private static SvcInfo GetSvcInfo()
{
var info = new SvcInfo();
info.RegStart = ReadStartValue();
IntPtr scm = OpenSCManager(null, null, SC_MANAGER_CONNECT);
if (scm == IntPtr.Zero) return info;
try
{
IntPtr h = OpenService(scm, SvcName, SERVICE_QUERY_STATUS);
if (h == IntPtr.Zero) return info; // ERROR_SERVICE_DOES_NOT_EXIST
try
{
info.Registered = true;
var ssp = new SERVICE_STATUS_PROCESS();
int needed;
if (QueryServiceStatusEx(h, SC_STATUS_PROCESS_INFO, ref ssp,
Marshal.SizeOf(typeof(SERVICE_STATUS_PROCESS)), out needed))
{
info.State = ssp.dwCurrentState;
info.ProcessId = ssp.dwProcessId;
info.Win32Exit = ssp.dwWin32ExitCode;
}
}
finally { CloseServiceHandle(h); }
}
finally { CloseServiceHandle(scm); }
return info;
}
private static int ReadStartValue()
{
try
{
using (var k = Registry.LocalMachine.OpenSubKey(SvcKeyPath))
{
if (k == null) return -1;
object v = k.GetValue("Start");
return v == null ? -1 : Convert.ToInt32(v);
}
}
catch { return -1; }
}
private static string StateName(uint s)
{
switch (s)
{
case SERVICE_STOPPED: return "Stopped";
case SERVICE_START_PENDING: return "StartPending";
case SERVICE_STOP_PENDING: return "StopPending";
case SERVICE_RUNNING: return "Running";
default: return "0x" + s.ToString("X");
}
}
private static string StartTypeName(int v)
{
switch (v)
{
case 0: return "Boot";
case 1: return "System";
case 2: return "Automatic";
case 3: return "Manual";
case 4: return "Disabled";
default: return v < 0 ? "(无注册项)" : "?" + v;
}
}
// ════════════════════════════════════════════════════════════════
// 步骤 1:摘除自动拉起机制
// ════════════════════════════════════════════════════════════════
private static void DisableTriggers()
{
WriteLog("── 步骤 1:摘除自动拉起机制 ──");
if (Registry.LocalMachine.OpenSubKey(SvcKeyPath) == null)
{
AddResult("1-SvcKey", SvcKeyPath, Status.Skip, "服务注册项不存在");
return;
}
// FailureActions:失败后 60 秒自动重启
try
{
using (var k = Registry.LocalMachine.OpenSubKey(SvcKeyPath, true))
{
if (k.GetValue("FailureActions") != null)
{
k.DeleteValue("FailureActions", false);
AddResult("1-FailureActions", "FailureActions", Status.Ok, "已移除失败自动重启");
}
else
{
AddResult("1-FailureActions", "FailureActions", Status.Skip, "无此值");
}
if (k.GetValue("DelayedAutostart") != null)
{
k.DeleteValue("DelayedAutostart", false);
AddResult("1-DelayedAutostart", "DelayedAutostart", Status.Ok, "已移除");
}
}
}
catch (Exception ex)
{
AddResult("1-FailureActions", "FailureActions", Status.Fail, ex.Message);
}
// TriggerInfo:类型 7 = 设备接口到达即启动。
// 这是"插手柄/游戏一运行服务就回来"的直接原因。
try
{
using (var k = Registry.LocalMachine.OpenSubKey(SvcKeyPath, true))
{
if (k != null && k.OpenSubKey("TriggerInfo") != null)
{
int n = k.OpenSubKey("TriggerInfo").GetSubKeyNames().Length;
k.DeleteSubKeyTree("TriggerInfo", false);
AddResult("1-TriggerInfo", @"...\TriggerInfo", Status.Ok,
string.Format("已移除(含 {0} 个触发器)", n));
}
else
{
AddResult("1-TriggerInfo", @"...\TriggerInfo", Status.Skip, "无此子项");
}
}
}
catch (Exception ex)
{
AddResult("1-TriggerInfo", @"...\TriggerInfo", Status.Fail, ex.Message);
}
}
// ════════════════════════════════════════════════════════════════
// 步骤 2:强制停止 + 禁用
// ════════════════════════════════════════════════════════════════
private static void StopAndDisable()
{
WriteLog("── 步骤 2:强制停止服务并设为禁用 ──");
var info = GetSvcInfo();
if (!info.Registered)
{
AddResult("2-Stop", SvcName, Status.Skip, "服务未注册(无需停止)");
}
else if (info.State == SERVICE_STOPPED)
{
AddResult("2-Stop", SvcName, Status.Skip,
string.Format("已是 Stopped(Win32Exit={0})", info.Win32Exit));
}
else
{
StopServiceForcefully(info);
}
// 设为 Disabled(Start=4)
IntPtr scm = OpenSCManager(null, null, SC_MANAGER_CONNECT);
if (scm == IntPtr.Zero)
{
AddResult("2-Disable", SvcName, Status.Fail,
"无法连接服务控制管理器, 错误 " + Marshal.GetLastWin32Error());
}
else
{
try
{
IntPtr h = OpenService(scm, SvcName, SERVICE_CHANGE_CONFIG);
if (h == IntPtr.Zero)
{
AddResult("2-Disable", SvcName, Status.Fail,
"打开服务失败, 错误 " + Marshal.GetLastWin32Error());
}
else
{
try
{
if (ChangeServiceConfig(h, 0xFFFFFFFF, SERVICE_DISABLED, -1,
null, null, IntPtr.Zero, null, null, null, null))
{
AddResult("2-Disable", "Start", Status.Ok, "Start=4 (Disabled)");
}
else
{
AddResult("2-Disable", "Start", Status.Fail,
"ChangeServiceConfig 失败, 错误 " + Marshal.GetLastWin32Error());
}
}
finally { CloseServiceHandle(h); }
}
}
finally { CloseServiceHandle(scm); }
}
}
/// <summary>先温和停止,超时后再强杀宿主进程 —— 这就是"强制关闭"。</summary>
private static void StopServiceForcefully(SvcInfo info)
{
IntPtr scm = OpenSCManager(null, null, SC_MANAGER_CONNECT);
if (scm == IntPtr.Zero)
{
AddResult("2-Stop", SvcName, Status.Fail,
"无法连接 SCM, 错误 " + Marshal.GetLastWin32Error());
return;
}
try
{
IntPtr h = OpenService(scm, SvcName, SERVICE_STOP | SERVICE_QUERY_STATUS);
if (h == IntPtr.Zero)
{
AddResult("2-Stop", SvcName, Status.Fail,
"打开服务失败, 错误 " + Marshal.GetLastWin32Error());
return;
}
try
{
var st = new SERVICE_STATUS();
ControlService(h, SERVICE_CONTROL_STOP, ref st);
WriteLog(" 已发送停止请求,等待服务退出…");
var sw = Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < 15000)
{
System.Threading.Thread.Sleep(400);
var ssp = new SERVICE_STATUS_PROCESS();
int needed;
if (!QueryServiceStatusEx(h, SC_STATUS_PROCESS_INFO, ref ssp,
Marshal.SizeOf(typeof(SERVICE_STATUS_PROCESS)), out needed))
break;
if (ssp.dwCurrentState == SERVICE_STOPPED)
{
AddResult("2-Stop", SvcName, Status.Ok,
string.Format("已停止(耗时 {0:F1}s)", sw.Elapsed.TotalSeconds));
return;
}
}
// 温和停止失败 → 强杀进程
WriteLog(" 服务未在 15 秒内停止,转为强制结束进程。", Status.Warn);
ForceKillPid(info.ProcessId, h);
}
finally { CloseServiceHandle(h); }
}
finally { CloseServiceHandle(scm); }
}
private static void ForceKillPid(uint pid, IntPtr hSvc)
{
if (pid == 0)
{
AddResult("2-Stop", SvcName, Status.Fail,
"停止超时,且服务未暴露进程 ID(可能从未真正启动)");
return;
}
try
{
using (var p = Process.GetProcessById((int)pid))
{
string name = p.ProcessName;
p.Kill();
p.WaitForExit(10000);
AddResult("2-Stop", SvcName, Status.Warn,
string.Format("温和停止超时,已强制结束进程 {0} (PID {1})", name, pid));
}
}
catch (Exception ex)
{
AddResult("2-Stop", SvcName, Status.Fail,
string.Format("强杀 PID {0} 失败: {1}", pid, ex.Message));
}
}
// ════════════════════════════════════════════════════════════════
// 步骤 3:删除服务注册项
// ════════════════════════════════════════════════════════════════
private static void DeleteServiceReg()
{
WriteLog("── 步骤 3:删除 SCM 服务注册项 ──");
if (Registry.LocalMachine.OpenSubKey(SvcKeyPath) == null)
{
AddResult("3-DeleteSvc", SvcName, Status.Skip, "注册项已不存在");
return;
}
IntPtr scm = OpenSCManager(null, null, SC_MANAGER_CONNECT);
if (scm == IntPtr.Zero)
{
AddResult("3-DeleteSvc", SvcName, Status.Fail, "无法连接 SCM");
return;
}
try
{
IntPtr h = OpenService(scm, SvcName, 0x10000 /*DELETE*/);
if (h == IntPtr.Zero)
{
int err = Marshal.GetLastWin32Error();
if (err == 1060) { AddResult("3-DeleteSvc", SvcName, Status.Skip, "服务不存在"); return; }
AddResult("3-DeleteSvc", SvcName, Status.Fail, "打开服务失败, 错误 " + err);
return;
}
try
{
if (DeleteService(h))
AddResult("3-DeleteSvc", SvcName, Status.Ok, "服务已标记删除");
else
{
int err = Marshal.GetLastWin32Error();
// 1072 = ERROR_SERVICE_MARKED_FOR_DELETE
AddResult("3-DeleteSvc", SvcName,
err == 1072 ? Status.Warn : Status.Fail,
"DeleteService 失败, 错误 " + err + (err == 1072 ? "(已标记删除,重启后消失)" : ""));
}
}
finally { CloseServiceHandle(h); }
}
finally { CloseServiceHandle(scm); }
}
// ════════════════════════════════════════════════════════════════
// 步骤 4:取得所有权并删除二进制
// ════════════════════════════════════════════════════════════════
private static void TakeOwnership(string path)
{
int rc;
RunTool("takeown.exe", "/F \"" + path + "\" /A", out rc);
RunTool("icacls.exe", "\"" + path + "\" /grant *S-1-5-32-544:(F)", out rc);
RunTool("attrib.exe", "-R -S -H \"" + path + "\"", out rc);
}
private static void RemoveTargetFile(string path)
{
if (!Exists(path))
{
AddResult("4-DeleteFile", path, Status.Skip, "不存在");
return;
}
string size = "?", owner = "?";
try
{
var fi = new FileInfo(path);
size = fi.Length.ToString();
try { owner = fi.GetAccessControl().GetOwner(typeof(NTAccount)).ToString(); }
catch { }
}
catch { }
// 第一轮:直接删
string firstErr;
try
{
File.Delete(path);
AddResult("4-DeleteFile", path, Status.Ok,
string.Format("已删除(原大小 {0}, 属主 {1})", size, owner));
return;
}
catch (Exception ex) { firstErr = ex.Message; }
// 第二轮:取得所有权后重试
WriteLog(" 取得所有权后重试: " + path);
TakeOwnership(path);
try
{
File.Delete(path);
AddResult("4-DeleteFile", path, Status.Ok,
string.Format("取得所有权后删除成功(原属主 {0})", owner));
return;
}
catch (Exception ex)
{
// 第三轮:登记重启删除
if (RegisterPendingDelete(path))
AddResult("4-DeleteFile", path, Status.Warn,
"文件被占用,已登记重启后删除(" + ex.Message + ")");
else
AddResult("4-DeleteFile", path, Status.Fail,
"删除失败: " + firstErr + " / " + ex.Message);
}
}
private static void DeleteBinaries()
{
WriteLog("── 步骤 4:删除 GameInput 二进制 ──");
var all = new List<string>(TargetFiles);
// 服务主程序按"实际形态"归类:非 0 字节才是真二进制,纳入删除集;
// 0 字节说明它已被替换成墓碑,交给步骤 5 清理,不在这里删。
if (Exists(SvcBinary))
{
long svcLen = -1;
try { svcLen = new FileInfo(SvcBinary).Length; }
catch { }
if (svcLen > 0) all.Add(SvcBinary);
else AddResult("4-SvcBinary", SvcBinary, Status.Skip,
"0 字节墓碑形态,交给步骤 5 清理(不在步骤 4 删除)");
}
var winsxs = new List<string>();
// 枚举硬链接。WinSxS 是受保护的组件存储:单独删掉它会让
// 组件清单与实际文件不一致,导致 sfc/DISM 报错且无法自动修复。
// 默认保留;System32 侧链接消失后程序已无法正常加载。
foreach (var f in all.ToArray())
{
if (!Exists(f)) continue;
int rc;
string outp = RunTool("fsutil.exe", "hardlink list \"" + f + "\"", out rc);
foreach (var raw in outp.Split('\n'))
{
string l = raw.Trim().TrimEnd('\r');
if (l.Length == 0 || l[0] != '\\') continue;
if (l.StartsWith(@"\Windows\", StringComparison.OrdinalIgnoreCase))
{
string full = "C:" + l;
if (all.Contains(full)) continue;
if (full.IndexOf(@"\WinSxS\", StringComparison.OrdinalIgnoreCase) >= 0)
{
if (!winsxs.Contains(full)) winsxs.Add(full);
}
else all.Add(full);
}
}
}
if (winsxs.Count > 0)
{
if (_includeWinSxS)
{
all.AddRange(winsxs);
AddResult("4-WinSxS", @"C:\Windows\WinSxS", Status.Warn,
string.Format("已按 -IncludeWinSxS 纳入 {0} 个组件存储链接", winsxs.Count));
}
else
{
AddResult("4-WinSxS", @"C:\Windows\WinSxS", Status.Skip,
string.Format("保留 {0} 个硬链接源(组件存储受保护;加 -IncludeWinSxS 可强制删除)", winsxs.Count));
}
}
WriteLog(string.Format(" 待处理路径 {0} 个", all.Count));
foreach (var p in all) RemoveTargetFile(p);
try
{
string[] man = Directory.GetFiles(@"C:\Windows\WinSxS\Manifests", "*gameinput*");
if (man.Length > 0)
AddResult("4-Manifests", @"C:\Windows\WinSxS\Manifests", Status.Warn,
string.Format("保留 {0} 个组件清单(强删会导致 sfc/DISM 组件存储不一致)", man.Length));
}
catch { }
}
// ════════════════════════════════════════════════════════════════
// 步骤 5:清理 0 字节墓碑
// ════════════════════════════════════════════════════════════════
private static void CleanTombstones()
{
WriteLog("── 步骤 5:清理 0 字节墓碑残留 ──");
// 候选集 = 固定墓碑路径 + (仅当它确实是 0 字节时才加入)服务主程序路径。
// 这样修复过的真实二进制绝不会进入本步骤。
var candidates = new List<string>(Tombstones);
if (Exists(SvcBinary))
{
long svcLen = -1;
try { svcLen = new FileInfo(SvcBinary).Length; }
catch { }
if (svcLen == 0) candidates.Add(SvcBinary);
else AddResult("5-SvcBinary", SvcBinary, Status.Skip,
string.Format("非 0 字节文件 (大小 {0}),是正常的服务二进制,不按墓碑清理", svcLen));
}
foreach (var p in candidates)
{
if (!Exists(p))
{
AddResult("5-Tombstone", p, Status.Skip, "不存在");
continue;
}
bool isDir;
long len = -1;
try
{
var attr = File.GetAttributes(p);
isDir = (attr & FileAttributes.Directory) != 0;
if (!isDir) len = new FileInfo(p).Length;
}
catch (Exception ex)
{
AddResult("5-Tombstone", p, Status.Fail, "读取属性失败: " + ex.Message);
continue;
}
// 只删"确认是 0 字节文件"的目标,避免误删真实程序
if (isDir || len != 0)
{
AddResult("5-Tombstone", p, Status.Skip,
isDir ? "是目录,跳过" : string.Format("非 0 字节({0}),跳过以免误删", len));
continue;
}
try
{
File.Delete(p);
AddResult("5-Tombstone", p, Status.Ok, "已删除(0 字节墓碑)");
continue;
}
catch { }
TakeOwnership(p);
try
{
File.Delete(p);
AddResult("5-Tombstone", p, Status.Ok, "取得所有权后删除成功");
}
catch (Exception ex)
{
if (RegisterPendingDelete(p))
AddResult("5-Tombstone", p, Status.Warn, "已登记重启后删除");
else
AddResult("5-Tombstone", p, Status.Fail, ex.Message);
}
}
AddResult("5-Note", "火绒(Huorong)", Status.Warn,
"HRWSCCtrl 正在运行;这些墓碑很可能是它的文件保护产物,删除后若再次出现请查其防护日志");
}
// ════════════════════════════════════════════════════════════════
// 步骤 6:登记重启删除
// ════════════════════════════════════════════════════════════════
private static bool RegisterPendingDelete(string path)
{
try
{
using (var k = Registry.LocalMachine.OpenSubKey(SessionMgrPath, true))
{
if (k == null) return false;
var cur = k.GetValue("PendingFileRenameOperations") as string[];
var list = new List<string>(cur ?? new string[0]);
// 格式:源路径 + 空目标 = 删除
string entry = @"\??\" + path;
if (list.Contains(entry)) return true;
list.Add(entry);
list.Add("");
k.SetValue("PendingFileRenameOperations", list.ToArray(), RegistryValueKind.MultiString);
WriteLog(" 已登记重启删除: " + path, Status.Ok);
return true;
}
}
catch (Exception ex)
{
WriteLog(" 登记重启删除失败 (" + path + "): " + ex.Message, Status.Fail);
return false;
}
}
private static void PendingCleanup()
{
WriteLog("── 步骤 6:重启删除队列确认 ──");
try
{
using (var k = Registry.LocalMachine.OpenSubKey(SessionMgrPath))
{
var cur = k == null ? null : k.GetValue("PendingFileRenameOperations") as string[];
int hits = 0;
if (cur != null)
foreach (var s in cur)
if (s.IndexOf("GameInput", StringComparison.OrdinalIgnoreCase) >= 0) hits++;
if (hits > 0)
{
AddResult("6-Pending", "PendingFileRenameOperations", Status.Ok,
string.Format("队列中有 {0} 条 GameInput 相关项,重启后生效", hits));
AddResult("6-Reboot", "系统", Status.Warn, "需要重启才能完成清理");
}
else AddResult("6-Pending", "PendingFileRenameOperations", Status.Skip, "无遗留项");
}
}
catch (Exception ex)
{
AddResult("6-Pending", "PendingFileRenameOperations", Status.Warn, ex.Message);
}
}
// ════════════════════════════════════════════════════════════════
// 复检
// ════════════════════════════════════════════════════════════════
private static void PostCheck()
{
WriteLog("── 复检 ──");
var info = GetSvcInfo();
if (info.Registered)
AddResult("Post-Service", SvcName, Status.Warn,
string.Format("服务仍存在: {0} / {1}", StateName(info.State), StartTypeName(info.RegStart)));
else
AddResult("Post-Service", SvcName, Status.Ok,
string.Format("服务已注销(注册项 Start={0})", StartTypeName(info.RegStart)));
foreach (var f in TargetFiles)
{
if (Exists(f)) AddResult("Post-File", f, Status.Warn, "仍存在");
else AddResult("Post-File", f, Status.Ok, "已清除");
}
int n = 0;
foreach (var p in Process.GetProcesses())
{
try { if (p.ProcessName.IndexOf("GameInput", StringComparison.OrdinalIgnoreCase) >= 0) n++; }
catch { }
finally { p.Dispose(); }
}
AddResult("Post-Process", "GameInput*", n == 0 ? Status.Ok : Status.Warn,
n == 0 ? "无相关进程" : string.Format("仍有 {0} 个进程", n));
}
// ════════════════════════════════════════════════════════════════
// 审计
// ════════════════════════════════════════════════════════════════
private static void Audit()
{
WriteLog("── 审计模式:只检测,不修改 ──");
var info = GetSvcInfo();
if (info.Registered)
AddResult("Audit-Service", SvcName, Status.Warn,
string.Format("{0} / {1}", StateName(info.State), StartTypeName(info.RegStart)));
else
AddResult("Audit-Service", SvcName, Status.Ok, "未注册");
AddResult("Audit-Start", "Start", Status.Skip,
string.Format("Start={0} ({1})", info.RegStart, StartTypeName(info.RegStart)));
bool hasFa = GetRegValueString(SvcKeyPath, "FailureActions") != null;
AddResult("Audit-FailureActions", "FailureActions", hasFa ? Status.Warn : Status.Ok,
hasFa ? "存在:失败会自动重启" : "无");
bool hasTrig;
using (var k = Registry.LocalMachine.OpenSubKey(SvcKeyPath))
hasTrig = k != null && k.OpenSubKey("TriggerInfo") != null;
AddResult("Audit-TriggerInfo", "TriggerInfo", hasTrig ? Status.Warn : Status.Ok,
hasTrig ? "存在:按设备接口触发启动(插手柄即拉起)" : "无");
foreach (var f in TargetFiles)
{
if (!Exists(f)) { AddResult("Audit-File", f, Status.Ok, "已清除"); continue; }
int rc;
string outp = RunTool("fsutil.exe", "hardlink list \"" + f + "\"", out rc);
int links = 0;
foreach (var raw in outp.Split('\n'))
{
string l = raw.Trim();
if (l.Length > 0 && l[0] == '\\') links++;
}
long len = 0;
try { len = new FileInfo(f).Length; } catch { }
AddResult("Audit-File", f, Status.Warn,
string.Format("存在 大小={0} 硬链接={1}", len, links));
}
foreach (var t in Tombstones)
{
if (!Exists(t)) { AddResult("Audit-Tombstone", t, Status.Ok, "不存在"); continue; }
bool isDir;
long len = 0;
try
{
var a = File.GetAttributes(t);
isDir = (a & FileAttributes.Directory) != 0;
if (!isDir) len = new FileInfo(t).Length;
}
catch { isDir = false; }
AddResult("Audit-Tombstone", t, Status.Warn,
isDir ? "目录" : string.Format("{0} 字节墓碑", len));
}
// 服务主程序:按实际形态报告,避免把修好的真二进制误报成墓碑
if (!Exists(SvcBinary))
{
AddResult("Audit-SvcBinary", SvcBinary, Status.Ok, "不存在");
}
else
{
bool isDir;
long len = -1;
try
{
var a = File.GetAttributes(SvcBinary);
isDir = (a & FileAttributes.Directory) != 0;
if (!isDir) len = new FileInfo(SvcBinary).Length;
}
catch { isDir = false; }
if (isDir)
AddResult("Audit-SvcBinary", SvcBinary, Status.Warn, "是目录,形态异常");
else if (len == 0)
AddResult("Audit-SvcBinary", SvcBinary, Status.Warn, "0 字节墓碑,步骤 5 可清理");
else
AddResult("Audit-SvcBinary", SvcBinary, Status.Warn,
string.Format("存在 大小={0}(正常的服务二进制;步骤 4 会删除它)", len));
}
}
// ════════════════════════════════════════════════════════════════