Repository navigation
Expand file tree
/
Copy pathContextMenuDeepAnalysisService.cs
More file actions
683 lines (618 loc) · 31.6 KB
/
Copy pathContextMenuDeepAnalysisService.cs
File metadata and controls
683 lines (618 loc) · 31.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
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using ContextMenuMgr.Contracts;
using Microsoft.Win32;
namespace ContextMenuMgr.Frontend.Services;
public sealed class ContextMenuDeepAnalysisService
{
private const int NativeAccessViolationExitCode = -1073741819;
private const int StackBufferOverrunExitCode = -1073740791;
private const string ProbeHostArchitectureMismatchMessage = "解析辅助进程架构与目录标识不一致,无法启动。请重新构建或安装完整程序包。";
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
private static readonly UTF8Encoding Utf8NoBom = new(encoderShouldEmitUTF8Identifier: false);
private readonly LocalizationService _localization;
public ContextMenuDeepAnalysisService(LocalizationService localization)
{
_localization = localization;
}
public async Task<ContextMenuDeepAnalysisResult> AnalyzeAsync(
ContextMenuDeepAnalysisRequest request,
TimeSpan? timeout = null,
CancellationToken cancellationToken = default)
{
if (request.OperationId == Guid.Empty)
{
request = request with { OperationId = Guid.NewGuid() };
}
var startedAt = DateTimeOffset.UtcNow;
FrontendDebugLog.Operation(
"FrontendOperation",
$"DeepAnalysisStart: OperationId={request.OperationId}, ItemId={request.ItemId}, DisplayName={request.DisplayName}, EntryKind={request.EntryKind}, Category={request.Category}, HandlerClsid={request.HandlerClsid}, ProbeMode={request.ProbeMode}, Timestamp={startedAt:O}.");
var selection = SelectProbeHost(request);
FrontendDebugLog.Info(
"ContextMenuDeepAnalysisService",
$"ProbeHostSelection: OSArchitecture={RuntimeInformation.OSArchitecture}, FrontendProcessArchitecture={RuntimeInformation.ProcessArchitecture}, HandlerFilePath={selection.HandlerFilePath ?? "<null>"}, HandlerFileExists={selection.HandlerFileExists}, HandlerMachineType={selection.HandlerMachineType}, HandlerMachineRawValue={selection.HandlerMachineRawValue ?? "<null>"}, SelectedProbeHostPath={selection.SelectedProbeHostPath ?? "<null>"}, SelectedProbeHostArchitecture={selection.SelectedProbeHostArchitecture}, Reason={selection.Reason}.");
if (selection.FailureCode is not null || selection.SelectedProbeHostPath is null)
{
FrontendDebugLog.Operation(
"FrontendOperation",
$"DeepAnalysisEnd: OperationId={request.OperationId}, ItemId={request.ItemId}, ProbeMode={request.ProbeMode}, Success=false, ErrorCode={selection.FailureCode ?? "ProbeHostNotFound"}, ItemCount=0, ElapsedMs={(DateTimeOffset.UtcNow - startedAt).TotalMilliseconds:F0}.");
return Failure(selection.FailureCode ?? "ProbeHostNotFound", GetMissingHostMessage(selection), request) with
{
HandlerFilePath = selection.HandlerFilePath ?? request.HandlerFilePath,
HandlerFileExists = selection.HandlerFileExists,
HandlerMachineType = selection.HandlerMachineType,
HandlerFileMachineType = selection.HandlerMachineType,
HandlerMachineRawValue = selection.HandlerMachineRawValue,
SelectedProbeHostArchitecture = selection.SelectedProbeHostArchitecture.ToString(),
ArchitectureSelectionReason = selection.Reason,
OSArchitecture = RuntimeInformation.OSArchitecture.ToString(),
FrontendProcessArchitecture = RuntimeInformation.ProcessArchitecture.ToString(),
DiagnosticDetails = $"ProbeHostSelection: {selection.Reason}"
};
}
var probeHostPath = selection.SelectedProbeHostPath;
var architectureFailure = ValidateSelectedProbeHostArchitecture(selection, request);
if (architectureFailure is not null)
{
FrontendDebugLog.Operation(
"FrontendOperation",
$"DeepAnalysisEnd: OperationId={request.OperationId}, ItemId={request.ItemId}, ProbeMode={request.ProbeMode}, Success=false, ErrorCode={architectureFailure.ErrorCode}, ItemCount=0, ElapsedMs={(DateTimeOffset.UtcNow - startedAt).TotalMilliseconds:F0}.");
return architectureFailure;
}
using var timeoutCts = new CancellationTokenSource(timeout ?? TimeSpan.FromSeconds(5));
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token);
var operationDirectory = Path.Combine(Path.GetTempPath(), "ContextMenuMgr.DeepAnalysis", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(operationDirectory);
var requestPath = Path.Combine(operationDirectory, "request.json");
var resultPath = Path.Combine(operationDirectory, "result.json");
await File.WriteAllTextAsync(requestPath, JsonSerializer.Serialize(request, JsonOptions), Utf8NoBom, cancellationToken);
var startInfo = new ProcessStartInfo
{
FileName = probeHostPath,
WorkingDirectory = Path.GetDirectoryName(probeHostPath) ?? AppContext.BaseDirectory,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
StandardInputEncoding = Utf8NoBom,
StandardOutputEncoding = Utf8NoBom,
StandardErrorEncoding = Utf8NoBom
};
startInfo.ArgumentList.Add("--request");
startInfo.ArgumentList.Add(requestPath);
startInfo.ArgumentList.Add("--result");
startInfo.ArgumentList.Add(resultPath);
using var process = new Process { StartInfo = startInfo, EnableRaisingEvents = true };
Task<string>? outputTask = null;
Task<string>? errorTask = null;
try
{
FrontendDebugLog.Info(
"ContextMenuDeepAnalysisService",
$"ProbeHostStart: Path={probeHostPath}, OperationId={request.OperationId}, ItemId={request.ItemId}, ProbeMode={request.ProbeMode}, TimeoutMs={(timeout ?? TimeSpan.FromSeconds(5)).TotalMilliseconds:F0}, RequestPath={requestPath}, ResultPath={resultPath}.");
if (!process.Start())
{
FrontendDebugLog.Operation(
"FrontendOperation",
$"DeepAnalysisEnd: OperationId={request.OperationId}, ItemId={request.ItemId}, ProbeMode={request.ProbeMode}, Success=false, ErrorCode=ProbeHostStartFailed, ItemCount=0, ElapsedMs={(DateTimeOffset.UtcNow - startedAt).TotalMilliseconds:F0}.");
return Failure("ProbeHostStartFailed", "Failed to start ProbeHost.", request);
}
process.StandardInput.Close();
outputTask = process.StandardOutput.ReadToEndAsync();
errorTask = process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync(linkedCts.Token);
var output = await outputTask;
var error = await errorTask;
var exitCode = process.ExitCode;
var elapsedMs = (DateTimeOffset.UtcNow - startedAt).TotalMilliseconds;
var stdoutBytes = Utf8NoBom.GetByteCount(output);
var stderrBytes = Utf8NoBom.GetByteCount(error);
FrontendDebugLog.Info(
"ContextMenuDeepAnalysisService",
$"ProbeHostExit: OperationId={request.OperationId}, ItemId={request.ItemId}, ExitCode={exitCode}, ElapsedMs={elapsedMs:F0}, StdoutBytes={stdoutBytes}, StderrBytes={stderrBytes}, ResultFileExists={File.Exists(resultPath)}.");
FrontendDebugLog.Info(
"ContextMenuDeepAnalysisService",
$"ProbeHostCapturedOutput: ItemId={request.ItemId}, StdoutExcerpt={Excerpt(output, 300)}, StderrExcerpt={Excerpt(error, 1000)}.");
var resultJson = File.Exists(resultPath)
? await File.ReadAllTextAsync(resultPath, Utf8NoBom, cancellationToken)
: string.Empty;
if (!string.IsNullOrWhiteSpace(resultJson))
{
var parsed = EnrichWithSelection(TryParseResultJson(resultJson, exitCode, error, request, resultPath, source: "result file"), selection);
var jsonValid = parsed.ErrorCode is not "InvalidProbeHostJson" and not "InvalidProbeHostOutput";
FrontendDebugLog.Info(
"ContextMenuDeepAnalysisService",
$"ProbeHostResult: ItemId={request.ItemId}, Source=ResultFile, JsonValid={jsonValid}, Success={parsed.Success}, ErrorCode={parsed.ErrorCode ?? "<none>"}, ItemCount={parsed.Items.Count}.");
FrontendDebugLog.Operation(
"FrontendOperation",
$"DeepAnalysisEnd: OperationId={parsed.OperationId}, ItemId={request.ItemId}, ProbeMode={request.ProbeMode}, Success={parsed.Success}, ErrorCode={parsed.ErrorCode ?? "<none>"}, ItemCount={parsed.Items.Count}, ExitCode={exitCode}, ElapsedMs={elapsedMs:F0}.");
return parsed;
}
var trimmedStdout = TrimBomAndWhitespace(output);
if (trimmedStdout.StartsWith("{", StringComparison.Ordinal))
{
var parsed = EnrichWithSelection(TryParseResultJson(trimmedStdout, exitCode, error, request, "stdout", source: "stdout"), selection);
var jsonValid = parsed.ErrorCode is not "InvalidProbeHostJson" and not "InvalidProbeHostOutput";
FrontendDebugLog.Info(
"ContextMenuDeepAnalysisService",
$"ProbeHostResult: ItemId={request.ItemId}, Source=Stdout, JsonValid={jsonValid}, Success={parsed.Success}, ErrorCode={parsed.ErrorCode ?? "<none>"}, ItemCount={parsed.Items.Count}.");
FrontendDebugLog.Operation(
"FrontendOperation",
$"DeepAnalysisEnd: OperationId={parsed.OperationId}, ItemId={request.ItemId}, ProbeMode={request.ProbeMode}, Success={parsed.Success}, ErrorCode={parsed.ErrorCode ?? "<none>"}, ItemCount={parsed.Items.Count}, ExitCode={exitCode}, ElapsedMs={elapsedMs:F0}.");
return parsed;
}
var nativeCrash = TryBuildNativeCrashFailure(exitCode, output, error, request, requestPath, resultPath, selection);
if (nativeCrash is not null)
{
FrontendDebugLog.Warning(
"ContextMenuDeepAnalysisService",
$"ProbeHostExitFailure: ItemId={request.ItemId}, Category={request.Category}, HandlerClsid={request.HandlerClsid}, ErrorCode={nativeCrash.ErrorCode}, ExitCode={exitCode}, ExitCodeHex={FormatExitCodeHex(exitCode)}, ProbeHostArchitecture={ExtractProbeHostArchitecture(error)}, OSArchitecture={RuntimeInformation.OSArchitecture}, StdoutExcerpt={Excerpt(output, 300)}, StderrExcerpt={Excerpt(error, 1000)}.");
FrontendDebugLog.Operation(
"FrontendOperation",
$"DeepAnalysisEnd: OperationId={nativeCrash.OperationId}, ItemId={request.ItemId}, ProbeMode={request.ProbeMode}, Success=false, ErrorCode={nativeCrash.ErrorCode}, ItemCount=0, ExitCode={exitCode}, ExitCodeHex={FormatExitCodeHex(exitCode)}, ElapsedMs={elapsedMs:F0}.");
return nativeCrash;
}
var invalidOutput = EnrichWithSelection(BuildInvalidOutputFailure(exitCode, output, error, request, requestPath, resultPath), selection);
FrontendDebugLog.Warning(
"ContextMenuDeepAnalysisService",
$"ProbeHostInvalidOutput: ItemId={request.ItemId}, ExitCode={exitCode}, StdoutExcerpt={Excerpt(output, 300)}, StderrExcerpt={Excerpt(error, 1000)}.");
FrontendDebugLog.Operation(
"FrontendOperation",
$"DeepAnalysisEnd: OperationId={invalidOutput.OperationId}, ItemId={request.ItemId}, ProbeMode={request.ProbeMode}, Success=false, ErrorCode={invalidOutput.ErrorCode}, ItemCount=0, ExitCode={exitCode}, ElapsedMs={elapsedMs:F0}.");
return invalidOutput;
}
catch (OperationCanceledException) when (timeoutCts.IsCancellationRequested)
{
KillProcess(process);
var output = await TryReadTaskAsync(outputTask);
var error = await TryReadTaskAsync(errorTask);
FrontendDebugLog.Warning(
"ContextMenuDeepAnalysisService",
$"ProbeHostExit: ItemId={request.ItemId}, ExitCode=<timeout>, ElapsedMs={(DateTimeOffset.UtcNow - startedAt).TotalMilliseconds:F0}, StdoutBytes={Utf8NoBom.GetByteCount(output)}, StderrBytes={Utf8NoBom.GetByteCount(error)}, ResultJsonValid=false.");
FrontendDebugLog.Operation(
"FrontendOperation",
$"DeepAnalysisEnd: OperationId={request.OperationId}, ItemId={request.ItemId}, ProbeMode={request.ProbeMode}, Success=false, ErrorCode=Timeout, ItemCount=0, ElapsedMs={(DateTimeOffset.UtcNow - startedAt).TotalMilliseconds:F0}.");
return Failure("Timeout", _localization.Translate("DeepAnalyzeTimeoutText"), request);
}
catch (Exception ex)
{
KillProcess(process);
FrontendDebugLog.Error(
"FrontendOperation",
ex,
$"DeepAnalysisEnd: OperationId={request.OperationId}, ItemId={request.ItemId}, ProbeMode={request.ProbeMode}, Success=false, ErrorCode=ProbeHostFailed, ItemCount=0, ElapsedMs={(DateTimeOffset.UtcNow - startedAt).TotalMilliseconds:F0}.");
return Failure("ProbeHostFailed", ex.Message, request);
}
finally
{
TryDeleteDirectory(operationDirectory);
}
}
private ProbeHostSelection SelectProbeHost(ContextMenuDeepAnalysisRequest request)
{
var handlerFilePath = NormalizeComServerPath(request.HandlerFilePath) ?? ResolveHandlerPathFromClsid(request.HandlerClsid);
var machine = PeMachineTypeDetector.Detect(handlerFilePath);
var architecture = machine.Architecture == ProbeHostArchitecture.Unknown
? CurrentProcessProbeHostArchitecture()
: machine.Architecture;
var path = LocateProbeHost(architecture, allowRootFallback: machine.Architecture == ProbeHostArchitecture.Unknown);
var reason = machine.Architecture == ProbeHostArchitecture.Unknown
? $"UnknownHandlerArchitectureFallback: {machine.Error ?? "unknown machine type"}"
: $"HandlerMachineType={machine.MachineType}";
if (path is not null)
{
return new ProbeHostSelection(
path,
architecture,
handlerFilePath,
!string.IsNullOrWhiteSpace(handlerFilePath) && File.Exists(handlerFilePath),
machine.MachineType,
machine.RawValue,
reason,
null);
}
var failureCode = architecture switch
{
ProbeHostArchitecture.X86 => "MissingX86ProbeHost",
ProbeHostArchitecture.X64 => "MissingX64ProbeHost",
ProbeHostArchitecture.Arm64 => "MissingArm64ProbeHost",
_ => "ProbeHostNotFound"
};
return new ProbeHostSelection(
null,
architecture,
handlerFilePath,
!string.IsNullOrWhiteSpace(handlerFilePath) && File.Exists(handlerFilePath),
machine.MachineType,
machine.RawValue,
$"{reason}; Missing host for {architecture}.",
failureCode);
}
private static ProbeHostArchitecture CurrentProcessProbeHostArchitecture() => RuntimeInformation.ProcessArchitecture switch
{
Architecture.X86 => ProbeHostArchitecture.X86,
Architecture.X64 => ProbeHostArchitecture.X64,
Architecture.Arm64 => ProbeHostArchitecture.Arm64,
_ => ProbeHostArchitecture.Unknown
};
private static string? LocateProbeHost(ProbeHostArchitecture architecture, bool allowRootFallback)
{
var baseDirectory = AppContext.BaseDirectory;
var architectureName = architecture switch
{
ProbeHostArchitecture.X86 => "x86",
ProbeHostArchitecture.X64 => "x64",
ProbeHostArchitecture.Arm64 => "arm64",
_ => null
};
var candidates = new List<string>();
if (!string.IsNullOrWhiteSpace(architectureName))
{
candidates.Add(Path.Combine(baseDirectory, "ProbeHost", architectureName, "ContextMenuMgr.ProbeHost.exe"));
}
if (allowRootFallback)
{
candidates.Add(Path.Combine(baseDirectory, "ContextMenuMgr.ProbeHost.exe"));
candidates.Add(Path.Combine(baseDirectory, "probehost", "ContextMenuMgr.ProbeHost.exe"));
}
return candidates.FirstOrDefault(File.Exists);
}
private string GetMissingHostMessage(ProbeHostSelection selection)
{
return selection.FailureCode switch
{
"MissingX86ProbeHost" => _localization.Translate("DeepAnalysisMissingX86ProbeHost"),
"MissingX64ProbeHost" => _localization.Translate("DeepAnalysisMissingX64ProbeHost"),
"MissingArm64ProbeHost" => _localization.Translate("DeepAnalysisMissingArm64ProbeHost"),
_ => "ContextMenuMgr.ProbeHost.exe was not found."
};
}
private ContextMenuDeepAnalysisResult? ValidateSelectedProbeHostArchitecture(
ProbeHostSelection selection,
ContextMenuDeepAnalysisRequest request)
{
if (string.IsNullOrWhiteSpace(selection.SelectedProbeHostPath)
|| selection.SelectedProbeHostArchitecture == ProbeHostArchitecture.Unknown)
{
return null;
}
var machine = PeMachineTypeDetector.Detect(selection.SelectedProbeHostPath);
var folderLabel = Path.GetFileName(Path.GetDirectoryName(selection.SelectedProbeHostPath) ?? string.Empty);
FrontendDebugLog.Info(
"ContextMenuDeepAnalysisService",
$"ProbeHostExecutableArchitecture: SelectedProbeHostPath={selection.SelectedProbeHostPath}, FolderLabel={folderLabel}, SelectedProbeHostArchitecture={selection.SelectedProbeHostArchitecture}, ActualProbeHostMachineType={machine.MachineType}, ActualProbeHostMachineRawValue={machine.RawValue ?? "<null>"}, Error={machine.Error ?? "<none>"}.");
if (machine.Architecture == selection.SelectedProbeHostArchitecture)
{
return null;
}
var diagnosticDetails = string.Join(
Environment.NewLine,
new[]
{
$"SelectedProbeHostPath={selection.SelectedProbeHostPath}",
$"SelectedProbeHostArchitecture={selection.SelectedProbeHostArchitecture}",
$"ProbeHostFolderLabel={folderLabel}",
$"ActualProbeHostMachineType={machine.MachineType}",
$"ActualProbeHostMachineRawValue={machine.RawValue}",
$"ActualProbeHostMachineError={machine.Error}",
$"HandlerFilePath={selection.HandlerFilePath ?? request.HandlerFilePath}",
$"HandlerMachineType={selection.HandlerMachineType}",
$"HandlerMachineRawValue={selection.HandlerMachineRawValue}",
$"OSArchitecture={RuntimeInformation.OSArchitecture}",
$"FrontendProcessArchitecture={RuntimeInformation.ProcessArchitecture}"
}.Where(static line => !string.IsNullOrWhiteSpace(line)));
return Failure(
"ProbeHostExecutableArchitectureMismatch",
ProbeHostArchitectureMismatchMessage,
request) with
{
HandlerFilePath = selection.HandlerFilePath ?? request.HandlerFilePath,
HandlerFileExists = selection.HandlerFileExists,
HandlerMachineType = selection.HandlerMachineType,
HandlerFileMachineType = selection.HandlerMachineType,
HandlerMachineRawValue = selection.HandlerMachineRawValue,
SelectedProbeHostArchitecture = selection.SelectedProbeHostArchitecture.ToString(),
SelectedProbeHostPath = selection.SelectedProbeHostPath,
ActualProbeHostMachineType = machine.MachineType,
ArchitectureSelectionReason = selection.Reason,
OSArchitecture = RuntimeInformation.OSArchitecture.ToString(),
FrontendProcessArchitecture = RuntimeInformation.ProcessArchitecture.ToString(),
DiagnosticDetails = diagnosticDetails
};
}
private static string? ResolveHandlerPathFromClsid(string? handlerClsid)
{
if (!Guid.TryParse(handlerClsid, out var clsid))
{
return null;
}
var clsidText = clsid.ToString("B");
foreach (var valuePath in new[]
{
$@"CLSID\{clsidText}\InprocServer32",
$@"CLSID\{clsidText}\LocalServer32"
})
{
try
{
using var key = Registry.ClassesRoot.OpenSubKey(valuePath);
if (key?.GetValue(null) is string value && !string.IsNullOrWhiteSpace(value))
{
return NormalizeComServerPath(value);
}
}
catch
{
}
}
return null;
}
private static string? NormalizeComServerPath(string? value)
{
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
var expanded = Environment.ExpandEnvironmentVariables(value.Trim());
if (expanded.StartsWith('"'))
{
var closingQuoteIndex = expanded.IndexOf('"', 1);
if (closingQuoteIndex > 1)
{
return expanded[1..closingQuoteIndex];
}
}
foreach (var extension in new[] { ".dll", ".exe" })
{
var index = expanded.IndexOf(extension, StringComparison.OrdinalIgnoreCase);
if (index >= 0)
{
return expanded[..(index + extension.Length)];
}
}
return expanded;
}
private static ContextMenuDeepAnalysisResult Failure(
string errorCode,
string message,
ContextMenuDeepAnalysisRequest request)
{
return new ContextMenuDeepAnalysisResult
{
OperationId = request.OperationId,
Success = false,
ErrorCode = errorCode,
Message = message,
DisplayName = request.DisplayName,
HandlerClsid = request.HandlerClsid,
HandlerFilePath = request.HandlerFilePath,
SamplePath = request.SamplePath,
HandlerFileExists = !string.IsNullOrWhiteSpace(request.HandlerFilePath) && File.Exists(request.HandlerFilePath),
OSArchitecture = RuntimeInformation.OSArchitecture.ToString(),
FrontendProcessArchitecture = RuntimeInformation.ProcessArchitecture.ToString(),
ProbeMode = request.ProbeMode,
IsSpecificHandlerResult = false,
IsWholeContextMenuResult = false,
SpecificHandlerFailedButWholeContextAvailable = request.ProbeMode == ContextMenuDeepAnalysisProbeMode.SpecificHandler,
SpecificHandlerFailureCode = request.ProbeMode == ContextMenuDeepAnalysisProbeMode.SpecificHandler ? errorCode : null,
SpecificHandlerFailureMessage = request.ProbeMode == ContextMenuDeepAnalysisProbeMode.SpecificHandler ? message : null
};
}
private static ContextMenuDeepAnalysisResult TryParseResultJson(
string json,
int exitCode,
string stderr,
ContextMenuDeepAnalysisRequest request,
string sourcePath,
string source)
{
var trimmedJson = TrimBomAndWhitespace(json);
if (!trimmedJson.StartsWith("{", StringComparison.Ordinal))
{
return BuildInvalidOutputFailure(exitCode, json, stderr, request, sourcePath, sourcePath);
}
try
{
var result = JsonSerializer.Deserialize<ContextMenuDeepAnalysisResult>(trimmedJson, JsonOptions);
if (result is not null)
{
return result.OperationId == Guid.Empty
? result with { OperationId = request.OperationId }
: result;
}
return Failure(
"InvalidProbeHostJson",
BuildInvalidJsonMessage("ProbeHost returned an empty JSON result.", exitCode, json, stderr, source, sourcePath),
request);
}
catch (JsonException ex)
{
FrontendDebugLog.Warning(
"ContextMenuDeepAnalysisService",
$"ProbeHostInvalidJson: ItemId={request.ItemId}, Source={source}, SourcePath={sourcePath}, ExitCode={exitCode}, JsonError={ex.Message}, StdoutOrResultExcerpt={Excerpt(json, 300)}, StderrExcerpt={Excerpt(stderr, 1000)}.");
return Failure(
"InvalidProbeHostJson",
BuildInvalidJsonMessage(ex.Message, exitCode, json, stderr, source, sourcePath),
request);
}
}
private static ContextMenuDeepAnalysisResult EnrichWithSelection(
ContextMenuDeepAnalysisResult result,
ProbeHostSelection selection)
{
return result with
{
HandlerFilePath = result.HandlerFilePath ?? selection.HandlerFilePath,
HandlerFileExists = result.HandlerFileExists || selection.HandlerFileExists,
HandlerMachineType = result.HandlerMachineType ?? selection.HandlerMachineType,
HandlerFileMachineType = result.HandlerFileMachineType ?? selection.HandlerMachineType,
HandlerMachineRawValue = result.HandlerMachineRawValue ?? selection.HandlerMachineRawValue,
SelectedProbeHostArchitecture = selection.SelectedProbeHostArchitecture.ToString(),
SelectedProbeHostPath = selection.SelectedProbeHostPath,
ActualProbeHostMachineType = result.ActualProbeHostMachineType ?? PeMachineTypeDetector.Detect(selection.SelectedProbeHostPath).MachineType,
ArchitectureSelectionReason = selection.Reason,
OSArchitecture = result.OSArchitecture ?? RuntimeInformation.OSArchitecture.ToString(),
FrontendProcessArchitecture = result.FrontendProcessArchitecture ?? RuntimeInformation.ProcessArchitecture.ToString()
};
}
private ContextMenuDeepAnalysisResult? TryBuildNativeCrashFailure(
int exitCode,
string stdout,
string stderr,
ContextMenuDeepAnalysisRequest request,
string requestPath,
string resultPath,
ProbeHostSelection selection)
{
var errorCode = exitCode switch
{
NativeAccessViolationExitCode => "ProbeHostNativeAccessViolation",
StackBufferOverrunExitCode => "ProbeHostStackBufferOverrun",
< 0 => "ProbeHostNativeCrash",
_ => null
};
if (errorCode is null)
{
return null;
}
var message = errorCode switch
{
"ProbeHostNativeAccessViolation" => _localization.Translate("DeepAnalyzeNativeAccessViolationText"),
"ProbeHostStackBufferOverrun" => _localization.Translate("DeepAnalyzeStackBufferOverrunText"),
_ => _localization.Translate("DeepAnalyzeNativeCrashText")
};
return Failure(errorCode, message, request) with
{
ProbeHostProcessArchitecture = ExtractProbeHostArchitecture(stderr),
SelectedProbeHostArchitecture = selection.SelectedProbeHostArchitecture.ToString(),
SelectedProbeHostPath = selection.SelectedProbeHostPath,
HandlerMachineType = selection.HandlerMachineType,
HandlerFileMachineType = selection.HandlerMachineType,
HandlerMachineRawValue = selection.HandlerMachineRawValue,
ArchitectureSelectionReason = selection.Reason,
ActualProbeHostMachineType = PeMachineTypeDetector.Detect(selection.SelectedProbeHostPath).MachineType,
OSArchitecture = RuntimeInformation.OSArchitecture.ToString(),
Is64BitProcess = Environment.Is64BitProcess,
DiagnosticDetails = BuildProbeHostDiagnostics(exitCode, stdout, stderr, requestPath, resultPath)
};
}
private static ContextMenuDeepAnalysisResult BuildInvalidOutputFailure(
int exitCode,
string stdout,
string stderr,
ContextMenuDeepAnalysisRequest request,
string requestPath,
string resultPath)
{
return Failure(
"InvalidProbeHostOutput",
$"ProbeHost returned non-JSON output. ExitCode={exitCode}. Stdout={Excerpt(stdout, 300)} Stderr={Excerpt(stderr, 1000)}",
request) with
{
DiagnosticDetails = BuildProbeHostDiagnostics(exitCode, stdout, stderr, requestPath, resultPath)
};
}
private static string BuildInvalidJsonMessage(
string jsonError,
int exitCode,
string json,
string stderr,
string source,
string sourcePath)
{
return $"ProbeHost returned invalid JSON from {source}. ExitCode={exitCode}. Source={sourcePath}. JsonError={jsonError}. Output={Excerpt(json, 300)} Stderr={Excerpt(stderr, 1000)}";
}
private static string TrimBomAndWhitespace(string value)
{
return (value ?? string.Empty).TrimStart('\uFEFF').Trim();
}
private static string Excerpt(string? value, int maxChars)
{
if (string.IsNullOrEmpty(value))
{
return "<empty>";
}
var normalized = value.Replace("\r", "\\r", StringComparison.Ordinal).Replace("\n", "\\n", StringComparison.Ordinal);
return normalized.Length <= maxChars
? normalized
: normalized[..maxChars] + "...";
}
private static string BuildProbeHostDiagnostics(
int exitCode,
string stdout,
string stderr,
string requestPath,
string resultPath)
{
return $"ExitCode={exitCode} ({FormatExitCodeHex(exitCode)}){Environment.NewLine}"
+ $"RequestPath={requestPath}{Environment.NewLine}"
+ $"ResultPath={resultPath}{Environment.NewLine}"
+ $"Stdout={Excerpt(stdout, 300)}{Environment.NewLine}"
+ $"Stderr={Excerpt(stderr, 1000)}";
}
private static string FormatExitCodeHex(int exitCode) => $"0x{unchecked((uint)exitCode):X8}";
private static string? ExtractProbeHostArchitecture(string stderr)
{
const string marker = "ProcessArchitecture=";
if (string.IsNullOrWhiteSpace(stderr))
{
return null;
}
var index = stderr.IndexOf(marker, StringComparison.OrdinalIgnoreCase);
if (index < 0)
{
return null;
}
var start = index + marker.Length;
var end = stderr.IndexOf(',', start);
return end > start
? stderr[start..end].Trim()
: stderr[start..].Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries).FirstOrDefault()?.Trim();
}
private static async Task<string> TryReadTaskAsync(Task<string>? task)
{
if (task is null)
{
return string.Empty;
}
try
{
return await task.WaitAsync(TimeSpan.FromMilliseconds(500));
}
catch
{
return string.Empty;
}
}
private static void TryDeleteDirectory(string directory)
{
try
{
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
catch
{
}
}
private static void KillProcess(Process process)
{
try
{
if (!process.HasExited)
{
process.Kill(entireProcessTree: true);
}
}
catch
{
}
}
}