From 9e301b901344450841f3ddb41d501e08e8973176 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 11:20:19 +0000 Subject: [PATCH 1/4] Fix ilspycmd -o fallback to read IL from its output directory ilspycmd treats -o as an output directory and writes .il inside it, leaving stdout empty. nildiff passed a file path, so after a successful exit File.Exists(tempOut) was false, the empty stdout was used, and the fallback always produced empty IL while leaking ilspy_out_* directories. Pass a fresh temporary directory, read the input-named IL file from it, and remove the directory recursively after every attempt, including failures and timeouts. FakeDisassembler now emulates the real ilspycmd -o semantics. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0169z7S1N3Vmq8rHkry7EDVa --- CHANGELOG.md | 2 + .../Helpers/FakeDisassemblerProgram.cs | 32 ++++- ...sembleServiceTests.IlspyOutputDirectory.cs | 118 ++++++++++++++++++ ...DisassembleServiceTests.UnitAndPrefetch.cs | 29 +++-- .../Services/DotNetDisassembleServiceTests.cs | 46 +++++-- .../DotNetDisassembleService.Streaming.cs | 51 +++++--- .../DotNetDisassembleService.VersionLabel.cs | 39 ++++-- Services/DotNetDisassembleService.cs | 51 +++++--- doc/DEVELOPER_GUIDE.md | 4 +- 9 files changed, 317 insertions(+), 55 deletions(-) create mode 100644 FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.IlspyOutputDirectory.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c115dd4..3d80ac68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), #### Fixed +- **ilspycmd `-o` fallback reads the IL it actually writes** — `ilspycmd -o` takes an output directory and writes `.il` inside it, but nildiff passed a file path, so the fallback always returned empty IL after a successful exit and left `ilspy_out_*` directories in the temp folder. nildiff now passes a fresh temporary directory, reads the generated `.il` file, and deletes the directory recursively after every attempt, including failures and timeouts. Affected: `Services/DotNetDisassembleService.cs`, `Services/DotNetDisassembleService.Streaming.cs`, `Services/DotNetDisassembleService.VersionLabel.cs`, `FolderDiffIL4DotNet.Tests/Helpers/FakeDisassemblerProgram.cs`. Tests: `DisassembleAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt`, `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt`, `ResolveIlspyOutputFile_ReturnsInputNamedIlFileOnly`, `BuildArgSets_IlspyCommand_PassesTemporaryOutputDirectoryToOutputFlag`, `CleanupTemporaryPathBestEffort_WhenPathIsDirectory_DeletesItRecursivelyWithoutWarning`. - **npm audit CI uses patched brace-expansion** — Updated the 2.x override and lockfile from `2.1.4` to `2.1.7`, resolving the reported denial-of-service vulnerabilities and the transitive `minimatch` finding without adding audit exceptions. - **npm audit CI uses patched js-yaml** — Updated the 3.x override and lockfile to `3.15.2`, resolving `GHSA-2883-xcg3-v3hh` without adding an audit exception. - **Benchmark regression CI compares matching execution environments** — Preserved BenchmarkDotNet host metadata and partitioned trusted history by CPU, core topology, OS, architecture, runtime/SDK, build configuration, and BenchmarkDotNet version. Mixed-host legacy history starts a visible five-sample warmup per environment; warning/failure thresholds, ancestry checks, and trusted publication restrictions remain unchanged. Added regression coverage for environment isolation, invalid host metadata, report combination, and real slowdowns within one environment. @@ -1772,6 +1773,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), #### 修正 +- **ilspycmd の `-o` フォールバックで実際に書き出された IL を読むように修正** — `ilspycmd -o` は出力ディレクトリを受け取り、その中に `<入力名>.il` を書き出しますが、nildiff はファイルパスを渡していたため、このフォールバックは正常終了しても常に空の IL を返し、一時フォルダに `ilspy_out_*` ディレクトリを残していました。新しい一時ディレクトリを渡して生成された `<入力名>.il` ファイルを読み取り、失敗やタイムアウトを含むすべての試行の後にディレクトリを再帰的に削除するようにしました。対象: `Services/DotNetDisassembleService.cs`, `Services/DotNetDisassembleService.Streaming.cs`, `Services/DotNetDisassembleService.VersionLabel.cs`, `FolderDiffIL4DotNet.Tests/Helpers/FakeDisassemblerProgram.cs`。テスト: `DisassembleAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt`, `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt`, `ResolveIlspyOutputFile_ReturnsInputNamedIlFileOnly`, `BuildArgSets_IlspyCommand_PassesTemporaryOutputDirectoryToOutputFlag`, `CleanupTemporaryPathBestEffort_WhenPathIsDirectory_DeletesItRecursivelyWithoutWarning`。 - **npm audit CI で修正版 brace-expansion を使用** — 2.x override と lockfile を `2.1.4` から `2.1.7` に更新し、監査例外を追加せず、報告されたサービス拒否の脆弱性と依存先から波及した `minimatch` の検出を解消しました。 - **npm audit CI で修正版 js-yaml を使用** — 3.x override と lockfile を `3.15.2` に更新し、監査例外を追加せず `GHSA-2883-xcg3-v3hh` を解消しました。 - **ベンチマーク回帰 CI を同一実行環境で比較** — BenchmarkDotNet のホスト情報を保持し、CPU、コア構成、OS、アーキテクチャ、runtime/SDK、ビルド構成、BenchmarkDotNet バージョンごとに信頼済み履歴を分離しました。旧来のホスト混在履歴は環境ごとに明示的な 5 サンプルのウォームアップから開始し、warning/failure 閾値、祖先チェック、信頼済み公開の制約は維持します。環境分離、不正なホスト情報、レポート結合、同一環境内での実際の遅化に回帰テストを追加しました。 diff --git a/FolderDiffIL4DotNet.Tests/Helpers/FakeDisassemblerProgram.cs b/FolderDiffIL4DotNet.Tests/Helpers/FakeDisassemblerProgram.cs index 4eaf033d..19563d4f 100644 --- a/FolderDiffIL4DotNet.Tests/Helpers/FakeDisassemblerProgram.cs +++ b/FolderDiffIL4DotNet.Tests/Helpers/FakeDisassemblerProgram.cs @@ -30,6 +30,14 @@ var failPattern = GetEnv("FAIL_PATTERN"); var failExit = int.TryParse(GetEnv("FAIL_EXIT"), out var fe) ? fe : 90; var counterPath = GetEnv("COUNTER_PATH"); +// Exit code used only when no "-o" is passed (simulates a stdout-mode failure). +// "-o" が無い場合にだけ使う終了コード(stdout モードの失敗を再現)。 +var stdoutModeExit = int.TryParse(GetEnv("STDOUT_EXIT"), out var se) ? se : (int?)null; +// "1" writes no IL at all (an empty environment value cannot be set portably). +// "1" で IL を一切書かない(空文字の環境変数は移植性のある設定ができないため)。 +var emptyOutput = GetEnv("EMPTY_OUTPUT") == "1"; +var stderrOutput = GetEnv("STDERR"); +var sleepMilliseconds = int.TryParse(GetEnv("SLEEP_MS"), out var sm) ? sm : 0; // Handle version flags / バージョンフラグの処理 if (cmdArgs.Any(a => a == "--version" || a == "-v" || a == "-h")) @@ -47,5 +55,27 @@ if (!string.IsNullOrEmpty(failPattern) && cmdArgs.Any(a => a.EndsWith(failPattern, StringComparison.Ordinal))) return failExit; -Console.WriteLine(output); +if (sleepMilliseconds > 0) + Thread.Sleep(sleepMilliseconds); + +if (!string.IsNullOrEmpty(stderrOutput)) + Console.Error.WriteLine(stderrOutput); + +// Emulate ilspycmd: "-o" names an output DIRECTORY and ".il" is written inside it; stdout stays empty. +// ilspycmd を模倣: "-o" は出力ディレクトリを指し、その中に "<入力名>.il" を書き出す。stdout には何も出さない。 +var outputOptionIndex = Array.IndexOf(cmdArgs, "-o"); +if (outputOptionIndex >= 0 && outputOptionIndex + 1 < cmdArgs.Length) +{ + var outputDirectory = cmdArgs[outputOptionIndex + 1]; + Directory.CreateDirectory(outputDirectory); + if (!emptyOutput) + File.WriteAllText(Path.Combine(outputDirectory, Path.GetFileNameWithoutExtension(cmdArgs[^1]) + ".il"), output + Environment.NewLine); + return exit; +} + +if (stdoutModeExit.HasValue) + return stdoutModeExit.Value; + +if (!emptyOutput) + Console.WriteLine(output); return exit; diff --git a/FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.IlspyOutputDirectory.cs b/FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.IlspyOutputDirectory.cs new file mode 100644 index 00000000..3b1835bf --- /dev/null +++ b/FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.IlspyOutputDirectory.cs @@ -0,0 +1,118 @@ +/// +/// Partial class covering ilspycmd -o output-directory handling. +/// ilspycmd の -o 出力ディレクトリ処理を検証するパーシャルクラス。 +/// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; +using FolderDiffIL4DotNet.Services; +using Xunit; + +namespace FolderDiffIL4DotNet.Tests.Services +{ + public sealed partial class DotNetDisassembleServiceTests + { + /// + /// When only ilspycmd's -o mode works, returns the IL written into the output directory and removes that directory. + /// ilspycmd の -o モードだけが成功する場合、 は出力ディレクトリに書き出された IL を返し、そのディレクトリを削除することを検証します。 + /// + [Fact] + public async Task DisassembleAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt() + { + await RunWithIlspyOnlyStdoutFailureAsync("ilspy-o-text", async (service, dllPath) => + { + var (ilText, command) = await service.DisassembleAsync(dllPath); + + Assert.Equal("IL_FROM_ILSPY_OUTPUT_DIRECTORY", ilText.Trim()); + Assert.Contains("ilspycmd", command, StringComparison.OrdinalIgnoreCase); + Assert.Contains(" -o ", command, StringComparison.Ordinal); + }); + } + + /// + /// Same as the text variant, for the line-based pair API used by IL comparison: both sides read IL from the output directory and no directory is left behind. + /// テキスト版と同じ内容を、IL 比較で使う行ベースのペア API で検証します。両側とも出力ディレクトリから IL を読み、ディレクトリは残りません。 + /// + [Fact] + public async Task DisassemblePairAsLinesWithSameDisassemblerAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt() + { + await RunWithIlspyOnlyStdoutFailureAsync("ilspy-o-lines", async (service, dllPath) => + { + var newDllPath = Path.Combine(Path.GetDirectoryName(dllPath)!, "ilspy-o-lines-new.dll"); + await File.WriteAllTextAsync(newDllPath, "dummy-new"); + + var (oldLines, oldCommand, newLines, newCommand) = await service.DisassemblePairAsLinesWithSameDisassemblerAsync(dllPath, newDllPath); + + Assert.Equal(new[] { "IL_FROM_ILSPY_OUTPUT_DIRECTORY" }, oldLines); + Assert.Equal(new[] { "IL_FROM_ILSPY_OUTPUT_DIRECTORY" }, newLines); + Assert.Contains(" -o ", oldCommand, StringComparison.Ordinal); + Assert.Contains(" -o ", newCommand, StringComparison.Ordinal); + }); + } + + /// + /// ilspycmd names the -o output after the input file (Foo.Bar.dll → Foo.Bar.il), so only that file is accepted; a missing directory or a differently named file yields null. + /// ilspycmd は -o の出力を入力ファイル名から付ける(Foo.Bar.dll → Foo.Bar.il)ため、そのファイルだけを受け付け、ディレクトリが無い場合や別名のファイルしか無い場合は null になることを検証します。 + /// + [Fact] + public void ResolveIlspyOutputFile_ReturnsInputNamedIlFileOnly() + { + var method = typeof(DotNetDisassembleService).GetMethod("ResolveIlspyOutputFile", BindingFlags.Static | BindingFlags.NonPublic); + Assert.NotNull(method); + string? Resolve(string directory) => method.Invoke(null, [directory, Path.Combine(_rootDir, "Foo.Bar.dll")]) as string; + + Assert.Null(Resolve(Path.Combine(_rootDir, "resolve-missing"))); + + var otherNameDirectory = Path.Combine(_rootDir, "resolve-other-name"); + Directory.CreateDirectory(otherNameDirectory); + File.WriteAllText(Path.Combine(otherNameDirectory, "Other.il"), "x"); + Assert.Null(Resolve(otherNameDirectory)); + + var expectedDirectory = Path.Combine(_rootDir, "resolve-expected"); + Directory.CreateDirectory(expectedDirectory); + File.WriteAllText(Path.Combine(expectedDirectory, "Other.il"), "x"); + File.WriteAllText(Path.Combine(expectedDirectory, "Foo.Bar.il"), "x"); + Assert.Equal(Path.Combine(expectedDirectory, "Foo.Bar.il"), Resolve(expectedDirectory)); + } + + /// + /// Installs fake tools where only ilspycmd works, and only with -o; asserts no ilspy_out_* path is left in the temp directory. + /// ilspycmd だけが -o 付きでのみ成功する偽ツールを配置し、一時ディレクトリに ilspy_out_* が残らないことを検証します。 + /// + private async Task RunWithIlspyOnlyStdoutFailureAsync(string scenario, Func act) + { + var ilspyOutputPathsBefore = SnapshotIlspyOutputPaths(); + await RunWithFakeToolsAsync(scenario, binDir => + { + InstallFakeTool(binDir, "dotnet-ildasm", prefix => Environment.SetEnvironmentVariable(prefix + "EXIT", "1")); + InstallFakeTool(binDir, "dotnet", prefix => Environment.SetEnvironmentVariable(prefix + "EXIT", "1")); + InstallFakeTool(binDir, "ilspycmd", prefix => + { + Environment.SetEnvironmentVariable(prefix + "VERSION_OUTPUT", "ilspycmd 9.1.0"); + Environment.SetEnvironmentVariable(prefix + "OUTPUT", "IL_FROM_ILSPY_OUTPUT_DIRECTORY"); + Environment.SetEnvironmentVariable(prefix + "STDOUT_EXIT", "70"); + }); + }, async binDir => + { + var service = CreateService(CreateConfig(enableIlCache: false), null); + var dllPath = Path.Combine(_rootDir, scenario + ".dll"); + await File.WriteAllTextAsync(dllPath, "dummy"); + + await act(service, dllPath); + + Assert.Empty(SnapshotIlspyOutputPaths().Except(ilspyOutputPathsBefore)); + }); + } + + /// + /// Returns the ilspy_out_* entries currently in the temp directory, for before/after leak checks. + /// 一時ディレクトリにある ilspy_out_* エントリを返します(前後比較による残留チェック用)。 + /// + private static HashSet SnapshotIlspyOutputPaths() + => new(Directory.EnumerateFileSystemEntries(Path.GetTempPath(), "ilspy_out_*"), StringComparer.Ordinal); + } +} diff --git a/FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.UnitAndPrefetch.cs b/FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.UnitAndPrefetch.cs index d5af7fe2..d3efcfce 100644 --- a/FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.UnitAndPrefetch.cs +++ b/FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.UnitAndPrefetch.cs @@ -256,32 +256,41 @@ public void AreSameDisassemblerVersion_DifferentVersions_ReturnsFalse() Assert.False(result); } + /// + /// ilspycmd treats -o as an output directory, so each -o value is a not-yet-created ilspy_out_* directory path that the arg set also tracks for reading and cleanup. + /// ilspycmd は -o を出力ディレクトリとして扱うため、各 -o の値が未作成の ilspy_out_* ディレクトリパスであり、読み取りと削除のため引数セットでも保持されていることを検証します。 + /// [Fact] [Trait("Category", "Unit")] - public void BuildArgSets_IlspyCommand_IncludesOutputFileArguments() + public void BuildArgSets_IlspyCommand_PassesTemporaryOutputDirectoryToOutputFlag() { - // Tests that ilspycmd arg sets include the -o flag with temp output path. - // ilspycmd の引数セットに -o フラグと一時出力パスが含まれることをテスト。 var method = typeof(DotNetDisassembleService).GetMethod("BuildArgSets", BindingFlags.Static | BindingFlags.NonPublic); Assert.NotNull(method); var argSetsObject = method.Invoke(null, ["ilspycmd", "/tmp/sample.dll", null]); var argSets = Assert.IsAssignableFrom(argSetsObject); - bool hasOutputArg = false; + int outputArgSetCount = 0; foreach (var item in argSets) { var itemType = item.GetType(); - var argsField = itemType.GetField("Item2"); - Assert.NotNull(argsField); - var args = Assert.IsType(argsField.GetValue(item)); - if (Array.IndexOf(args, "-o") >= 0) + var args = Assert.IsType(itemType.GetField("Item2")!.GetValue(item)); + var tempOutDirectory = itemType.GetField("Item3")!.GetValue(item) as string; + var outputFlagIndex = Array.IndexOf(args, "-o"); + if (outputFlagIndex < 0) { - hasOutputArg = true; + Assert.Null(tempOutDirectory); + continue; } + + outputArgSetCount++; + Assert.Equal(tempOutDirectory, args[outputFlagIndex + 1]); + Assert.StartsWith("ilspy_out_", Path.GetFileName(tempOutDirectory), StringComparison.Ordinal); + Assert.Equal(string.Empty, Path.GetExtension(tempOutDirectory)); + Assert.False(Directory.Exists(tempOutDirectory)); } - Assert.True(hasOutputArg, "ilspycmd arg sets should include -o output flag"); + Assert.Equal(2, outputArgSetCount); } } } diff --git a/FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.cs b/FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.cs index a6f10a62..6c646698 100644 --- a/FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.cs +++ b/FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.cs @@ -227,24 +227,27 @@ public void BuildStartDisassemblerToolWarning_WhenCommandContainsInvalidChars_Do Assert.Contains("missing tool", message, StringComparison.Ordinal); } + /// + /// ilspycmd -o writes into a directory, so cleanup removes a directory together with its contents and logs nothing. + /// ilspycmd の -o はディレクトリへ書き出すため、クリーンアップが中身ごとディレクトリを削除し、何もログ出力しないことを検証します。 + /// [Fact] - public void CleanupTemporaryPathBestEffort_WhenDirectoryPathCannotBeDeleted_LogsWarning() + public void CleanupTemporaryPathBestEffort_WhenPathIsDirectory_DeletesItRecursivelyWithoutWarning() { var config = CreateConfig(enableIlCache: false); var logger = new TestLogger(logFileAbsolutePath: "test.log"); var service = new DotNetDisassembleService(config, ilCache: null, _resultLists, logger, _dotNetDisassemblerCache); - var tempDirectory = Path.Combine(_rootDir, "leftover-temp-dir"); + var tempDirectory = Path.Combine(_rootDir, "ilspy-out-temp-dir"); Directory.CreateDirectory(tempDirectory); + File.WriteAllText(Path.Combine(tempDirectory, "sample.il"), ".assembly sample"); var method = typeof(DotNetDisassembleService).GetMethod("CleanupTemporaryPathBestEffort", BindingFlags.Instance | BindingFlags.NonPublic); Assert.NotNull(method); method.Invoke(service, [tempDirectory, "unit test"]); - Assert.Contains(logger.Messages, m => m.Contains("Temporary cleanup left a path behind", StringComparison.Ordinal) - && m.Contains("File=False", StringComparison.Ordinal) - && m.Contains("Directory=True", StringComparison.Ordinal)); - Assert.True(Directory.Exists(tempDirectory)); + Assert.False(Directory.Exists(tempDirectory)); + Assert.Empty(logger.Entries); } [Fact] @@ -559,6 +562,34 @@ private static void InstallFakeTool(string binDir, string toolName, Action + /// Installs fake tools into a scenario-specific bin directory, puts it first on PATH, runs the test body, and restores the environment. + /// シナリオ専用の bin ディレクトリに偽ツールを配置して PATH の先頭に追加し、テスト本体を実行した後に環境を復元します。 + /// + private async Task RunWithFakeToolsAsync(string scenario, Action installTools, Func act) + { + var binDir = Path.Combine(_rootDir, "bin-" + scenario); + Directory.CreateDirectory(binDir); + installTools(binDir); + + var oldPath = Environment.GetEnvironmentVariable("PATH"); + var oldHome = Environment.GetEnvironmentVariable("HOME"); + try + { + Environment.SetEnvironmentVariable("PATH", binDir + Path.PathSeparator + oldPath); + Environment.SetEnvironmentVariable("HOME", _rootDir); + await act(binDir); + } + finally + { + Environment.SetEnvironmentVariable("PATH", oldPath); + Environment.SetEnvironmentVariable("HOME", oldHome); + ClearFakeToolEnvVars("dotnet-ildasm"); + ClearFakeToolEnvVars("dotnet"); + ClearFakeToolEnvVars("ilspycmd"); + } + } + private static string GetEnvPrefix(string toolName) => "FD_FAKE_" + toolName.ToUpperInvariant().Replace("-", "_") + "_"; @@ -572,7 +603,8 @@ private static void ClearFakeToolEnvVars(string toolName) { var prefix = GetEnvPrefix(toolName); foreach (var suffix in new[] { "VERSION_EXIT", "VERSION_OUTPUT", "OUTPUT", "EXIT", - "FAIL_PATTERN", "FAIL_EXIT", "COUNTER_PATH" }) + "FAIL_PATTERN", "FAIL_EXIT", "COUNTER_PATH", + "STDOUT_EXIT", "EMPTY_OUTPUT", "STDERR", "SLEEP_MS" }) { Environment.SetEnvironmentVariable(prefix + suffix, null); } diff --git a/Services/DotNetDisassembleService.Streaming.cs b/Services/DotNetDisassembleService.Streaming.cs index 06546723..3ff4778c 100644 --- a/Services/DotNetDisassembleService.Streaming.cs +++ b/Services/DotNetDisassembleService.Streaming.cs @@ -125,12 +125,39 @@ public sealed partial class DotNetDisassembleService /// /// Tries disassembly with a single argument set, returning IL as lines: cache check, process execution (line-by-line stdout), cache store. + /// The ilspycmd -o temporary output directory is always removed afterwards. /// 1 つの引数セットで逆アセンブルを試行し IL を行リストで返します。キャッシュ事前チェック→行単位プロセス実行→キャッシュ格納。 + /// ilspycmd の -o 一時出力ディレクトリは終了後に必ず削除します。 /// private async Task<(bool Success, IReadOnlyList? IlLines, string? Label, Exception? Error)> TryDisassembleWithArgumentsToLines( string disassembleCommand, string dotNetAssemblyFileAbsolutePath, - (string workingDirectory, string[] args, string? tempOut) argset, + (string workingDirectory, string[] args, string? tempOutDirectory) argset, + bool allowCache, + bool recordUsage) + { + try + { + return await TryDisassembleWithArgumentsToLinesCore(disassembleCommand, dotNetAssemblyFileAbsolutePath, argset, allowCache, recordUsage); + } + finally + { + // Remove the ilspycmd -o directory on every outcome (success, failure, timeout). + // ilspycmd の -o ディレクトリは成功・失敗・タイムアウトのいずれでも削除する。 + CleanupTemporaryPathBestEffort(argset.tempOutDirectory, "ilspy temporary output directory"); + } + } + + /// + /// Core of : cache check, process execution, and cache store. + /// Temporary output cleanup is left to the caller's finally. + /// の本体。キャッシュ確認→プロセス実行→キャッシュ格納を行います。 + /// 一時出力の削除は呼び出し元の finally が担当します。 + /// + private async Task<(bool Success, IReadOnlyList? IlLines, string? Label, Exception? Error)> TryDisassembleWithArgumentsToLinesCore( + string disassembleCommand, + string dotNetAssemblyFileAbsolutePath, + (string workingDirectory, string[] args, string? tempOutDirectory) argset, bool allowCache, bool recordUsage) { @@ -187,24 +214,20 @@ public sealed partial class DotNetDisassembleService /// /// Reads IL lines after a successful process exit. - /// ilspycmd reads from a temp file; other tools use the stdout lines already collected. - /// プロセス正常終了後の IL 行を取得。ilspycmd は一時ファイルから、他ツールは収集済み stdout 行を使用。 + /// ilspycmd with -o reads the IL file from the output directory (empty when none was written); other cases use the stdout lines already collected. + /// プロセス正常終了後の IL 行を取得。-o 付き ilspycmd は出力ディレクトリ内の IL ファイルから読み取り(書き出されていなければ空)、それ以外は収集済み stdout 行を使用。 /// - private async Task> ReadIlLinesAfterSuccessAsync( + private static async Task> ReadIlLinesAfterSuccessAsync( bool isIlspy, - (string workingDirectory, string[] args, string? tempOut) argset, + (string workingDirectory, string[] args, string? tempOutDirectory) argset, List stdoutLines) { - if (isIlspy && !string.IsNullOrEmpty(argset.tempOut) && File.Exists(argset.tempOut)) + if (isIlspy && !string.IsNullOrEmpty(argset.tempOutDirectory)) { - try - { - return StripDisassemblerStdoutNoticeLines(await File.ReadAllLinesAsync(argset.tempOut)); - } - finally - { - CleanupTemporaryPathBestEffort(argset.tempOut, "ilspy temporary output"); - } + var outputFileAbsolutePath = ResolveIlspyOutputFile(argset.tempOutDirectory, argset.args[^1]); + return outputFileAbsolutePath == null + ? new List() + : StripDisassemblerStdoutNoticeLines(await File.ReadAllLinesAsync(outputFileAbsolutePath)); } return StripDisassemblerStdoutNoticeLines(stdoutLines); } diff --git a/Services/DotNetDisassembleService.VersionLabel.cs b/Services/DotNetDisassembleService.VersionLabel.cs index c99b60f6..210dd352 100644 --- a/Services/DotNetDisassembleService.VersionLabel.cs +++ b/Services/DotNetDisassembleService.VersionLabel.cs @@ -51,6 +51,10 @@ public sealed partial class DotNetDisassembleService return null; } + /// + /// Deletes a temporary file or directory (recursively) on a best-effort basis, logging a warning when the path remains or deletion fails. + /// 一時ファイルまたはディレクトリ(再帰的)をベストエフォートで削除し、パスが残った場合や削除に失敗した場合は警告をログ出力します。 + /// private void CleanupTemporaryPathBestEffort(string? temporaryPath, string purpose) { if (string.IsNullOrWhiteSpace(temporaryPath)) @@ -60,7 +64,16 @@ private void CleanupTemporaryPathBestEffort(string? temporaryPath, string purpos try { - FileSystemUtility.DeleteFileSilent(temporaryPath); + // ilspycmd -o output is a directory; everything else is a single file. + // ilspycmd の -o 出力先はディレクトリ、それ以外は単一ファイル。 + if (Directory.Exists(temporaryPath)) + { + Directory.Delete(temporaryPath, recursive: true); + } + else + { + FileSystemUtility.DeleteFileSilent(temporaryPath); + } if (File.Exists(temporaryPath) || Directory.Exists(temporaryPath)) { _logger.LogMessage( @@ -96,16 +109,18 @@ private static string DescribePathStateForDiagnostics(string path, Exception? ex /// /// Enumerates argument sets to try, based on the command type. + /// For ilspycmd, tempOutDirectory is the -o output directory (ilspycmd treats -o as a directory and writes <name>.il inside it). /// コマンド種別に応じた試行用の引数セットを列挙します。 + /// ilspycmd の tempOutDirectory は -o の出力ディレクトリです(ilspycmd は -o をディレクトリとして扱い、その中に <name>.il を書き出します)。 /// - private static IEnumerable<(string workingDirectory, string[] args, string? tempOut)> BuildArgSets(string disassembleCommand, string disassemblerFileAbsolutePath, string? tempAsciiPath) + private static IEnumerable<(string workingDirectory, string[] args, string? tempOutDirectory)> BuildArgSets(string disassembleCommand, string disassemblerFileAbsolutePath, string? tempAsciiPath) { var disassemblerFileDirectoryAbsolutePath = Path.GetDirectoryName(disassemblerFileAbsolutePath) ?? Environment.CurrentDirectory; var disassemblerFileNameOnly = Path.GetFileName(disassemblerFileAbsolutePath); var isDotnetMuxer = IsDotnetMuxer(disassembleCommand); var isIlspy = IsIlspyCommand(disassembleCommand); - var argSets = new List<(string workingDirectory, string[] args, string? tempOut)>(); + var argSets = new List<(string workingDirectory, string[] args, string? tempOutDirectory)>(); if (!isIlspy) { argSets.Add((disassemblerFileDirectoryAbsolutePath, isDotnetMuxer ? [Constants.ILDASM_LABEL, disassemblerFileNameOnly] : [disassemblerFileNameOnly], null)); @@ -123,20 +138,30 @@ private static string DescribePathStateForDiagnostics(string path, Exception? ex { argSets.Add((Environment.CurrentDirectory, [ILSPY_FLAG_IL, tempAsciiPath], null)); } - static string MakeTempOut() => Path.Combine(Path.GetTempPath(), $"ilspy_out_{Guid.NewGuid():N}.il"); - var out1 = MakeTempOut(); + static string MakeTempOutDirectory() => Path.Combine(Path.GetTempPath(), $"ilspy_out_{Guid.NewGuid():N}"); + var out1 = MakeTempOutDirectory(); argSets.Add((disassemblerFileDirectoryAbsolutePath, [ILSPY_FLAG_IL, ILSPY_FLAG_OUTPUT, out1, disassemblerFileNameOnly], out1)); - var out2 = MakeTempOut(); + var out2 = MakeTempOutDirectory(); argSets.Add((Environment.CurrentDirectory, [ILSPY_FLAG_IL, ILSPY_FLAG_OUTPUT, out2, disassemblerFileAbsolutePath], out2)); if (!string.IsNullOrEmpty(tempAsciiPath)) { - var out3 = MakeTempOut(); + var out3 = MakeTempOutDirectory(); argSets.Add((Environment.CurrentDirectory, [ILSPY_FLAG_IL, ILSPY_FLAG_OUTPUT, out3, tempAsciiPath], out3)); } } return argSets; } + /// + /// Returns the IL file ilspycmd writes into its -o output directory, <input file name without extension>.il, or null when it does not exist. + /// ilspycmd が -o の出力ディレクトリに書き出す IL ファイル <入力ファイル名(拡張子なし)>.il を返し、存在しない場合は null を返します。 + /// + private static string? ResolveIlspyOutputFile(string outputDirectoryAbsolutePath, string inputAssemblyPath) + { + var outputFileAbsolutePath = Path.Combine(outputDirectoryAbsolutePath, Path.GetFileNameWithoutExtension(inputAssemblyPath) + ".il"); + return File.Exists(outputFileAbsolutePath) ? outputFileAbsolutePath : null; + } + /// /// Appends the tool version to the base label. Returns the base label as-is on failure. /// ベースラベルにツールバージョンを付加して返します。取得失敗時はそのまま返します。 diff --git a/Services/DotNetDisassembleService.cs b/Services/DotNetDisassembleService.cs index 1ef50935..663c706b 100644 --- a/Services/DotNetDisassembleService.cs +++ b/Services/DotNetDisassembleService.cs @@ -250,12 +250,39 @@ public Task PrefetchIlCacheAsync(IEnumerable dotNetAssemblyFilesAbsolute /// /// Tries disassembly with a single argument set: cache check, process execution, cache store. + /// The ilspycmd -o temporary output directory is always removed afterwards. /// 1つの引数セットで逆アセンブルを試行します。キャッシュ事前チェック→プロセス実行→キャッシュ格納までを担当。 + /// ilspycmd の -o 一時出力ディレクトリは終了後に必ず削除します。 /// private async Task<(bool Success, string? IlText, string? DisassembleCommandAndItsVersionWithArguments, Exception? Error)> TryDisassembleWithArguments( string disassembleCommand, string dotNetAssemblyFileAbsolutePath, - (string workingDirectory, string[] args, string? tempOut) argset, + (string workingDirectory, string[] args, string? tempOutDirectory) argset, + bool allowCache, + bool recordUsage) + { + try + { + return await TryDisassembleWithArgumentsCore(disassembleCommand, dotNetAssemblyFileAbsolutePath, argset, allowCache, recordUsage); + } + finally + { + // Remove the ilspycmd -o directory on every outcome (success, failure, timeout). + // ilspycmd の -o ディレクトリは成功・失敗・タイムアウトのいずれでも削除する。 + CleanupTemporaryPathBestEffort(argset.tempOutDirectory, "ilspy temporary output directory"); + } + } + + /// + /// Core of : cache check, process execution, and cache store. + /// Temporary output cleanup is left to the caller's finally. + /// の本体。キャッシュ確認→プロセス実行→キャッシュ格納を行います。 + /// 一時出力の削除は呼び出し元の finally が担当します。 + /// + private async Task<(bool Success, string? IlText, string? DisassembleCommandAndItsVersionWithArguments, Exception? Error)> TryDisassembleWithArgumentsCore( + string disassembleCommand, + string dotNetAssemblyFileAbsolutePath, + (string workingDirectory, string[] args, string? tempOutDirectory) argset, bool allowCache, bool recordUsage) { @@ -357,25 +384,21 @@ public Task PrefetchIlCacheAsync(IEnumerable dotNetAssemblyFilesAbsolute /// /// Reads IL text after a successful process exit. - /// ilspycmd reads from a temp file (deleted after read); other tools use stdout. + /// ilspycmd with -o reads the IL file from the output directory (empty when none was written); other cases use stdout. /// プロセス正常終了後の IL テキストを取得します。 - /// ilspycmd は一時ファイルから読み取り、その他は stdout を使用します。 + /// -o 付き ilspycmd は出力ディレクトリ内の IL ファイルから読み取り(書き出されていなければ空)、それ以外は stdout を使用します。 /// - private async Task ReadIlTextAfterSuccessAsync( + private static async Task ReadIlTextAfterSuccessAsync( bool isIlspy, - (string workingDirectory, string[] args, string? tempOut) argset, + (string workingDirectory, string[] args, string? tempOutDirectory) argset, string stdout) { - if (isIlspy && !string.IsNullOrEmpty(argset.tempOut) && File.Exists(argset.tempOut)) + if (isIlspy && !string.IsNullOrEmpty(argset.tempOutDirectory)) { - try - { - return StripDisassemblerStdoutNotices(await File.ReadAllTextAsync(argset.tempOut)); - } - finally - { - CleanupTemporaryPathBestEffort(argset.tempOut, "ilspy temporary output"); - } + var outputFileAbsolutePath = ResolveIlspyOutputFile(argset.tempOutDirectory, argset.args[^1]); + return outputFileAbsolutePath == null + ? string.Empty + : StripDisassemblerStdoutNotices(await File.ReadAllTextAsync(outputFileAbsolutePath)); } return StripDisassemblerStdoutNotices(stdout ?? string.Empty); } diff --git a/doc/DEVELOPER_GUIDE.md b/doc/DEVELOPER_GUIDE.md index 3a89b0e2..c906cce8 100644 --- a/doc/DEVELOPER_GUIDE.md +++ b/doc/DEVELOPER_GUIDE.md @@ -574,7 +574,7 @@ Failure handling: - `FilesAreEqualAsync(...)` also treats [`DirectoryNotFoundException`](https://learn.microsoft.com/en-us/dotnet/api/system.io.directorynotfoundexception?view=net-8.0), [`IOException`](https://learn.microsoft.com/en-us/dotnet/api/system.io.ioexception?view=net-8.0), [`UnauthorizedAccessException`](https://learn.microsoft.com/en-us/dotnet/api/system.unauthorizedaccessexception?view=net-8.0), and [`NotSupportedException`](https://learn.microsoft.com/en-us/dotnet/api/system.notsupportedexception?view=net-8.0) as expected runtime failures: it logs them with both old/new absolute paths and rethrows without changing the exception type. - Other unexpected exceptions are logged from inside `FilesAreEqualAsync(...)` with separate "unexpected error" wording and then rethrown to the caller. - `PrecomputeIlCachesAsync()`, disk-cache eviction cleanup, and post-write read-only protection are best-effort operations. They log warnings and continue because the main comparison result or already-written report remains usable. -- Temporary ASCII copies and ilspy temp-output files created by [`DotNetDisassembleService`](../Services/DotNetDisassembleService.cs) are also cleaned up on a best-effort basis. If deletion leaves the path behind or even the existence probe fails recoverably, the service logs a warning rather than changing the comparison result. +- Temporary ASCII copies and ilspy temp-output directories created by [`DotNetDisassembleService`](../Services/DotNetDisassembleService.cs) are also cleaned up on a best-effort basis. `ilspycmd -o` takes an output directory and writes `.il` inside it, so the service passes a fresh `ilspy_out_` directory, reads the IL file from it, and removes the directory recursively after every attempt, including failures and timeouts. If deletion leaves the path behind or even the existence probe fails recoverably, the service logs a warning rather than changing the comparison result. - **Use exception filters to consolidate identical catch blocks** — When multiple `catch` blocks perform the same action (e.g. all call `CreateFailureResult` or all log the same warning), merge them with an exception filter (`catch (Exception ex) when (ex is X or Y or Z)`). This reduces code duplication without changing runtime semantics. - Even when you need to add more context, do not wrap the original exception in a new generic [`Exception`](https://learn.microsoft.com/en-us/dotnet/api/system.exception?view=net-8.0). Log the original exception and use `throw;` so the original exception type and stack trace are preserved. @@ -1557,7 +1557,7 @@ flowchart TD - `FilesAreEqualAsync(...)` では、[`DirectoryNotFoundException`](https://learn.microsoft.com/ja-jp/dotnet/api/system.io.directorynotfoundexception?view=net-8.0)、[`IOException`](https://learn.microsoft.com/ja-jp/dotnet/api/system.io.ioexception?view=net-8.0)、[`UnauthorizedAccessException`](https://learn.microsoft.com/ja-jp/dotnet/api/system.unauthorizedaccessexception?view=net-8.0)、[`NotSupportedException`](https://learn.microsoft.com/ja-jp/dotnet/api/system.notsupportedexception?view=net-8.0) も想定される実行時失敗として扱い、old/new 両方の絶対パスを含む error ログを出したうえで例外型を変えずに再送出します。 - それ以外の予期しない例外は、`FilesAreEqualAsync(...)` の中で old/new 両方の絶対パスを含む "unexpected error" ログを出力したうえで、呼び出し元へ再送出されます。 - `PrecomputeIlCachesAsync()`、ディスクキャッシュ退避時の削除、書き込み後の読み取り専用化は best-effort です。比較結果や生成済みレポートは利用できるため、warning を記録して継続します。 -- [`DotNetDisassembleService`](../Services/DotNetDisassembleService.cs) が生成する一時 ASCII コピーや ilspy 用 temp 出力も best-effort で cleanup されます。削除後もパスが残る場合や、存在確認自体が recoverable に失敗した場合は、比較結果を変えず warning のみを残します。 +- [`DotNetDisassembleService`](../Services/DotNetDisassembleService.cs) が生成する一時 ASCII コピーや ilspy 用 temp 出力ディレクトリも best-effort で cleanup されます。`ilspycmd -o` は出力ディレクトリを受け取り、その中に `<入力名>.il` を書き出すため、サービスは新しい `ilspy_out_` ディレクトリを渡して IL ファイルを読み取り、失敗やタイムアウトを含むすべての試行の後にディレクトリを再帰的に削除します。削除後もパスが残る場合や、存在確認自体が recoverable に失敗した場合は、比較結果を変えず warning のみを残します。 - 例外に補足情報を付けたい場合も、汎用 [`Exception`](https://learn.microsoft.com/ja-jp/dotnet/api/system.exception?view=net-8.0) へ包み直すのではなく、元の例外をログに出したうえで `throw;` してください。元の例外型とスタックトレースを保つためです。 避けたい例: From 1d84e6352fb1ef0d4fee6487b237849f7dc2c989 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 11:20:58 +0000 Subject: [PATCH 2/4] Treat disassembler runs that exit 0 without IL as failures A run that exited 0 but produced no IL was accepted as successful empty IL. That skipped the remaining argument sets and disassemblers, so the IL comparison retried the same deterministic empty result until its retry limit and failed, with nothing explaining why. Now such a run counts toward the failure blacklist, logs a console warning with the command, file, ilspycmd output directory (noting "(no IL file found)" when ilspycmd wrote no IL file), and stderr, and falls through to the next argument set or disassembler. An IL cache hit that holds only disassembler notices is removed via the new ILCache.RemoveIL and regenerated instead of becoming empty IL. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0169z7S1N3Vmq8rHkry7EDVa --- CHANGELOG.md | 2 + ...tNetDisassembleServiceTests.EmptyOutput.cs | 226 ++++++++++++++++++ Services/Caching/ILCache.cs | 11 + ...otNetDisassembleService.OutputSanitizer.cs | 58 ++++- .../DotNetDisassembleService.Streaming.cs | 18 +- Services/DotNetDisassembleService.cs | 58 ++++- doc/DEVELOPER_GUIDE.md | 4 +- doc/TROUBLESHOOTING.md | 2 + 8 files changed, 365 insertions(+), 14 deletions(-) create mode 100644 FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.EmptyOutput.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d80ac68..c3c0bfe7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), #### Fixed - **ilspycmd `-o` fallback reads the IL it actually writes** — `ilspycmd -o` takes an output directory and writes `.il` inside it, but nildiff passed a file path, so the fallback always returned empty IL after a successful exit and left `ilspy_out_*` directories in the temp folder. nildiff now passes a fresh temporary directory, reads the generated `.il` file, and deletes the directory recursively after every attempt, including failures and timeouts. Affected: `Services/DotNetDisassembleService.cs`, `Services/DotNetDisassembleService.Streaming.cs`, `Services/DotNetDisassembleService.VersionLabel.cs`, `FolderDiffIL4DotNet.Tests/Helpers/FakeDisassemblerProgram.cs`. Tests: `DisassembleAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt`, `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt`, `ResolveIlspyOutputFile_ReturnsInputNamedIlFileOnly`, `BuildArgSets_IlspyCommand_PassesTemporaryOutputDirectoryToOutputFlag`, `CleanupTemporaryPathBestEffort_WhenPathIsDirectory_DeletesItRecursivelyWithoutWarning`. +- **Disassembler runs that exit 0 without IL are failures** — Such runs were accepted as successful empty IL, which skipped the remaining argument sets and disassemblers and made IL comparison fail after its raw-disassembly retries. They now count toward the disassembler failure blacklist, log a console warning with the command, file, ilspycmd output directory (marked `(no IL file found)` when ilspycmd wrote no IL file), and stderr, and continue with the next argument set or disassembler. IL cache hits that contain only disassembler notices are removed and regenerated instead of becoming empty IL. Added `ILCache.RemoveIL`. Affected: `Services/DotNetDisassembleService.cs`, `Services/DotNetDisassembleService.Streaming.cs`, `Services/DotNetDisassembleService.OutputSanitizer.cs`, `Services/Caching/ILCache.cs`, `doc/TROUBLESHOOTING.md`. Tests: `DisassembleAsync_WhenPrimaryToolExitsZeroWithoutIl_LogsStderrAndFallsBackToNextTool`, `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenPrimaryToolExitsZeroWithoutIl_LogsStderrAndFallsBackToNextTool`, `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenEveryToolExitsZeroWithoutIl_ThrowsInsteadOfReturningEmptyIl`, `DisassembleAsync_WhenCachedIlContainsOnlyToolNotices_RemovesEntryAndRegeneratesIl`, `ILCacheRemoveIL_RemovesMemoryAndDiskEntries`, `ContainsIlContent_DetectsAnyLineThatIsNeitherBlankNorToolNotice`. - **npm audit CI uses patched brace-expansion** — Updated the 2.x override and lockfile from `2.1.4` to `2.1.7`, resolving the reported denial-of-service vulnerabilities and the transitive `minimatch` finding without adding audit exceptions. - **npm audit CI uses patched js-yaml** — Updated the 3.x override and lockfile to `3.15.2`, resolving `GHSA-2883-xcg3-v3hh` without adding an audit exception. - **Benchmark regression CI compares matching execution environments** — Preserved BenchmarkDotNet host metadata and partitioned trusted history by CPU, core topology, OS, architecture, runtime/SDK, build configuration, and BenchmarkDotNet version. Mixed-host legacy history starts a visible five-sample warmup per environment; warning/failure thresholds, ancestry checks, and trusted publication restrictions remain unchanged. Added regression coverage for environment isolation, invalid host metadata, report combination, and real slowdowns within one environment. @@ -1774,6 +1775,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), #### 修正 - **ilspycmd の `-o` フォールバックで実際に書き出された IL を読むように修正** — `ilspycmd -o` は出力ディレクトリを受け取り、その中に `<入力名>.il` を書き出しますが、nildiff はファイルパスを渡していたため、このフォールバックは正常終了しても常に空の IL を返し、一時フォルダに `ilspy_out_*` ディレクトリを残していました。新しい一時ディレクトリを渡して生成された `<入力名>.il` ファイルを読み取り、失敗やタイムアウトを含むすべての試行の後にディレクトリを再帰的に削除するようにしました。対象: `Services/DotNetDisassembleService.cs`, `Services/DotNetDisassembleService.Streaming.cs`, `Services/DotNetDisassembleService.VersionLabel.cs`, `FolderDiffIL4DotNet.Tests/Helpers/FakeDisassemblerProgram.cs`。テスト: `DisassembleAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt`, `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt`, `ResolveIlspyOutputFile_ReturnsInputNamedIlFileOnly`, `BuildArgSets_IlspyCommand_PassesTemporaryOutputDirectoryToOutputFlag`, `CleanupTemporaryPathBestEffort_WhenPathIsDirectory_DeletesItRecursivelyWithoutWarning`。 +- **終了コード 0 で IL を出さない逆アセンブラ実行を失敗として扱うように修正** — このような実行は空の IL として成功扱いされていたため、残りの引数セットや逆アセンブラが試されず、IL 比較は raw 逆アセンブルの再試行後に失敗していました。逆アセンブラ失敗のブラックリスト計数に含め、コマンド、ファイル、ilspycmd の出力ディレクトリ(ilspycmd が IL ファイルを書かなかった場合は `(no IL file found)` を付記)、stderr を含む警告をコンソールに出力したうえで、次の引数セットまたは逆アセンブラへ進むようにしました。逆アセンブラの通知行だけを含む IL キャッシュヒットは、空の IL にせず削除して再生成します。`ILCache.RemoveIL` を追加しました。対象: `Services/DotNetDisassembleService.cs`, `Services/DotNetDisassembleService.Streaming.cs`, `Services/DotNetDisassembleService.OutputSanitizer.cs`, `Services/Caching/ILCache.cs`, `doc/TROUBLESHOOTING.md`。テスト: `DisassembleAsync_WhenPrimaryToolExitsZeroWithoutIl_LogsStderrAndFallsBackToNextTool`, `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenPrimaryToolExitsZeroWithoutIl_LogsStderrAndFallsBackToNextTool`, `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenEveryToolExitsZeroWithoutIl_ThrowsInsteadOfReturningEmptyIl`, `DisassembleAsync_WhenCachedIlContainsOnlyToolNotices_RemovesEntryAndRegeneratesIl`, `ILCacheRemoveIL_RemovesMemoryAndDiskEntries`, `ContainsIlContent_DetectsAnyLineThatIsNeitherBlankNorToolNotice`。 - **npm audit CI で修正版 brace-expansion を使用** — 2.x override と lockfile を `2.1.4` から `2.1.7` に更新し、監査例外を追加せず、報告されたサービス拒否の脆弱性と依存先から波及した `minimatch` の検出を解消しました。 - **npm audit CI で修正版 js-yaml を使用** — 3.x override と lockfile を `3.15.2` に更新し、監査例外を追加せず `GHSA-2883-xcg3-v3hh` を解消しました。 - **ベンチマーク回帰 CI を同一実行環境で比較** — BenchmarkDotNet のホスト情報を保持し、CPU、コア構成、OS、アーキテクチャ、runtime/SDK、ビルド構成、BenchmarkDotNet バージョンごとに信頼済み履歴を分離しました。旧来のホスト混在履歴は環境ごとに明示的な 5 サンプルのウォームアップから開始し、warning/failure 閾値、祖先チェック、信頼済み公開の制約は維持します。環境分離、不正なホスト情報、レポート結合、同一環境内での実際の遅化に回帰テストを追加しました。 diff --git a/FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.EmptyOutput.cs b/FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.EmptyOutput.cs new file mode 100644 index 00000000..eb00a35c --- /dev/null +++ b/FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.EmptyOutput.cs @@ -0,0 +1,226 @@ +/// +/// Partial class covering disassembler runs that exit 0 without IL and cache entries that contain no IL. +/// 終了コード 0 で IL を出さない逆アセンブラ実行と、IL を含まないキャッシュエントリを検証するパーシャルクラス。 +/// + +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using FolderDiffIL4DotNet.Common; +using FolderDiffIL4DotNet.Services; +using FolderDiffIL4DotNet.Services.Caching; +using FolderDiffIL4DotNet.Tests.Helpers; +using Xunit; + +namespace FolderDiffIL4DotNet.Tests.Services +{ + public sealed partial class DotNetDisassembleServiceTests + { + private const string EMPTY_IL_STDERR = "EMPTY_IL_STDERR_DETAIL"; + private const string NO_IL_WARNING_FRAGMENT = "exited with code 0 but produced no IL"; + + /// + /// A primary tool that exits 0 without IL is treated as a failure: a console warning with its stderr is logged and falls back to ilspycmd. + /// IL を出さずに終了コード 0 で終わる優先ツールは失敗として扱われ、stderr 付きの警告がコンソールに出力されたうえで が ilspycmd へフォールバックすることを検証します。 + /// + [Fact] + public async Task DisassembleAsync_WhenPrimaryToolExitsZeroWithoutIl_LogsStderrAndFallsBackToNextTool() + { + var logger = new TestLogger(); + await RunWithFakeToolsAsync("empty-fallback-text", ConfigureEmptyDotnetIldasmAndWorkingIlspy, async binDir => + { + var service = new DotNetDisassembleService(CreateConfig(enableIlCache: false), ilCache: null, _resultLists, logger, _dotNetDisassemblerCache); + var dllPath = Path.Combine(_rootDir, "empty-fallback-text.dll"); + await File.WriteAllTextAsync(dllPath, "dummy"); + + var (ilText, command) = await service.DisassembleAsync(dllPath); + + Assert.Equal("IL_FROM_ILSPY", ilText.Trim()); + Assert.Contains("ilspycmd", command, StringComparison.OrdinalIgnoreCase); + AssertNoIlWarning(logger, dllPath); + }); + } + + /// + /// Same as the text variant, for the line-based pair API used by IL comparison: both sides fall back to ilspycmd after the warning. + /// テキスト版と同じ内容を、IL 比較で使う行ベースのペア API で検証します。警告の後、両側とも ilspycmd へフォールバックします。 + /// + [Fact] + public async Task DisassemblePairAsLinesWithSameDisassemblerAsync_WhenPrimaryToolExitsZeroWithoutIl_LogsStderrAndFallsBackToNextTool() + { + var logger = new TestLogger(); + await RunWithFakeToolsAsync("empty-fallback-lines", ConfigureEmptyDotnetIldasmAndWorkingIlspy, async binDir => + { + var service = new DotNetDisassembleService(CreateConfig(enableIlCache: false), ilCache: null, _resultLists, logger, _dotNetDisassemblerCache); + var oldDll = Path.Combine(_rootDir, "empty-fallback-old.dll"); + var newDll = Path.Combine(_rootDir, "empty-fallback-new.dll"); + await File.WriteAllTextAsync(oldDll, "dummy-old"); + await File.WriteAllTextAsync(newDll, "dummy-new"); + + var (oldLines, oldCommand, newLines, newCommand) = await service.DisassemblePairAsLinesWithSameDisassemblerAsync(oldDll, newDll); + + Assert.Equal(new[] { "IL_FROM_ILSPY" }, oldLines); + Assert.Equal(new[] { "IL_FROM_ILSPY" }, newLines); + Assert.Contains("ilspycmd", oldCommand, StringComparison.OrdinalIgnoreCase); + Assert.Contains("ilspycmd", newCommand, StringComparison.OrdinalIgnoreCase); + AssertNoIlWarning(logger, oldDll); + }); + } + + /// + /// When every tool exits 0 without IL, the pair API throws instead of returning empty IL; the ilspycmd -o warning reports the output directory with (no IL file found), and no ilspy_out_* path is left behind. + /// すべてのツールが IL を出さずに終了コード 0 で終わる場合、ペア API は空の IL を返さず例外を投げること、ilspycmd の -o の警告が出力ディレクトリと (no IL file found) を報告すること、ilspy_out_* が残らないことを検証します。 + /// + [Fact] + public async Task DisassemblePairAsLinesWithSameDisassemblerAsync_WhenEveryToolExitsZeroWithoutIl_ThrowsInsteadOfReturningEmptyIl() + { + var logger = new TestLogger(); + var ilspyOutputPathsBefore = SnapshotIlspyOutputPaths(); + await RunWithFakeToolsAsync("empty-everywhere", binDir => + { + InstallFakeTool(binDir, "dotnet-ildasm", prefix => Environment.SetEnvironmentVariable(prefix + "EMPTY_OUTPUT", "1")); + InstallFakeTool(binDir, "dotnet", prefix => Environment.SetEnvironmentVariable(prefix + "EXIT", "1")); + // ilspycmd writes nothing to stdout and creates the -o directory without an IL file. + // ilspycmd は stdout に何も出さず、-o ディレクトリは作るが IL ファイルは書かない。 + InstallFakeTool(binDir, "ilspycmd", prefix => + { + Environment.SetEnvironmentVariable(prefix + "VERSION_OUTPUT", "ilspycmd 9.1.0"); + Environment.SetEnvironmentVariable(prefix + "EMPTY_OUTPUT", "1"); + }); + }, async binDir => + { + var service = new DotNetDisassembleService(CreateConfig(enableIlCache: false), ilCache: null, _resultLists, logger, _dotNetDisassemblerCache); + var oldDll = Path.Combine(_rootDir, "empty-everywhere-old.dll"); + var newDll = Path.Combine(_rootDir, "empty-everywhere-new.dll"); + await File.WriteAllTextAsync(oldDll, "dummy-old"); + await File.WriteAllTextAsync(newDll, "dummy-new"); + + await Assert.ThrowsAsync( + () => service.DisassemblePairAsLinesWithSameDisassemblerAsync(oldDll, newDll)); + + Assert.Contains(logger.Entries, entry => entry.Message.Contains(NO_IL_WARNING_FRAGMENT, StringComparison.Ordinal) + && entry.Message.Contains("OutputDirectory:", StringComparison.Ordinal) + && entry.Message.Contains("(no IL file found)", StringComparison.Ordinal) + && entry.Message.Contains(" -o ", StringComparison.Ordinal)); + Assert.Empty(SnapshotIlspyOutputPaths().Except(ilspyOutputPathsBefore)); + }); + } + + /// + /// An IL cache entry that holds only tool notices is not returned as empty IL: it is removed with a console warning, the IL is regenerated by the tool, and the cache then holds the regenerated IL. + /// ツール通知行だけを含む IL キャッシュエントリは空の IL として返されず、コンソール警告とともに削除され、ツールで IL が再生成されて、キャッシュには再生成後の IL が入ることを検証します。 + /// + [Fact] + public async Task DisassembleAsync_WhenCachedIlContainsOnlyToolNotices_RemovesEntryAndRegeneratesIl() + { + var logger = new TestLogger(); + var counterPath = Path.Combine(_rootDir, "notice-cache-counter.txt"); + await RunWithFakeToolsAsync("notice-cache", binDir => + { + InstallFakeTool(binDir, "dotnet-ildasm", prefix => + { + Environment.SetEnvironmentVariable(prefix + "VERSION_OUTPUT", "1.2.3"); + Environment.SetEnvironmentVariable(prefix + "OUTPUT", "IL_REGENERATED"); + Environment.SetEnvironmentVariable(prefix + "COUNTER_PATH", counterPath); + }); + InstallFakeTool(binDir, "dotnet", prefix => Environment.SetEnvironmentVariable(prefix + "EXIT", "1")); + InstallFakeTool(binDir, "ilspycmd", prefix => Environment.SetEnvironmentVariable(prefix + "EXIT", "1")); + }, async binDir => + { + var ilCache = new ILCache(Path.Combine(_rootDir, "notice-cache-dir"), logger); + var service = new DotNetDisassembleService(CreateConfig(enableIlCache: true), ilCache, _resultLists, logger, _dotNetDisassemblerCache); + var dllPath = Path.Combine(_rootDir, "notice-cache.dll"); + await File.WriteAllTextAsync(dllPath, "dummy"); + + SeedDisassemblerVersionCache(Constants.DOTNET_ILDASM, "1.2.3"); + var label = $"{Constants.DOTNET_ILDASM} {Path.GetFileName(dllPath)} (version: 1.2.3)"; + await ilCache.SetILAsync(dllPath, label, + "You are not using the latest version of the tool, please update.\nLatest version is '9.1.0.7988' (yours is '8.2.0.7535')."); + + var (ilText, command) = await service.DisassembleAsync(dllPath); + + Assert.Equal("IL_REGENERATED", ilText.Trim()); + Assert.Equal(label, command); + Assert.True(File.Exists(counterPath)); + Assert.Contains(logger.Entries, entry => entry.LogLevel == AppLogLevel.Warning + && entry.ShouldOutputMessageToConsole + && entry.Message.Contains("Ignored cached IL", StringComparison.Ordinal) + && entry.Message.Contains(dllPath, StringComparison.Ordinal)); + Assert.Equal("IL_REGENERATED", (await ilCache.TryGetILAsync(dllPath, label))?.Trim()); + }); + } + + /// + /// removes both the memory entry and the disk entry, so neither the same instance nor a new instance over the same directory finds it. + /// がメモリとディスクの両方のエントリを削除し、同じインスタンスでも同じディレクトリを使う新しいインスタンスでも見つからなくなることを検証します。 + /// + [Fact] + public async Task ILCacheRemoveIL_RemovesMemoryAndDiskEntries() + { + var cacheDir = Path.Combine(_rootDir, "remove-il-cache"); + var dllPath = Path.Combine(_rootDir, "remove-il.dll"); + await File.WriteAllTextAsync(dllPath, "dummy"); + var ilCache = new ILCache(cacheDir, _logger); + await ilCache.SetILAsync(dllPath, "tool (version: 1)", "IL"); + + ilCache.RemoveIL(dllPath, "tool (version: 1)"); + + Assert.Null(await ilCache.TryGetILAsync(dllPath, "tool (version: 1)")); + Assert.Null(await new ILCache(cacheDir, _logger).TryGetILAsync(dllPath, "tool (version: 1)")); + } + + /// + /// Both ContainsIlContent overloads (string and lines) return true only when some line is neither blank nor a known tool notice. + /// ContainsIlContent の両オーバーロード(文字列版と行リスト版)が、空白行でも既知のツール通知行でもない行がある場合にだけ true を返すことを検証します。 + /// + [Theory] + [InlineData(null, false)] + [InlineData("", false)] + [InlineData(" \r\n\t\n", false)] + [InlineData("You are not using the latest version of the tool, please update.\r\nLatest version is '9.1.0' (yours is '8.2.0').\n", false)] + [InlineData("You are not using the latest version of the tool, please update.\n IL_0000: ret", true)] + [InlineData("// IL code: Sample", true)] + [InlineData("Latest version is a word without the version fragment", true)] + public void ContainsIlContent_DetectsAnyLineThatIsNeitherBlankNorToolNotice(string? text, bool expected) + { + Assert.Equal(expected, DotNetDisassembleService.ContainsIlContent(text)); + var lines = DotNetDisassembleService.SplitToLines(text ?? string.Empty); + Assert.Equal(expected, DotNetDisassembleService.ContainsIlContent(lines)); + } + + /// + /// Installs a dotnet-ildasm fake that exits 0 with only stderr output, a failing dotnet muxer, and a working ilspycmd fake. + /// stderr だけを出して終了コード 0 で終わる dotnet-ildasm、失敗する dotnet muxer、成功する ilspycmd の偽ツールを配置します。 + /// + private static void ConfigureEmptyDotnetIldasmAndWorkingIlspy(string binDir) + { + InstallFakeTool(binDir, "dotnet-ildasm", prefix => + { + Environment.SetEnvironmentVariable(prefix + "VERSION_OUTPUT", "dotnet ildasm 0.12.0"); + Environment.SetEnvironmentVariable(prefix + "EMPTY_OUTPUT", "1"); + Environment.SetEnvironmentVariable(prefix + "STDERR", EMPTY_IL_STDERR); + }); + InstallFakeTool(binDir, "dotnet", prefix => Environment.SetEnvironmentVariable(prefix + "EXIT", "1")); + InstallFakeTool(binDir, "ilspycmd", prefix => + { + Environment.SetEnvironmentVariable(prefix + "VERSION_OUTPUT", "ilspycmd 9.1.0"); + Environment.SetEnvironmentVariable(prefix + "OUTPUT", "IL_FROM_ILSPY"); + }); + } + + /// + /// Asserts that a console warning reported the dotnet-ildasm run for as exiting 0 without IL, including its stderr. + /// に対する dotnet-ildasm の実行が「終了コード 0 で IL 無し」として、stderr 付きでコンソール警告されたことを検証します。 + /// + private static void AssertNoIlWarning(TestLogger logger, string dllPath) + { + Assert.Contains(logger.Entries, entry => entry.LogLevel == AppLogLevel.Warning + && entry.ShouldOutputMessageToConsole + && entry.Message.Contains(NO_IL_WARNING_FRAGMENT, StringComparison.Ordinal) + && entry.Message.Contains("dotnet-ildasm", StringComparison.Ordinal) + && entry.Message.Contains(dllPath, StringComparison.Ordinal) + && entry.Message.Contains(EMPTY_IL_STDERR, StringComparison.Ordinal)); + } + } +} diff --git a/Services/Caching/ILCache.cs b/Services/Caching/ILCache.cs index 4f4b7e58..41f60e1a 100644 --- a/Services/Caching/ILCache.cs +++ b/Services/Caching/ILCache.cs @@ -194,6 +194,17 @@ public async Task SetILAsync(string fileAbsolutePath, string toolLabel, string i LogStatsIfIntervalElapsed(); } + /// + /// Removes the memory and disk entries for the given file and tool label (used when a hit turns out to contain no IL). + /// 指定ファイルとツールラベルのメモリ・ディスクエントリを削除します(ヒットした内容に IL が無いと判明した場合に使用)。 + /// + public void RemoveIL(string fileAbsolutePath, string toolLabel) + { + var ilCacheKey = BuildILCacheKey(fileAbsolutePath, toolLabel); + _memoryCache.Remove(ilCacheKey); + _diskCache.Remove(ilCacheKey); + } + /// /// Builds a cache key: SHA256 + + toolLabel. /// キャッシュキーを生成します: SHA256 + + toolLabel。 diff --git a/Services/DotNetDisassembleService.OutputSanitizer.cs b/Services/DotNetDisassembleService.OutputSanitizer.cs index 479ee879..5596243b 100644 --- a/Services/DotNetDisassembleService.OutputSanitizer.cs +++ b/Services/DotNetDisassembleService.OutputSanitizer.cs @@ -59,13 +59,67 @@ private static List CopyPrefix(IReadOnlyList lines, int count) return copied; } - private static bool IsDisassemblerStdoutNoticeLine(string? line) + /// + /// Returns true when the text has at least one line that is neither blank nor a known tool notice. + /// Scans without allocating and stops at the first IL line. + /// 空白行でも既知のツール通知行でもない行が 1 行以上あれば true を返します。 + /// 割り当てなしで走査し、最初の IL 行で打ち切ります。 + /// + internal static bool ContainsIlContent(string? text) { - if (string.IsNullOrWhiteSpace(line)) + if (string.IsNullOrEmpty(text)) { return false; } + foreach (var line in text.AsSpan().EnumerateLines()) + { + if (IsIlContentLine(line)) + { + return true; + } + } + return false; + } + + /// + /// Returns true when at least one line is neither blank nor a known tool notice. + /// 空白行でも既知のツール通知行でもない行が 1 行以上あれば true を返します。 + /// + internal static bool ContainsIlContent(IReadOnlyList lines) + { + ArgumentNullException.ThrowIfNull(lines); + + for (int i = 0; i < lines.Count; i++) + { + if (IsIlContentLine(lines[i])) + { + return true; + } + } + return false; + } + + /// + /// Returns true when the line is neither blank nor a known tool notice, i.e. it carries IL output. + /// 空白行でも既知のツール通知行でもない、つまり IL 出力を含む行であれば true を返します。 + /// + private static bool IsIlContentLine(ReadOnlySpan line) + => !line.IsWhiteSpace() && !IsDisassemblerStdoutNoticeLine(line); + + /// + /// Returns true when the line is a known disassembler tool notice; null or blank lines are never notices. + /// 既知の逆アセンブラツール通知行であれば true を返します。null や空白行は通知行として扱いません。 + /// + private static bool IsDisassemblerStdoutNoticeLine(string? line) + => !string.IsNullOrWhiteSpace(line) && IsDisassemblerStdoutNoticeLine(line.AsSpan()); + + /// + /// Span-based notice check used by the allocation-free scan in . + /// の割り当てなし走査で使う、span ベースの通知行判定です。 + /// + private static bool IsDisassemblerStdoutNoticeLine(ReadOnlySpan line) + { var trimmed = line.Trim(); return trimmed.StartsWith(ILSPY_UPDATE_NOTICE_PREFIX, StringComparison.OrdinalIgnoreCase) || (trimmed.StartsWith(ILSPY_LATEST_VERSION_PREFIX, StringComparison.OrdinalIgnoreCase) diff --git a/Services/DotNetDisassembleService.Streaming.cs b/Services/DotNetDisassembleService.Streaming.cs index 3ff4778c..55ce7264 100644 --- a/Services/DotNetDisassembleService.Streaming.cs +++ b/Services/DotNetDisassembleService.Streaming.cs @@ -125,9 +125,9 @@ public sealed partial class DotNetDisassembleService /// /// Tries disassembly with a single argument set, returning IL as lines: cache check, process execution (line-by-line stdout), cache store. - /// The ilspycmd -o temporary output directory is always removed afterwards. + /// Exit code 0 without IL content is reported as a failure. The ilspycmd -o temporary output directory is always removed afterwards. /// 1 つの引数セットで逆アセンブルを試行し IL を行リストで返します。キャッシュ事前チェック→行単位プロセス実行→キャッシュ格納。 - /// ilspycmd の -o 一時出力ディレクトリは終了後に必ず削除します。 + /// IL を含まない終了コード 0 は失敗として返します。ilspycmd の -o 一時出力ディレクトリは終了後に必ず削除します。 /// private async Task<(bool Success, IReadOnlyList? IlLines, string? Label, Exception? Error)> TryDisassembleWithArgumentsToLines( string disassembleCommand, @@ -149,9 +149,9 @@ public sealed partial class DotNetDisassembleService } /// - /// Core of : cache check, process execution, and cache store. + /// Core of : cache check, process execution, empty-IL check, and cache store. /// Temporary output cleanup is left to the caller's finally. - /// の本体。キャッシュ確認→プロセス実行→キャッシュ格納を行います。 + /// の本体。キャッシュ確認→プロセス実行→空 IL 判定→キャッシュ格納を行います。 /// 一時出力の削除は呼び出し元の finally が担当します。 /// private async Task<(bool Success, IReadOnlyList? IlLines, string? Label, Exception? Error)> TryDisassembleWithArgumentsToLinesCore( @@ -186,8 +186,16 @@ public sealed partial class DotNetDisassembleService if (exitCode == 0) { - ResetDisassembleFailure(disassembleCommand); var ilLines = await ReadIlLinesAfterSuccessAsync(IsIlspyCommand(disassembleCommand), argset, stdoutLines!); + if (!ContainsIlContent(ilLines)) + { + // Exit 0 without IL is a failure, so the next argument set or disassembler is tried. + // IL の無い終了コード 0 は失敗として扱い、次の引数セットまたは逆アセンブラを試す。 + return (Success: false, IlLines: null, Label: null, + Error: RegisterEmptyIlOutputFailure(disassembleCommand, dotNetAssemblyFileAbsolutePath, argset, stderr)); + } + + ResetDisassembleFailure(disassembleCommand); if (string.IsNullOrEmpty(label)) { label = await GetDisassembleCommandAndItsVersionWithArgumentsAsync(ProcessHelper.BuildBaseLabel(disassembleCommand, argset.args)); diff --git a/Services/DotNetDisassembleService.cs b/Services/DotNetDisassembleService.cs index 663c706b..d4d509c5 100644 --- a/Services/DotNetDisassembleService.cs +++ b/Services/DotNetDisassembleService.cs @@ -250,9 +250,9 @@ public Task PrefetchIlCacheAsync(IEnumerable dotNetAssemblyFilesAbsolute /// /// Tries disassembly with a single argument set: cache check, process execution, cache store. - /// The ilspycmd -o temporary output directory is always removed afterwards. + /// Exit code 0 without IL content is reported as a failure. The ilspycmd -o temporary output directory is always removed afterwards. /// 1つの引数セットで逆アセンブルを試行します。キャッシュ事前チェック→プロセス実行→キャッシュ格納までを担当。 - /// ilspycmd の -o 一時出力ディレクトリは終了後に必ず削除します。 + /// IL を含まない終了コード 0 は失敗として返します。ilspycmd の -o 一時出力ディレクトリは終了後に必ず削除します。 /// private async Task<(bool Success, string? IlText, string? DisassembleCommandAndItsVersionWithArguments, Exception? Error)> TryDisassembleWithArguments( string disassembleCommand, @@ -274,9 +274,9 @@ public Task PrefetchIlCacheAsync(IEnumerable dotNetAssemblyFilesAbsolute } /// - /// Core of : cache check, process execution, and cache store. + /// Core of : cache check, process execution, empty-IL check, and cache store. /// Temporary output cleanup is left to the caller's finally. - /// の本体。キャッシュ確認→プロセス実行→キャッシュ格納を行います。 + /// の本体。キャッシュ確認→プロセス実行→空 IL 判定→キャッシュ格納を行います。 /// 一時出力の削除は呼び出し元の finally が担当します。 /// private async Task<(bool Success, string? IlText, string? DisassembleCommandAndItsVersionWithArguments, Exception? Error)> TryDisassembleWithArgumentsCore( @@ -313,10 +313,18 @@ public Task PrefetchIlCacheAsync(IEnumerable dotNetAssemblyFilesAbsolute if (exitCode == 0) { + var ilText = await ReadIlTextAfterSuccessAsync(IsIlspyCommand(disassembleCommand), argset, stdout!); + if (!ContainsIlContent(ilText)) + { + // Exit 0 without IL is a failure, so the next argument set or disassembler is tried. + // IL の無い終了コード 0 は失敗として扱い、次の引数セットまたは逆アセンブラを試す。 + return (Success: false, IlText: null, DisassembleCommandAndItsVersionWithArguments: null, + Error: RegisterEmptyIlOutputFailure(disassembleCommand, dotNetAssemblyFileAbsolutePath, argset, stderr)); + } + // Success — clear the blacklist state. // 正常終了したらブラックリスト状態を解除。 ResetDisassembleFailure(disassembleCommand); - var ilText = await ReadIlTextAfterSuccessAsync(IsIlspyCommand(disassembleCommand), argset, stdout!); if (string.IsNullOrEmpty(label)) { // On cache-miss path the label may not have been computed yet. @@ -364,6 +372,17 @@ public Task PrefetchIlCacheAsync(IEnumerable dotNetAssemblyFilesAbsolute { var label = await GetDisassembleCommandAndItsVersionWithArgumentsAsync(ProcessHelper.BuildBaseLabel(disassembleCommand, args)); var cached = await _ilCache.TryGetILAsync(dotNetAssemblyFileAbsolutePath, label); + if (cached != null && !ContainsIlContent(cached)) + { + // An entry holding only tool notices (e.g. written by an older version) would become empty IL after sanitizing: drop it and regenerate. + // ツール通知行だけのエントリ(旧バージョンが書いたもの等)はサニタイズ後に空の IL になるため、削除して再生成する。 + _ilCache.RemoveIL(dotNetAssemblyFileAbsolutePath, label); + _logger.LogMessage( + AppLogLevel.Warning, + $"Ignored cached IL for '{dotNetAssemblyFileAbsolutePath}' (Tool='{label}') because it contains no IL after removing disassembler notices. The entry was removed and IL will be regenerated.", + shouldOutputMessageToConsole: true); + return (false, null, label); + } if (cached != null) { Interlocked.Increment(ref _ilCacheHits); @@ -430,6 +449,35 @@ private async Task TryStoreToCacheAsync( } } + /// + /// Builds the error for a run that exited 0 without IL, logs it to the console with stderr, and counts it as a tool failure. + /// 終了コード 0 で IL が無かった実行のエラーを生成し、stderr 付きでコンソールへログ出力したうえでツール失敗として計上します。 + /// + private InvalidOperationException RegisterEmptyIlOutputFailure( + string disassembleCommand, + string dotNetAssemblyFileAbsolutePath, + (string workingDirectory, string[] args, string? tempOutDirectory) argset, + string? stderr) + { + var outputDirectoryLine = string.Empty; + if (!string.IsNullOrEmpty(argset.tempOutDirectory)) + { + // Distinguish "ilspycmd wrote no IL file" from "the IL file had no IL content". + // 「ilspycmd が IL ファイルを書かなかった」と「IL ファイルに IL が無かった」を区別する。 + var missingFileNote = ResolveIlspyOutputFile(argset.tempOutDirectory, argset.args[^1]) == null ? " (no IL file found)" : string.Empty; + outputDirectoryLine = $"OutputDirectory: {argset.tempOutDirectory}{missingFileNote}\n"; + } + var error = new InvalidOperationException( + $"Disassembler exited with code 0 but produced no IL: {disassembleCommand} {ProcessHelper.GetUsedArgs(argset.args)} in {argset.workingDirectory}\n" + + $"File: {dotNetAssemblyFileAbsolutePath}\n" + + outputDirectoryLine + + $"Stderr: {(string.IsNullOrWhiteSpace(stderr) ? "(empty)" : stderr.Trim())}\n" + + "The next argument set or disassembler will be tried. If every attempt fails, check the stderr above, update the disassembler tool, or use --skip-il to bypass IL comparison."); + _logger.LogMessage(AppLogLevel.Warning, error.Message, shouldOutputMessageToConsole: true); + RegisterDisassembleFailure(disassembleCommand); + return error; + } + private bool IsDisassemblerBlacklisted(string disassembleCommand) => _blacklist.IsBlacklisted(disassembleCommand); diff --git a/doc/DEVELOPER_GUIDE.md b/doc/DEVELOPER_GUIDE.md index c906cce8..34f02208 100644 --- a/doc/DEVELOPER_GUIDE.md +++ b/doc/DEVELOPER_GUIDE.md @@ -711,7 +711,7 @@ Key performance features: - Chunk-parallel text comparison for large local text files - Optional memory-budget-aware throttling for chunk-parallel text comparison - Batched IL precompute target enumeration for very large folder trees -- Tool failure blacklist inside disassembler flow +- Tool failure blacklist inside disassembler flow; a run that exits 0 without IL also counts as a failure, is logged to the console with stderr, and continues to the next argument set or disassembler, and an IL cache hit that holds only tool notices is removed and regenerated - Progress keep-alive while long-running precompute is in flight When to be careful: @@ -1692,7 +1692,7 @@ flowchart TD - ローカルの大きいテキスト向けチャンク並列比較 - 並列テキスト比較に対する任意のメモリ予算ベース抑制 - 大規模ツリー向けの IL 事前計算バッチ化 -- 逆アセンブラ失敗時のブラックリスト +- 逆アセンブラ失敗時のブラックリスト。終了コード 0 でも IL を出さなかった実行は失敗として数え、stderr 付きでコンソールへログ出力したうえで次の引数セットまたは逆アセンブラへ進み、ツール通知行だけの IL キャッシュヒットは削除して再生成 - 長い事前計算中でも進捗が止まって見えないようにスピナーを回す 注意が必要な変更: diff --git a/doc/TROUBLESHOOTING.md b/doc/TROUBLESHOOTING.md index 2a66a817..de08de0e 100644 --- a/doc/TROUBLESHOOTING.md +++ b/doc/TROUBLESHOOTING.md @@ -136,6 +136,7 @@ The tool marked **In Use** in the report is the one that was successfully probed | `dotnet-ildasm --version` works but report still shows `SHA256Mismatch` | `SkipIL` is enabled | Check that `--skip-il` is not passed and `SkipIL` is `false` in [`config.json`](../config.json) | | Tool works for some assemblies but fails for others | Framework version mismatch or corrupt assembly | Check the per-file "Disassembler" column in the report; failed files show the fallback tool or `SHA256` | | `ilspycmd` hangs on certain assemblies | Known issue with some obfuscated assemblies | Set `DisassemblerTimeoutSeconds` in [`config.json`](../config.json) (default: 60s) to auto-kill hanging processes | +| Console warning `Disassembler exited with code 0 but produced no IL` | The tool reported success without writing IL for that assembly | nildiff already moves on to the next argument set or disassembler. If every attempt fails, read the `Stderr:` part of the warning, update the tool, or use `--skip-il` | | Permission denied on macOS/Linux | File not executable | Run `chmod +x ~/.dotnet/tools/dotnet-ildasm` | ### IL cache disk usage grows too large @@ -522,6 +523,7 @@ nildiff を実行し、レポートヘッダの **Disassembler Availability** | `dotnet-ildasm --version` は動作するがレポートが `SHA256Mismatch` のまま | `SkipIL` が有効 | `--skip-il` が渡されていないこと、`config.json` の `SkipIL` が `false` であることを確認 | | 一部のアセンブリでのみツールが失敗する | フレームワークバージョンの不一致またはアセンブリの破損 | レポートのファイルごとの「Disassembler」列を確認。失敗したファイルはフォールバックツールまたは `SHA256` と表示される | | `ilspycmd` が特定のアセンブリでハングする | 難読化されたアセンブリでの既知の問題 | `config.json` の `DisassemblerTimeoutSeconds` を設定(デフォルト: 60秒)してハングしたプロセスを自動終了 | +| コンソールに `Disassembler exited with code 0 but produced no IL` の警告が出る | そのアセンブリに対してツールが IL を書かずに成功を返した | nildiff は自動で次の引数セットまたは逆アセンブラへ進みます。すべて失敗する場合は警告の `Stderr:` を確認し、ツールを更新するか `--skip-il` を使用 | | macOS/Linux でパーミッションエラー | ファイルに実行権限がない | `chmod +x ~/.dotnet/tools/dotnet-ildasm` を実行 | ### IL キャッシュのディスク使用量が大きくなりすぎる From 44b451a87d0cd8d7eb59932398eab15fd52b5480 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 11:21:07 +0000 Subject: [PATCH 3/4] Log each failed disassembly attempt and show timeouts on the console A timed-out attempt was silent unless every disassembler failed, so the DisassemblerTimeoutSeconds guidance in the TimeoutException never reached users whose run fell back to another argument set or tool. Log every failed attempt with the file, command, and working directory. Timeouts are environment-dependent and actionable, so they are console warnings that keep the DisassemblerTimeoutSeconds guidance. Start failures and non-zero exits are routine fallback steps (e.g. a candidate tool that is not installed) and go to the log file only to avoid flooding the console; the final error still reports the root cause when every attempt fails. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0169z7S1N3Vmq8rHkry7EDVa --- CHANGELOG.md | 2 + ...embleServiceTests.AttemptFailureLogging.cs | 127 ++++++++++++++++++ .../DotNetDisassembleService.Streaming.cs | 2 + Services/DotNetDisassembleService.cs | 28 +++- USER_GUIDE.md | 4 +- doc/TROUBLESHOOTING.md | 2 + 6 files changed, 161 insertions(+), 4 deletions(-) create mode 100644 FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.AttemptFailureLogging.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index c3c0bfe7..8e0a84ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - **ilspycmd `-o` fallback reads the IL it actually writes** — `ilspycmd -o` takes an output directory and writes `.il` inside it, but nildiff passed a file path, so the fallback always returned empty IL after a successful exit and left `ilspy_out_*` directories in the temp folder. nildiff now passes a fresh temporary directory, reads the generated `.il` file, and deletes the directory recursively after every attempt, including failures and timeouts. Affected: `Services/DotNetDisassembleService.cs`, `Services/DotNetDisassembleService.Streaming.cs`, `Services/DotNetDisassembleService.VersionLabel.cs`, `FolderDiffIL4DotNet.Tests/Helpers/FakeDisassemblerProgram.cs`. Tests: `DisassembleAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt`, `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt`, `ResolveIlspyOutputFile_ReturnsInputNamedIlFileOnly`, `BuildArgSets_IlspyCommand_PassesTemporaryOutputDirectoryToOutputFlag`, `CleanupTemporaryPathBestEffort_WhenPathIsDirectory_DeletesItRecursivelyWithoutWarning`. - **Disassembler runs that exit 0 without IL are failures** — Such runs were accepted as successful empty IL, which skipped the remaining argument sets and disassemblers and made IL comparison fail after its raw-disassembly retries. They now count toward the disassembler failure blacklist, log a console warning with the command, file, ilspycmd output directory (marked `(no IL file found)` when ilspycmd wrote no IL file), and stderr, and continue with the next argument set or disassembler. IL cache hits that contain only disassembler notices are removed and regenerated instead of becoming empty IL. Added `ILCache.RemoveIL`. Affected: `Services/DotNetDisassembleService.cs`, `Services/DotNetDisassembleService.Streaming.cs`, `Services/DotNetDisassembleService.OutputSanitizer.cs`, `Services/Caching/ILCache.cs`, `doc/TROUBLESHOOTING.md`. Tests: `DisassembleAsync_WhenPrimaryToolExitsZeroWithoutIl_LogsStderrAndFallsBackToNextTool`, `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenPrimaryToolExitsZeroWithoutIl_LogsStderrAndFallsBackToNextTool`, `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenEveryToolExitsZeroWithoutIl_ThrowsInsteadOfReturningEmptyIl`, `DisassembleAsync_WhenCachedIlContainsOnlyToolNotices_RemovesEntryAndRegeneratesIl`, `ILCacheRemoveIL_RemovesMemoryAndDiskEntries`, `ContainsIlContent_DetectsAnyLineThatIsNeitherBlankNorToolNotice`. +- **Disassembler timeouts are reported when a fallback succeeds** — A timed-out attempt was silent unless every disassembler failed, so its `DisassemblerTimeoutSeconds` guidance never reached users whose run fell back to another argument set or tool. Each failed attempt is now logged with the file, command, and working directory: timeouts as console warnings that keep the `DisassemblerTimeoutSeconds` guidance, and start failures and non-zero exits in the log file only, because they are routine fallback steps (for example, a candidate tool that is not installed) and the final error already reports the root cause when every attempt fails. Affected: `Services/DotNetDisassembleService.cs`, `Services/DotNetDisassembleService.Streaming.cs`, `USER_GUIDE.md`, `doc/TROUBLESHOOTING.md`. Tests: `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenAttemptTimesOut_LogsTimeoutGuidanceToConsoleAndFallsBack`, `DisassembleAsync_WhenAttemptExitsNonZero_LogsFailureToFileOnlyAndFallsBack`. - **npm audit CI uses patched brace-expansion** — Updated the 2.x override and lockfile from `2.1.4` to `2.1.7`, resolving the reported denial-of-service vulnerabilities and the transitive `minimatch` finding without adding audit exceptions. - **npm audit CI uses patched js-yaml** — Updated the 3.x override and lockfile to `3.15.2`, resolving `GHSA-2883-xcg3-v3hh` without adding an audit exception. - **Benchmark regression CI compares matching execution environments** — Preserved BenchmarkDotNet host metadata and partitioned trusted history by CPU, core topology, OS, architecture, runtime/SDK, build configuration, and BenchmarkDotNet version. Mixed-host legacy history starts a visible five-sample warmup per environment; warning/failure thresholds, ancestry checks, and trusted publication restrictions remain unchanged. Added regression coverage for environment isolation, invalid host metadata, report combination, and real slowdowns within one environment. @@ -1776,6 +1777,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - **ilspycmd の `-o` フォールバックで実際に書き出された IL を読むように修正** — `ilspycmd -o` は出力ディレクトリを受け取り、その中に `<入力名>.il` を書き出しますが、nildiff はファイルパスを渡していたため、このフォールバックは正常終了しても常に空の IL を返し、一時フォルダに `ilspy_out_*` ディレクトリを残していました。新しい一時ディレクトリを渡して生成された `<入力名>.il` ファイルを読み取り、失敗やタイムアウトを含むすべての試行の後にディレクトリを再帰的に削除するようにしました。対象: `Services/DotNetDisassembleService.cs`, `Services/DotNetDisassembleService.Streaming.cs`, `Services/DotNetDisassembleService.VersionLabel.cs`, `FolderDiffIL4DotNet.Tests/Helpers/FakeDisassemblerProgram.cs`。テスト: `DisassembleAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt`, `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt`, `ResolveIlspyOutputFile_ReturnsInputNamedIlFileOnly`, `BuildArgSets_IlspyCommand_PassesTemporaryOutputDirectoryToOutputFlag`, `CleanupTemporaryPathBestEffort_WhenPathIsDirectory_DeletesItRecursivelyWithoutWarning`。 - **終了コード 0 で IL を出さない逆アセンブラ実行を失敗として扱うように修正** — このような実行は空の IL として成功扱いされていたため、残りの引数セットや逆アセンブラが試されず、IL 比較は raw 逆アセンブルの再試行後に失敗していました。逆アセンブラ失敗のブラックリスト計数に含め、コマンド、ファイル、ilspycmd の出力ディレクトリ(ilspycmd が IL ファイルを書かなかった場合は `(no IL file found)` を付記)、stderr を含む警告をコンソールに出力したうえで、次の引数セットまたは逆アセンブラへ進むようにしました。逆アセンブラの通知行だけを含む IL キャッシュヒットは、空の IL にせず削除して再生成します。`ILCache.RemoveIL` を追加しました。対象: `Services/DotNetDisassembleService.cs`, `Services/DotNetDisassembleService.Streaming.cs`, `Services/DotNetDisassembleService.OutputSanitizer.cs`, `Services/Caching/ILCache.cs`, `doc/TROUBLESHOOTING.md`。テスト: `DisassembleAsync_WhenPrimaryToolExitsZeroWithoutIl_LogsStderrAndFallsBackToNextTool`, `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenPrimaryToolExitsZeroWithoutIl_LogsStderrAndFallsBackToNextTool`, `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenEveryToolExitsZeroWithoutIl_ThrowsInsteadOfReturningEmptyIl`, `DisassembleAsync_WhenCachedIlContainsOnlyToolNotices_RemovesEntryAndRegeneratesIl`, `ILCacheRemoveIL_RemovesMemoryAndDiskEntries`, `ContainsIlContent_DetectsAnyLineThatIsNeitherBlankNorToolNotice`。 +- **フォールバックが成功した場合も逆アセンブラのタイムアウトを通知するように修正** — タイムアウトした試行は、すべての逆アセンブラが失敗しない限り何も出力されなかったため、別の引数セットやツールへフォールバックした実行では `DisassemblerTimeoutSeconds` の案内が利用者に届きませんでした。失敗した各試行を、ファイル、コマンド、作業ディレクトリとともにログ出力するようにしました。タイムアウトは `DisassemblerTimeoutSeconds` の案内を含む警告としてコンソールにも出力し、起動失敗と非 0 終了はログファイルのみに記録します。後者はフォールバックの通常過程(未インストールの候補ツール等)であり、すべての試行が失敗した場合は最終エラーが原因を報告するためです。対象: `Services/DotNetDisassembleService.cs`, `Services/DotNetDisassembleService.Streaming.cs`, `USER_GUIDE.md`, `doc/TROUBLESHOOTING.md`。テスト: `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenAttemptTimesOut_LogsTimeoutGuidanceToConsoleAndFallsBack`, `DisassembleAsync_WhenAttemptExitsNonZero_LogsFailureToFileOnlyAndFallsBack`。 - **npm audit CI で修正版 brace-expansion を使用** — 2.x override と lockfile を `2.1.4` から `2.1.7` に更新し、監査例外を追加せず、報告されたサービス拒否の脆弱性と依存先から波及した `minimatch` の検出を解消しました。 - **npm audit CI で修正版 js-yaml を使用** — 3.x override と lockfile を `3.15.2` に更新し、監査例外を追加せず `GHSA-2883-xcg3-v3hh` を解消しました。 - **ベンチマーク回帰 CI を同一実行環境で比較** — BenchmarkDotNet のホスト情報を保持し、CPU、コア構成、OS、アーキテクチャ、runtime/SDK、ビルド構成、BenchmarkDotNet バージョンごとに信頼済み履歴を分離しました。旧来のホスト混在履歴は環境ごとに明示的な 5 サンプルのウォームアップから開始し、warning/failure 閾値、祖先チェック、信頼済み公開の制約は維持します。環境分離、不正なホスト情報、レポート結合、同一環境内での実際の遅化に回帰テストを追加しました。 diff --git a/FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.AttemptFailureLogging.cs b/FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.AttemptFailureLogging.cs new file mode 100644 index 00000000..32026cbe --- /dev/null +++ b/FolderDiffIL4DotNet.Tests/Services/DotNetDisassembleServiceTests.AttemptFailureLogging.cs @@ -0,0 +1,127 @@ +/// +/// Partial class covering how failed disassembly attempts are logged before the next fallback is tried. +/// 次のフォールバックへ進む前に、失敗した逆アセンブル試行がどのようにログ出力されるかを検証するパーシャルクラス。 +/// + +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; +using FolderDiffIL4DotNet.Common; +using FolderDiffIL4DotNet.Models; +using FolderDiffIL4DotNet.Services; +using FolderDiffIL4DotNet.Tests.Helpers; +using Xunit; + +namespace FolderDiffIL4DotNet.Tests.Services +{ + public sealed partial class DotNetDisassembleServiceTests + { + /// + /// A timed-out attempt is logged as a console warning that names the file and keeps the DisassemblerTimeoutSeconds guidance, and disassembly falls back to ilspycmd. + /// タイムアウトした試行が、ファイル名と DisassemblerTimeoutSeconds の案内を含むコンソール警告として記録され、逆アセンブルが ilspycmd へフォールバックすることを検証します。 + /// + [Fact] + public async Task DisassemblePairAsLinesWithSameDisassemblerAsync_WhenAttemptTimesOut_LogsTimeoutGuidanceToConsoleAndFallsBack() + { + var logger = new TestLogger(); + await RunWithFakeToolsAsync("timeout-guidance", binDir => + { + // dotnet-ildasm sleeps past the 2-second timeout; the margin keeps the working ilspycmd fake below it on slow runners. + // dotnet-ildasm は 2 秒のタイムアウトを超えてスリープする。余裕を持たせ、遅いランナーでも成功側の ilspycmd 偽ツールは超えないようにする。 + InstallFakeTool(binDir, "dotnet-ildasm", prefix => + { + Environment.SetEnvironmentVariable(prefix + "VERSION_OUTPUT", "dotnet ildasm 0.12.0"); + Environment.SetEnvironmentVariable(prefix + "SLEEP_MS", "20000"); + }); + InstallFakeTool(binDir, "dotnet", prefix => Environment.SetEnvironmentVariable(prefix + "EXIT", "1")); + InstallFakeTool(binDir, "ilspycmd", prefix => + { + Environment.SetEnvironmentVariable(prefix + "VERSION_OUTPUT", "ilspycmd 9.1.0"); + Environment.SetEnvironmentVariable(prefix + "OUTPUT", "IL_FROM_ILSPY"); + }); + }, async binDir => + { + var config = new ConfigSettingsBuilder + { + EnableILCache = false, + IgnoredExtensions = new(), + TextFileExtensions = new(), + DisassemblerTimeoutSeconds = 2 + }.Build(); + var service = new DotNetDisassembleService(config, ilCache: null, _resultLists, logger, _dotNetDisassemblerCache); + // The dotnet muxer is routed to the same sleeping fake; disable it up front to keep the test to two timeouts. + // dotnet muxer は同じスリープする偽ツールへルーティングされるため、事前に無効化してタイムアウトを 2 回に抑える。 + var blacklist = (DisassemblerBlacklist)typeof(DotNetDisassembleService) + .GetField("_blacklist", BindingFlags.Instance | BindingFlags.NonPublic)! + .GetValue(service)!; + blacklist.InjectEntry(Constants.DOTNET_MUXER, failCount: 3, lastFailUtc: DateTime.UtcNow); + var oldDll = Path.Combine(_rootDir, "timeout-old.dll"); + var newDll = Path.Combine(_rootDir, "timeout-new.dll"); + await File.WriteAllTextAsync(oldDll, "dummy-old"); + await File.WriteAllTextAsync(newDll, "dummy-new"); + + var (oldLines, oldCommand, _, _) = await service.DisassemblePairAsLinesWithSameDisassemblerAsync(oldDll, newDll); + + Assert.Equal(new[] { "IL_FROM_ILSPY" }, oldLines); + Assert.Contains("ilspycmd", oldCommand, StringComparison.OrdinalIgnoreCase); + Assert.Contains(logger.Entries, entry => entry.LogLevel == AppLogLevel.Warning + && entry.ShouldOutputMessageToConsole + && entry.Message.Contains("Disassembler attempt failed", StringComparison.Ordinal) + && entry.Message.Contains(oldDll, StringComparison.Ordinal) + && entry.Message.Contains(nameof(TimeoutException), StringComparison.Ordinal) + && entry.Message.Contains("timed out after 2 seconds", StringComparison.Ordinal) + && entry.Message.Contains("DisassemblerTimeoutSeconds", StringComparison.Ordinal)); + }); + } + + /// + /// Non-zero exits are routine fallback steps: each attempt is logged with its file and stderr to the log file only, never to the console, and disassembly falls back to ilspycmd. + /// 非 0 終了はフォールバックの通常過程であり、各試行がファイル名と stderr 付きでログファイルにのみ記録されてコンソールには出ず、逆アセンブルが ilspycmd へフォールバックすることを検証します。 + /// + [Fact] + public async Task DisassembleAsync_WhenAttemptExitsNonZero_LogsFailureToFileOnlyAndFallsBack() + { + var logger = new TestLogger(); + await RunWithFakeToolsAsync("nonzero-file-only", binDir => + { + InstallFakeTool(binDir, "dotnet-ildasm", prefix => + { + Environment.SetEnvironmentVariable(prefix + "VERSION_OUTPUT", "dotnet ildasm 0.12.0"); + Environment.SetEnvironmentVariable(prefix + "EXIT", "91"); + Environment.SetEnvironmentVariable(prefix + "STDERR", "NONZERO_STDERR_DETAIL"); + }); + InstallFakeTool(binDir, "dotnet", prefix => Environment.SetEnvironmentVariable(prefix + "EXIT", "1")); + InstallFakeTool(binDir, "ilspycmd", prefix => + { + Environment.SetEnvironmentVariable(prefix + "VERSION_OUTPUT", "ilspycmd 9.1.0"); + Environment.SetEnvironmentVariable(prefix + "OUTPUT", "IL_FROM_ILSPY"); + }); + }, async binDir => + { + var service = new DotNetDisassembleService(CreateConfig(enableIlCache: false), ilCache: null, _resultLists, logger, _dotNetDisassemblerCache); + var dllPath = Path.Combine(_rootDir, "nonzero-file-only.dll"); + await File.WriteAllTextAsync(dllPath, "dummy"); + + var (ilText, _) = await service.DisassembleAsync(dllPath); + + Assert.Equal("IL_FROM_ILSPY", ilText.Trim()); + // Every non-zero attempt (file-name and absolute-path argument sets, plus the dotnet muxer routed to the same fake) is logged to the file only. + // 非 0 終了の各試行(ファイル名・絶対パスの引数セットと、同じ偽ツールへルーティングされる dotnet muxer)はファイルのみに記録される。 + var nonZeroEntries = logger.Entries.Where(entry => entry.Message.Contains("(exit 91)", StringComparison.Ordinal)).ToList(); + Assert.NotEmpty(nonZeroEntries); + Assert.All(nonZeroEntries, entry => + { + Assert.Equal(AppLogLevel.Warning, entry.LogLevel); + Assert.False(entry.ShouldOutputMessageToConsole); + Assert.Contains("Disassembler attempt failed", entry.Message, StringComparison.Ordinal); + Assert.Contains(dllPath, entry.Message, StringComparison.Ordinal); + Assert.Contains("NONZERO_STDERR_DETAIL", entry.Message, StringComparison.Ordinal); + }); + Assert.DoesNotContain(logger.Entries, entry => entry.ShouldOutputMessageToConsole + && entry.Message.Contains("Disassembler attempt failed", StringComparison.Ordinal)); + }); + } + } +} diff --git a/Services/DotNetDisassembleService.Streaming.cs b/Services/DotNetDisassembleService.Streaming.cs index 55ce7264..4dd0ad30 100644 --- a/Services/DotNetDisassembleService.Streaming.cs +++ b/Services/DotNetDisassembleService.Streaming.cs @@ -180,6 +180,7 @@ public sealed partial class DotNetDisassembleService var (exitCode, stdoutLines, stderr, error) = await RunProcessAsLinesAsync(disassembleCommand, argset.workingDirectory, argset.args, _config.DisassemblerTimeoutSeconds); if (error != null) { + LogDisassembleAttemptError(disassembleCommand, dotNetAssemblyFileAbsolutePath, argset, error); RegisterDisassembleFailure(disassembleCommand); return (Success: false, IlLines: null, Label: null, Error: error); } @@ -215,6 +216,7 @@ public sealed partial class DotNetDisassembleService $"ildasm failed (exit {exitCode}) with command: {disassembleCommand} {ProcessHelper.GetUsedArgs(argset.args)} in {argset.workingDirectory}\n" + $"File: {dotNetAssemblyFileAbsolutePath}\nStderr: {stderr}\n" + $"Hint: Common causes include corrupt assemblies, unsupported formats, or tool version incompatibility. If this persists, try updating the disassembler tool or use --skip-il to bypass IL comparison."); + LogDisassembleAttemptError(disassembleCommand, dotNetAssemblyFileAbsolutePath, argset, lastError); RegisterDisassembleFailure(disassembleCommand); return (Success: false, IlLines: null, Label: null, Error: lastError); } diff --git a/Services/DotNetDisassembleService.cs b/Services/DotNetDisassembleService.cs index d4d509c5..ea313d11 100644 --- a/Services/DotNetDisassembleService.cs +++ b/Services/DotNetDisassembleService.cs @@ -305,8 +305,9 @@ public Task PrefetchIlCacheAsync(IEnumerable dotNetAssemblyFilesAbsolute var (exitCode, stdout, stderr, error) = await RunProcessAsync(disassembleCommand, argset.workingDirectory, argset.args, _config.DisassemblerTimeoutSeconds); if (error != null) { - // Process failed to start — blacklist and return failure. - // プロセス起動失敗 — ブラックリストへ登録し失敗として返す。 + // Process failed to start or timed out — log, blacklist, and return failure. + // プロセス起動失敗またはタイムアウト — ログ出力・ブラックリスト登録のうえ失敗として返す。 + LogDisassembleAttemptError(disassembleCommand, dotNetAssemblyFileAbsolutePath, argset, error); RegisterDisassembleFailure(disassembleCommand); return (Success: false, IlText: null, DisassembleCommandAndItsVersionWithArguments: null, Error: error); } @@ -346,6 +347,7 @@ public Task PrefetchIlCacheAsync(IEnumerable dotNetAssemblyFilesAbsolute $"ildasm failed (exit {exitCode}) with command: {disassembleCommand} {ProcessHelper.GetUsedArgs(argset.args)} in {argset.workingDirectory}\n" + $"File: {dotNetAssemblyFileAbsolutePath}\nStderr: {stderr}\n" + $"Hint: Common causes include corrupt assemblies, unsupported formats, or tool version incompatibility. If this persists, try updating the disassembler tool or use --skip-il to bypass IL comparison."); + LogDisassembleAttemptError(disassembleCommand, dotNetAssemblyFileAbsolutePath, argset, lastError); RegisterDisassembleFailure(disassembleCommand); return (Success: false, IlText: null, DisassembleCommandAndItsVersionWithArguments: null, Error: lastError); } @@ -478,6 +480,28 @@ private InvalidOperationException RegisterEmptyIlOutputFailure( return error; } + /// + /// Logs a failed disassembly attempt (start failure, timeout, or non-zero exit). + /// Timeouts depend on the environment and are fixed by raising DisassemblerTimeoutSeconds, so they also go to the console; + /// the other failures are routine steps of the fallback chain (e.g. a candidate tool that is not installed) and go to the log file only, + /// because the final exception reports the root cause when every attempt fails. + /// 失敗した逆アセンブル試行(起動失敗・タイムアウト・非 0 終了)をログ出力します。 + /// タイムアウトは環境に依存し DisassemblerTimeoutSeconds の引き上げで解消できるためコンソールにも出力します。 + /// それ以外の失敗はフォールバックの通常過程(未インストールの候補ツール等)であり、全試行失敗時は最終例外が原因を報告するため、ログファイルのみに出力します。 + /// + private void LogDisassembleAttemptError( + string disassembleCommand, + string dotNetAssemblyFileAbsolutePath, + (string workingDirectory, string[] args, string? tempOutDirectory) argset, + Exception error) + { + bool isTimeout = error is TimeoutException; + _logger.LogMessage( + AppLogLevel.Warning, + $"Disassembler attempt failed for '{dotNetAssemblyFileAbsolutePath}' with command: {disassembleCommand} {ProcessHelper.GetUsedArgs(argset.args)} in {argset.workingDirectory} ({error.GetType().Name}): {error.Message}", + shouldOutputMessageToConsole: isTimeout); + } + private bool IsDisassemblerBlacklisted(string disassembleCommand) => _blacklist.IsBlacklisted(disassembleCommand); diff --git a/USER_GUIDE.md b/USER_GUIDE.md index 7dfeb630..0f8bed9f 100644 --- a/USER_GUIDE.md +++ b/USER_GUIDE.md @@ -754,7 +754,7 @@ Override only the settings you want to change. For example: DisassemblerTimeoutSeconds 60 - Timeout (seconds) for each disassembler process invocation. <=0 means no timeout. Increase for very large assemblies or slow network shares. + Timeout (seconds) for each disassembler process invocation. <=0 means no timeout. Increase for very large assemblies or slow network shares. Each timed-out attempt prints a console warning that names this setting before the next argument set or disassembler is tried. SkipIL @@ -1664,7 +1664,7 @@ JSON Schema ファイル([`doc/config.schema.json`](doc/config.schema.json)) DisassemblerTimeoutSeconds 60 - 各逆アセンブラプロセス実行のタイムアウト(秒)。<=0 でタイムアウトなし。非常に大きなアセンブリやネットワーク共有の遅延時に増加。 + 各逆アセンブラプロセス実行のタイムアウト(秒)。<=0 でタイムアウトなし。非常に大きなアセンブリやネットワーク共有の遅延時に増加。タイムアウトした試行ごとに、この設定名を含む警告をコンソールに出力してから、次の引数セットまたは逆アセンブラを試します。 SkipIL diff --git a/doc/TROUBLESHOOTING.md b/doc/TROUBLESHOOTING.md index de08de0e..bf3b4fbf 100644 --- a/doc/TROUBLESHOOTING.md +++ b/doc/TROUBLESHOOTING.md @@ -136,6 +136,7 @@ The tool marked **In Use** in the report is the one that was successfully probed | `dotnet-ildasm --version` works but report still shows `SHA256Mismatch` | `SkipIL` is enabled | Check that `--skip-il` is not passed and `SkipIL` is `false` in [`config.json`](../config.json) | | Tool works for some assemblies but fails for others | Framework version mismatch or corrupt assembly | Check the per-file "Disassembler" column in the report; failed files show the fallback tool or `SHA256` | | `ilspycmd` hangs on certain assemblies | Known issue with some obfuscated assemblies | Set `DisassemblerTimeoutSeconds` in [`config.json`](../config.json) (default: 60s) to auto-kill hanging processes | +| Console warning `Disassembler attempt failed ... (TimeoutException)` | The disassembler did not finish within `DisassemblerTimeoutSeconds`, often on slower machines or under heavy parallel load, so results can differ between machines | Raise `DisassemblerTimeoutSeconds` in [`config.json`](../config.json), or lower `MaxParallelism` to reduce contention. Other attempt failures (non-zero exit, tool not installed) are written to the log file only | | Console warning `Disassembler exited with code 0 but produced no IL` | The tool reported success without writing IL for that assembly | nildiff already moves on to the next argument set or disassembler. If every attempt fails, read the `Stderr:` part of the warning, update the tool, or use `--skip-il` | | Permission denied on macOS/Linux | File not executable | Run `chmod +x ~/.dotnet/tools/dotnet-ildasm` | @@ -523,6 +524,7 @@ nildiff を実行し、レポートヘッダの **Disassembler Availability** | `dotnet-ildasm --version` は動作するがレポートが `SHA256Mismatch` のまま | `SkipIL` が有効 | `--skip-il` が渡されていないこと、`config.json` の `SkipIL` が `false` であることを確認 | | 一部のアセンブリでのみツールが失敗する | フレームワークバージョンの不一致またはアセンブリの破損 | レポートのファイルごとの「Disassembler」列を確認。失敗したファイルはフォールバックツールまたは `SHA256` と表示される | | `ilspycmd` が特定のアセンブリでハングする | 難読化されたアセンブリでの既知の問題 | `config.json` の `DisassemblerTimeoutSeconds` を設定(デフォルト: 60秒)してハングしたプロセスを自動終了 | +| コンソールに `Disassembler attempt failed ... (TimeoutException)` の警告が出る | 逆アセンブラが `DisassemblerTimeoutSeconds` 以内に終わらなかった。遅い端末や並列負荷が高い環境で起きやすく、端末によって結果が変わることがある | `config.json` の `DisassemblerTimeoutSeconds` を増やすか、`MaxParallelism` を下げて競合を減らす。その他の試行失敗(非 0 終了、ツール未インストール)はログファイルのみに記録 | | コンソールに `Disassembler exited with code 0 but produced no IL` の警告が出る | そのアセンブリに対してツールが IL を書かずに成功を返した | nildiff は自動で次の引数セットまたは逆アセンブラへ進みます。すべて失敗する場合は警告の `Stderr:` を確認し、ツールを更新するか `--skip-il` を使用 | | macOS/Linux でパーミッションエラー | ファイルに実行権限がない | `chmod +x ~/.dotnet/tools/dotnet-ildasm` を実行 | From d49992435620d0c7c1b10334bfafa2c78014aef1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 11:24:13 +0000 Subject: [PATCH 4/4] Remove the raw-disassembly retry from IL comparison ILOutputService re-disassembled the same old/new pair up to 5 times when a raw side was empty. The disassembler service now treats a run that exits 0 without IL as a failed attempt and falls back across argument sets and disassemblers itself, and an empty result is deterministic for a given tool and assembly, so the retry only repeated the same outcome. Disassemble each pair once. An empty raw side, possible only from a non-conforming IDotNetDisassembleService implementation, fails immediately with an error diagnostic; diagnostics no longer carry Attempt= / WillRetry=. Filtered-empty sides are still logged as warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0169z7S1N3Vmq8rHkry7EDVa --- CHANGELOG.md | 8 + .../ILOutputServiceTests.Precompute.cs | 101 ++----- Services/ILOutputService.cs | 251 +++++++++--------- USER_GUIDE.md | 8 +- 4 files changed, 152 insertions(+), 216 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e0a84ea..17f22120 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### [Unreleased] +#### Removed + +- **IL comparison no longer re-disassembles a pair when either side's raw IL is empty** — `ILOutputService` used to retry the same old/new pair up to 5 attempts when the raw IL of either side (old or new) was empty. The disassembler service now treats a run that exits 0 without IL as a failed attempt and falls back across argument sets and disassemblers itself, and an empty result is deterministic for a given tool and assembly, so the retry only repeated the same outcome. Each pair is disassembled once; empty raw IL on either side (possible only from a non-conforming `IDotNetDisassembleService` implementation) fails immediately with an error diagnostic, and diagnostics no longer include `Attempt=` / `WillRetry=`. Filtered-empty sides are still logged as warnings. Affected: `Services/ILOutputService.cs`, `USER_GUIDE.md`. Tests: `DiffDotNetAssembliesAsync_WhenRawIlSideIsEmpty_ThrowsWithoutRetrying`, `DiffDotNetAssembliesAsync_WhenFilteredIlSideIsEmpty_LogsWarningAndCompares`. + #### Fixed - **ilspycmd `-o` fallback reads the IL it actually writes** — `ilspycmd -o` takes an output directory and writes `.il` inside it, but nildiff passed a file path, so the fallback always returned empty IL after a successful exit and left `ilspy_out_*` directories in the temp folder. nildiff now passes a fresh temporary directory, reads the generated `.il` file, and deletes the directory recursively after every attempt, including failures and timeouts. Affected: `Services/DotNetDisassembleService.cs`, `Services/DotNetDisassembleService.Streaming.cs`, `Services/DotNetDisassembleService.VersionLabel.cs`, `FolderDiffIL4DotNet.Tests/Helpers/FakeDisassemblerProgram.cs`. Tests: `DisassembleAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt`, `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt`, `ResolveIlspyOutputFile_ReturnsInputNamedIlFileOnly`, `BuildArgSets_IlspyCommand_PassesTemporaryOutputDirectoryToOutputFlag`, `CleanupTemporaryPathBestEffort_WhenPathIsDirectory_DeletesItRecursivelyWithoutWarning`. @@ -1773,6 +1777,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### [Unreleased] +#### 削除 + +- **IL 比較で old/new のいずれか片側でも raw IL が空のとき、ペアを再逆アセンブルしないように変更** — `ILOutputService` は old/new のいずれか片側でも raw IL が空の場合、同じ old/new ペアを最大 5 回まで再試行していました。逆アセンブルサービスが、終了コード 0 で IL を出さない実行を失敗した試行として扱い、引数セットと逆アセンブラのフォールバックを自ら行うようになったこと、また空の結果は同じツールとアセンブリの組み合わせでは毎回同じになることから、この再試行は同じ結果を繰り返すだけでした。各ペアの逆アセンブルは 1 回にし、いずれか片側でも raw IL が空の場合(規約に従わない `IDotNetDisassembleService` 実装でのみ起こり得る)はエラー診断を出して即座に失敗させます。診断から `Attempt=` / `WillRetry=` を除きました。フィルタ後に空になった側は引き続き警告としてログ出力します。対象: `Services/ILOutputService.cs`, `USER_GUIDE.md`。テスト: `DiffDotNetAssembliesAsync_WhenRawIlSideIsEmpty_ThrowsWithoutRetrying`, `DiffDotNetAssembliesAsync_WhenFilteredIlSideIsEmpty_LogsWarningAndCompares`。 + #### 修正 - **ilspycmd の `-o` フォールバックで実際に書き出された IL を読むように修正** — `ilspycmd -o` は出力ディレクトリを受け取り、その中に `<入力名>.il` を書き出しますが、nildiff はファイルパスを渡していたため、このフォールバックは正常終了しても常に空の IL を返し、一時フォルダに `ilspy_out_*` ディレクトリを残していました。新しい一時ディレクトリを渡して生成された `<入力名>.il` ファイルを読み取り、失敗やタイムアウトを含むすべての試行の後にディレクトリを再帰的に削除するようにしました。対象: `Services/DotNetDisassembleService.cs`, `Services/DotNetDisassembleService.Streaming.cs`, `Services/DotNetDisassembleService.VersionLabel.cs`, `FolderDiffIL4DotNet.Tests/Helpers/FakeDisassemblerProgram.cs`。テスト: `DisassembleAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt`, `DisassemblePairAsLinesWithSameDisassemblerAsync_WhenIlspyStdoutModeFails_ReadsIlFromOutputDirectoryAndRemovesIt`, `ResolveIlspyOutputFile_ReturnsInputNamedIlFileOnly`, `BuildArgSets_IlspyCommand_PassesTemporaryOutputDirectoryToOutputFlag`, `CleanupTemporaryPathBestEffort_WhenPathIsDirectory_DeletesItRecursivelyWithoutWarning`。 diff --git a/FolderDiffIL4DotNet.Tests/Services/ILOutputServiceTests.Precompute.cs b/FolderDiffIL4DotNet.Tests/Services/ILOutputServiceTests.Precompute.cs index b71f8eb0..898cb6e7 100644 --- a/FolderDiffIL4DotNet.Tests/Services/ILOutputServiceTests.Precompute.cs +++ b/FolderDiffIL4DotNet.Tests/Services/ILOutputServiceTests.Precompute.cs @@ -96,8 +96,12 @@ public async Task DiffDotNetAssembliesAsync_WhenIlTextOutputFails_LogsRelativeAn Assert.Same(exception, error.Exception); } + /// + /// An empty raw IL side fails immediately without re-disassembling: the disassembler is called once, a single error diagnostic is logged, and the exception reports the raw line counts. + /// raw IL の片側が空の場合、再逆アセンブルせず即座に失敗することを検証します。逆アセンブラの呼び出しは 1 回、エラー診断は 1 件で、例外は raw の行数を報告します。 + /// [Fact] - public async Task DiffDotNetAssembliesAsync_WhenOneIlSideStaysEmpty_ThrowsAfterRetryLimit() + public async Task DiffDotNetAssembliesAsync_WhenRawIlSideIsEmpty_ThrowsWithoutRetrying() { var config = new ConfigSettingsBuilder { @@ -124,66 +128,26 @@ public async Task DiffDotNetAssembliesAsync_WhenOneIlSideStaysEmpty_ThrowsAfterR var exception = await Assert.ThrowsAsync(() => service.DiffDotNetAssembliesAsync("lib/app.dll", "/virtual/old", "/virtual/new", shouldOutputIlText: true)); - Assert.Equal(5, disassembleService.LineDisassemblyCalls); - var warnings = logger.Entries.Where(entry => entry.LogLevel == AppLogLevel.Warning).ToList(); - Assert.Equal(4, warnings.Count); - Assert.Contains("IL comparison raw disassembly produced an empty line set", warnings[0].Message, StringComparison.Ordinal); - Assert.Contains("RawOldLines=0", warnings[0].Message, StringComparison.Ordinal); - Assert.Contains("RawNewLines=1", warnings[0].Message, StringComparison.Ordinal); - Assert.Contains("ShouldOutputIlText=True", warnings[0].Message, StringComparison.Ordinal); - Assert.Contains("Attempt=1/5", warnings[0].Message, StringComparison.Ordinal); - Assert.Contains("WillRetry=True", warnings[0].Message, StringComparison.Ordinal); + Assert.Equal(1, disassembleService.LineDisassemblyCalls); + Assert.DoesNotContain(logger.Entries, entry => entry.LogLevel == AppLogLevel.Warning); var error = Assert.Single(logger.Entries, entry => entry.LogLevel == AppLogLevel.Error); Assert.Contains("IL comparison raw disassembly produced an empty line set", error.Message, StringComparison.Ordinal); - Assert.Contains("Attempt=5/5", error.Message, StringComparison.Ordinal); - Assert.Contains("WillRetry=False", error.Message, StringComparison.Ordinal); - Assert.Contains("0 vs N lines", error.Message, StringComparison.Ordinal); - Assert.Contains("IL comparison raw disassembly stayed empty after 5 attempts", exception.Message, StringComparison.Ordinal); + Assert.Contains("RawOldLines=0", error.Message, StringComparison.Ordinal); + Assert.Contains("RawNewLines=1", error.Message, StringComparison.Ordinal); + Assert.Contains("ShouldOutputIlText=True", error.Message, StringComparison.Ordinal); + Assert.DoesNotContain("Attempt", error.Message, StringComparison.Ordinal); + Assert.DoesNotContain("0 vs N lines", error.Message, StringComparison.Ordinal); + Assert.Contains("IL comparison raw disassembly returned an empty line set", exception.Message, StringComparison.Ordinal); Assert.Contains("RawOldLines=0", exception.Message, StringComparison.Ordinal); Assert.Contains("RawNewLines=1", exception.Message, StringComparison.Ordinal); - Assert.Contains("Attempts=5", exception.Message, StringComparison.Ordinal); } + /// + /// When ignore rules remove every IL line on one side, the comparison still completes after a single disassembly and logs a warning with the raw and filtered line counts. + /// 無視規則で片側の IL 行がすべて除去された場合でも、逆アセンブル 1 回で比較を完了し、raw とフィルタ後の行数を含む警告をログ出力することを検証します。 + /// [Fact] - public async Task DiffDotNetAssembliesAsync_WhenRawIlSideRecovers_RetriesAndWritesRecoveredLines() - { - var config = new ConfigSettingsBuilder - { - IgnoredExtensions = new(), - TextFileExtensions = new() - }.Build(); - var logger = new TestLogger(logFileAbsolutePath: "test.log"); - var executionContext = new DiffExecutionContext( - oldFolderAbsolutePath: "/tmp/fd-iloutput-old", - newFolderAbsolutePath: "/tmp/fd-iloutput-new", - reportsFolderAbsolutePath: "/tmp/fd-iloutput-report", - optimizeForNetworkShares: false, - detectedNetworkOld: false, - detectedNetworkNew: false); - var ilTextOutputService = new CapturingIlTextOutputService(); - var disassembleService = new EmptyOldThenSuccessfulDisassembleService(); - var service = new ILOutputService( - config, - executionContext, - ilTextOutputService, - disassembleService, - ilCache: null, - logger); - - var result = await service.DiffDotNetAssembliesAsync("lib/app.dll", "/virtual/old", "/virtual/new", shouldOutputIlText: true); - - Assert.False(result.AreEqual); - Assert.Equal(2, disassembleService.LineDisassemblyCalls); - Assert.Equal(new[] { "recovered-old-il" }, ilTextOutputService.OldLines); - Assert.Equal(new[] { "recovered-new-il" }, ilTextOutputService.NewLines); - var warning = Assert.Single(logger.Entries, entry => entry.LogLevel == AppLogLevel.Warning); - Assert.Contains("IL comparison raw disassembly produced an empty line set", warning.Message, StringComparison.Ordinal); - Assert.Contains("Attempt=1/5", warning.Message, StringComparison.Ordinal); - Assert.Contains("WillRetry=True", warning.Message, StringComparison.Ordinal); - } - - [Fact] - public async Task DiffDotNetAssembliesAsync_WhenFilteredIlSideIsEmpty_LogsWithoutRetrying() + public async Task DiffDotNetAssembliesAsync_WhenFilteredIlSideIsEmpty_LogsWarningAndCompares() { var config = new ConfigSettingsBuilder { @@ -220,8 +184,8 @@ public async Task DiffDotNetAssembliesAsync_WhenFilteredIlSideIsEmpty_LogsWithou Assert.Contains("IL comparison filtered IL produced an empty line set", warning.Message, StringComparison.Ordinal); Assert.Contains("RawOldLines=1", warning.Message, StringComparison.Ordinal); Assert.Contains("FilteredOldLines=0", warning.Message, StringComparison.Ordinal); - Assert.Contains("Attempt=1/5", warning.Message, StringComparison.Ordinal); - Assert.Contains("WillRetry=False", warning.Message, StringComparison.Ordinal); + Assert.Contains("0 vs N lines", warning.Message, StringComparison.Ordinal); + Assert.DoesNotContain("Attempt", warning.Message, StringComparison.Ordinal); } [Theory] @@ -335,31 +299,6 @@ public Task PrefetchIlCacheAsync(IEnumerable paths, int maxParallel, Can => Task.CompletedTask; } - private sealed class EmptyOldThenSuccessfulDisassembleService : IDotNetDisassembleService - { - public int LineDisassemblyCalls { get; private set; } - - public Task<(string oldIlText, string oldCommandString, string newIlText, string newCommandString)> DisassemblePairWithSameDisassemblerAsync( - string oldPath, string newPath, CancellationToken cancellationToken = default) - => Task.FromResult<(string, string, string, string)>((string.Empty, string.Empty, string.Empty, string.Empty)); - - public Task<(IReadOnlyList oldIlLines, string oldCommandString, IReadOnlyList newIlLines, string newCommandString)> DisassemblePairAsLinesWithSameDisassemblerAsync( - string oldPath, string newPath, CancellationToken cancellationToken = default) - { - LineDisassemblyCalls++; - IReadOnlyList oldLines = LineDisassemblyCalls == 1 - ? Array.Empty() - : new[] { "recovered-old-il" }; - IReadOnlyList newLines = LineDisassemblyCalls == 1 - ? new[] { "new-il" } - : new[] { "recovered-new-il" }; - return Task.FromResult<(IReadOnlyList, string, IReadOnlyList, string)>((oldLines, "dotnet ildasm old.dll (version: 1.0.0)", newLines, "dotnet ildasm new.dll (version: 1.0.0)")); - } - - public Task PrefetchIlCacheAsync(IEnumerable paths, int maxParallel, CancellationToken cancellationToken = default) - => Task.CompletedTask; - } - private sealed class FilteredEmptyOldDisassembleService : IDotNetDisassembleService { public int LineDisassemblyCalls { get; private set; } diff --git a/Services/ILOutputService.cs b/Services/ILOutputService.cs index ca94392b..6b6a2a2c 100644 --- a/Services/ILOutputService.cs +++ b/Services/ILOutputService.cs @@ -23,8 +23,7 @@ public sealed partial class ILOutputService : IILOutputService private const string VERSION_LABEL_PREFIX = " (version: "; private const string ERROR_FAILED_TO_OUTPUT_IL = $"Failed to output {Constants.LABEL_IL}."; private const int IL_FILTER_STRING_MIN_LENGTH = 4; - private const int EMPTY_IL_LINE_SET_DISASSEMBLY_ATTEMPT_LIMIT = 5; - private static readonly string ERROR_EMPTY_RAW_IL_AFTER_RETRY_LIMIT = $"IL comparison raw disassembly stayed empty after {EMPTY_IL_LINE_SET_DISASSEMBLY_ATTEMPT_LIMIT} attempts."; + private const string ERROR_EMPTY_RAW_IL = "IL comparison raw disassembly returned an empty line set."; private readonly IReadOnlyConfigSettings _config; private readonly ILCache? _ilCache; private readonly IILTextOutputService _ilTextOutputService; @@ -126,12 +125,14 @@ public async Task PrecomputeAsync(IEnumerable filesAbsolutePaths, int ma /// Disassembles old/new .NET assemblies with the same disassembler, applies built-in normalization plus enabled configured normalization and line filtering, and compares the IL. /// Uses line-based streaming: reads process stdout line-by-line (avoids LOH allocations) and compares /// without materializing filtered line lists when IL text output is not required. - /// Retries raw disassembly up to 5 attempts when one or both raw sides are empty, then fails if any raw side is still empty; filtered-empty results are logged without retrying. + /// Disassembles each pair once: already falls back across argument sets and disassemblers and never reports empty IL as success, + /// so empty raw IL on either side fails immediately instead of being retried; filtered-empty results are logged. /// Outputs IL text files when is true. /// old/new の .NET アセンブリを同一逆アセンブラで逆アセンブルし、組み込み正規化と、有効化された設定ベースの正規化・行フィルタを適用したうえで IL を比較します。 /// 行単位のストリーミング処理を使用: プロセスの stdout を行単位で読み取り(LOH 割り当てを回避)、 /// IL テキスト出力が不要な場合はフィルタ済み行リストを実体化せずに比較します。 - /// raw 側の少なくとも片側が空の場合は最大 5 回まで再逆アセンブルし、それでも少なくとも片側が空なら失敗させます。フィルタ後に空になった場合はログのみで再試行しません。 + /// 各ペアの逆アセンブルは 1 回だけです。 が引数セットと逆アセンブラのフォールバックを済ませ、空の IL を成功として返さないため、 + /// old/new のいずれか片側でも raw IL が空なら再試行せず即座に失敗させます。フィルタ後に空になった場合はログ出力します。 /// が true の場合は IL テキストをファイルに出力します。 /// public async Task<(bool AreEqual, string? DisassemblerLabel)> DiffDotNetAssembliesAsync(string fileRelativePath, string oldFolderAbsolutePath, string newFolderAbsolutePath, bool shouldOutputIlText, CancellationToken cancellationToken = default) @@ -146,134 +147,121 @@ public async Task PrecomputeAsync(IEnumerable filesAbsolutePaths, int ma ? ILConfiguredSubstringHelper.GetEffectiveNormalizationSubstrings(_config.ILNormalizeContainingStrings) : new List(); bool shouldIgnore = _config.ShouldIgnoreILLinesContainingConfiguredStrings; - for (int attemptNumber = 1; attemptNumber <= EMPTY_IL_LINE_SET_DISASSEMBLY_ATTEMPT_LIMIT; attemptNumber++) + + cancellationToken.ThrowIfCancellationRequested(); + + // Disassemble old/new as lines (reads process stdout line-by-line, avoiding LOH-sized string allocations). + // old/new を行リストとして逆アセンブル(プロセス stdout を行単位で読み取り、LOH サイズの文字列割り当てを回避)。 + var (il1Lines, commandString1, il2Lines, commandString2) = + await _dotNetDisassembleService.DisassemblePairAsLinesWithSameDisassemblerAsync(file1AbsolutePath, file2AbsolutePath, cancellationToken); + var disassemblerLabel = BuildComparisonDisassemblerLabel(commandString1, commandString2); + if (il1Lines.Count == 0 || il2Lines.Count == 0) { - cancellationToken.ThrowIfCancellationRequested(); + // The disassembler service never reports empty IL as success, so an empty side here is a contract violation by the implementation: fail instead of comparing. + // 逆アセンブルサービスは空の IL を成功として返さないため、ここで空の側があるのは実装側の契約違反であり、比較せずに失敗させる。 + LogIlLineSetDiagnostics( + AppLogLevel.Error, + "raw disassembly", + fileRelativePath, + file1AbsolutePath, + file2AbsolutePath, + disassemblerLabel, + il1Lines.Count, + il2Lines.Count, + filteredOldLineCount: null, + filteredNewLineCount: null, + shouldOutputIlText, + shouldIgnore, + ilIgnoreContainingStrings.Count); + throw new InvalidOperationException( + $"{ERROR_EMPTY_RAW_IL} File='{fileRelativePath}', Old='{file1AbsolutePath}', New='{file2AbsolutePath}', RawOldLines={il1Lines.Count}, RawNewLines={il2Lines.Count}."); + } + + string configuredNormalizedValue = ilNormalizeContainingStrings.Count == 0 + ? CONFIGURED_NORMALIZED_VALUE + : CreateCollisionFreeConfiguredNormalizedValue(il1Lines, il2Lines); - // Disassemble old/new as lines (reads process stdout line-by-line, avoiding LOH-sized string allocations). - // old/new を行リストとして逆アセンブル(プロセス stdout を行単位で読み取り、LOH サイズの文字列割り当てを回避)。 - var (il1Lines, commandString1, il2Lines, commandString2) = - await _dotNetDisassembleService.DisassemblePairAsLinesWithSameDisassemblerAsync(file1AbsolutePath, file2AbsolutePath, cancellationToken); - var disassemblerLabel = BuildComparisonDisassemblerLabel(commandString1, commandString2); - bool rawLineSetIsEmpty = il1Lines.Count == 0 || il2Lines.Count == 0; - bool canRetryEmptyLineSet = attemptNumber < EMPTY_IL_LINE_SET_DISASSEMBLY_ATTEMPT_LIMIT; - if (rawLineSetIsEmpty) + if (!shouldOutputIlText) + { + // Streaming comparison: filter and compare line-by-line without materializing filtered lists. + // If lines differ, fall back to block-aware comparison to handle method reordering. + // ストリーミング比較: フィルタ済み行リストを実体化せずに行単位でフィルタ・比較する。 + // 行単位で不一致の場合、メソッド並び順変更を考慮しブロック単位比較にフォールバック。 + bool areILsEqual = StreamingFilteredSequenceEqual( + il1Lines, + il2Lines, + shouldIgnore, + ilIgnoreContainingStrings, + ilNormalizeContainingStrings, + configuredNormalizedValue); + if (!areILsEqual) { - AppLogLevel logLevel = canRetryEmptyLineSet ? AppLogLevel.Warning : AppLogLevel.Error; - LogIlLineSetDiagnostics( - logLevel, - "raw disassembly", + var filtered1 = FilterIlLines(il1Lines, shouldIgnore, ilIgnoreContainingStrings, ilNormalizeContainingStrings, configuredNormalizedValue); + var filtered2 = FilterIlLines(il2Lines, shouldIgnore, ilIgnoreContainingStrings, ilNormalizeContainingStrings, configuredNormalizedValue); + LogEmptyFilteredLineSetIfNeeded( fileRelativePath, file1AbsolutePath, file2AbsolutePath, disassemblerLabel, - il1Lines.Count, - il2Lines.Count, - filteredOldLineCount: null, - filteredNewLineCount: null, - shouldOutputIlText, - shouldIgnore, - ilIgnoreContainingStrings.Count, - attemptNumber, - EMPTY_IL_LINE_SET_DISASSEMBLY_ATTEMPT_LIMIT, - canRetryEmptyLineSet); - if (canRetryEmptyLineSet) - { - continue; - } - - throw new InvalidOperationException( - $"{ERROR_EMPTY_RAW_IL_AFTER_RETRY_LIMIT} File='{fileRelativePath}', Old='{file1AbsolutePath}', New='{file2AbsolutePath}', RawOldLines={il1Lines.Count}, RawNewLines={il2Lines.Count}, Attempts={attemptNumber}."); - } - - string configuredNormalizedValue = ilNormalizeContainingStrings.Count == 0 - ? CONFIGURED_NORMALIZED_VALUE - : CreateCollisionFreeConfiguredNormalizedValue(il1Lines, il2Lines); - - if (!shouldOutputIlText) - { - // Streaming comparison: filter and compare line-by-line without materializing filtered lists. - // If lines differ, fall back to block-aware comparison to handle method reordering. - // ストリーミング比較: フィルタ済み行リストを実体化せずに行単位でフィルタ・比較する。 - // 行単位で不一致の場合、メソッド並び順変更を考慮しブロック単位比較にフォールバック。 - bool areILsEqual = StreamingFilteredSequenceEqual( il1Lines, il2Lines, + filtered1.Count, + filtered2.Count, + shouldOutputIlText, shouldIgnore, - ilIgnoreContainingStrings, - ilNormalizeContainingStrings, - configuredNormalizedValue); - if (!areILsEqual) - { - var filtered1 = FilterIlLines(il1Lines, shouldIgnore, ilIgnoreContainingStrings, ilNormalizeContainingStrings, configuredNormalizedValue); - var filtered2 = FilterIlLines(il2Lines, shouldIgnore, ilIgnoreContainingStrings, ilNormalizeContainingStrings, configuredNormalizedValue); - LogEmptyFilteredLineSetIfNeeded( - fileRelativePath, - file1AbsolutePath, - file2AbsolutePath, - disassemblerLabel, - il1Lines, - il2Lines, - filtered1.Count, - filtered2.Count, - rawLineSetIsEmpty, - shouldOutputIlText, - shouldIgnore, - ilIgnoreContainingStrings.Count, - attemptNumber); + ilIgnoreContainingStrings.Count); - areILsEqual = BlockAwareSequenceEqual(filtered1, filtered2); - } - return (areILsEqual, disassemblerLabel); + areILsEqual = BlockAwareSequenceEqual(filtered1, filtered2); } + return (areILsEqual, disassemblerLabel); + } - // Materialized path: need full filtered lists for IL text file output. - // 実体化パス: IL テキストファイル出力用にフィルタ済み全行リストが必要。 - var filteredIl1Lines = FilterIlLines(il1Lines, shouldIgnore, ilIgnoreContainingStrings, ilNormalizeContainingStrings, configuredNormalizedValue); - var filteredIl2Lines = FilterIlLines(il2Lines, shouldIgnore, ilIgnoreContainingStrings, ilNormalizeContainingStrings, configuredNormalizedValue); - LogEmptyFilteredLineSetIfNeeded( - fileRelativePath, - file1AbsolutePath, - file2AbsolutePath, - disassemblerLabel, - il1Lines, - il2Lines, - filteredIl1Lines.Count, - filteredIl2Lines.Count, - rawLineSetIsEmpty, - shouldOutputIlText, - shouldIgnore, - ilIgnoreContainingStrings.Count, - attemptNumber); + // Materialized path: need full filtered lists for IL text file output. + // 実体化パス: IL テキストファイル出力用にフィルタ済み全行リストが必要。 + var filteredIl1Lines = FilterIlLines(il1Lines, shouldIgnore, ilIgnoreContainingStrings, ilNormalizeContainingStrings, configuredNormalizedValue); + var filteredIl2Lines = FilterIlLines(il2Lines, shouldIgnore, ilIgnoreContainingStrings, ilNormalizeContainingStrings, configuredNormalizedValue); + LogEmptyFilteredLineSetIfNeeded( + fileRelativePath, + file1AbsolutePath, + file2AbsolutePath, + disassemblerLabel, + il1Lines, + il2Lines, + filteredIl1Lines.Count, + filteredIl2Lines.Count, + shouldOutputIlText, + shouldIgnore, + ilIgnoreContainingStrings.Count); - bool areEqual = filteredIl1Lines.SequenceEqual(filteredIl2Lines); - if (!areEqual) - { - // Fall back to block-aware comparison to handle method/class reordering by the compiler. - // コンパイラによるメソッド・クラスの並び替えを考慮し、ブロック単位比較にフォールバック。 - areEqual = BlockAwareSequenceEqual(filteredIl1Lines, filteredIl2Lines); - } - try - { - // Save the filtered and normalized IL text as *_IL.txt. - // フィルタ・正規化済みの IL テキストを *_IL.txt として保存する。 - await _ilTextOutputService.WriteFullIlTextsAsync(fileRelativePath, filteredIl1Lines, filteredIl2Lines); - } - catch (Exception ex) when (ExceptionFilters.IsPathOrFileIoRecoverable(ex)) - { - // Log error with exception details and re-throw on IL text output failure. - // IL テキスト出力に失敗した場合は例外詳細付きエラーログを出しつつ再スロー。 - _logger.LogMessage(AppLogLevel.Error, - $"{ERROR_FAILED_TO_OUTPUT_IL} for '{fileRelativePath}' (Old='{file1AbsolutePath}', New='{file2AbsolutePath}', {ex.GetType().Name}): {ex.Message}", - shouldOutputMessageToConsole: true, ex); - throw; - } - return (areEqual, disassemblerLabel); + bool areEqual = filteredIl1Lines.SequenceEqual(filteredIl2Lines); + if (!areEqual) + { + // Fall back to block-aware comparison to handle method/class reordering by the compiler. + // コンパイラによるメソッド・クラスの並び替えを考慮し、ブロック単位比較にフォールバック。 + areEqual = BlockAwareSequenceEqual(filteredIl1Lines, filteredIl2Lines); } - - throw new InvalidOperationException("IL disassembly retry loop ended without producing a comparison result."); + try + { + // Save the filtered and normalized IL text as *_IL.txt. + // フィルタ・正規化済みの IL テキストを *_IL.txt として保存する。 + await _ilTextOutputService.WriteFullIlTextsAsync(fileRelativePath, filteredIl1Lines, filteredIl2Lines); + } + catch (Exception ex) when (ExceptionFilters.IsPathOrFileIoRecoverable(ex)) + { + // Log error with exception details and re-throw on IL text output failure. + // IL テキスト出力に失敗した場合は例外詳細付きエラーログを出しつつ再スロー。 + _logger.LogMessage(AppLogLevel.Error, + $"{ERROR_FAILED_TO_OUTPUT_IL} for '{fileRelativePath}' (Old='{file1AbsolutePath}', New='{file2AbsolutePath}', {ex.GetType().Name}): {ex.Message}", + shouldOutputMessageToConsole: true, ex); + throw; + } + return (areEqual, disassemblerLabel); } + /// + /// Logs a warning when filtering left one or both sides without IL lines (raw IL is known to be non-empty at this point). + /// フィルタ後に old/new の少なくとも片側の IL 行が無くなった場合に警告をログ出力します(この時点で raw IL が空でないことは確定済み)。 + /// private void LogEmptyFilteredLineSetIfNeeded( string fileRelativePath, string oldFileAbsolutePath, @@ -283,14 +271,11 @@ private void LogEmptyFilteredLineSetIfNeeded( IReadOnlyList rawNewLines, int filteredOldLineCount, int filteredNewLineCount, - bool rawLineSetIsEmpty, bool shouldOutputIlText, bool shouldIgnoreContainingStrings, - int ignoreStringCount, - int attemptNumber) + int ignoreStringCount) { - bool filteredLineSetIsEmpty = !rawLineSetIsEmpty && (filteredOldLineCount == 0 || filteredNewLineCount == 0); - if (!filteredLineSetIsEmpty) + if (filteredOldLineCount != 0 && filteredNewLineCount != 0) { return; } @@ -308,12 +293,13 @@ private void LogEmptyFilteredLineSetIfNeeded( filteredNewLineCount, shouldOutputIlText, shouldIgnoreContainingStrings, - ignoreStringCount, - attemptNumber, - EMPTY_IL_LINE_SET_DISASSEMBLY_ATTEMPT_LIMIT, - willRetry: false); + ignoreStringCount); } + /// + /// Logs the line counts and the settings that can empty a line set, for the raw or filtered IL stage. + /// raw またはフィルタ後の IL 段階について、行数と行セットを空にし得る設定をログ出力します。 + /// private void LogIlLineSetDiagnostics( AppLogLevel logLevel, string stage, @@ -327,13 +313,16 @@ private void LogIlLineSetDiagnostics( int? filteredNewLineCount, bool shouldOutputIlText, bool shouldIgnoreContainingStrings, - int ignoreStringCount, - int attemptNumber, - int maxAttemptCount, - bool willRetry) + int ignoreStringCount) { - string filteredCounts = filteredOldLineCount.HasValue && filteredNewLineCount.HasValue - ? $", FilteredOldLines={filteredOldLineCount.Value}, FilteredNewLines={filteredNewLineCount.Value}" + bool hasFilteredCounts = filteredOldLineCount.HasValue && filteredNewLineCount.HasValue; + string filteredCounts = hasFilteredCounts + ? $", FilteredOldLines={filteredOldLineCount.GetValueOrDefault()}, FilteredNewLines={filteredNewLineCount.GetValueOrDefault()}" + : string.Empty; + // Only a filtered-empty side reaches the comparison; an empty raw side fails before it. + // 比較まで進むのはフィルタ後に空になった場合だけで、raw が空の場合は比較前に失敗する。 + string consequence = hasFilteredCounts + ? " Empty IL on one side can later appear as an inline diff skip with 0 vs N lines." : string.Empty; // This diagnostic records settings that can cause an empty line set. Ignore rules can remove lines, // whereas built-in and configured normalization only replace text and therefore cannot affect line counts. @@ -341,7 +330,7 @@ private void LogIlLineSetDiagnostics( // 組み込み・設定正規化は文字列を置換するだけで行数に影響しない。 _logger.LogMessage( logLevel, - $"IL comparison {stage} produced an empty line set for '{fileRelativePath}' (Old='{oldFileAbsolutePath}', New='{newFileAbsolutePath}', Disassembler='{disassemblerLabel ?? "(unknown)"}', RawOldLines={rawOldLineCount}, RawNewLines={rawNewLineCount}{filteredCounts}, ShouldOutputIlText={shouldOutputIlText}, IgnoreConfiguredStrings={shouldIgnoreContainingStrings}, IgnoreStringCount={ignoreStringCount}, Attempt={attemptNumber}/{maxAttemptCount}, WillRetry={willRetry}). Empty IL on one side can later appear as an inline diff skip with 0 vs N lines.", + $"IL comparison {stage} produced an empty line set for '{fileRelativePath}' (Old='{oldFileAbsolutePath}', New='{newFileAbsolutePath}', Disassembler='{disassemblerLabel ?? "(unknown)"}', RawOldLines={rawOldLineCount}, RawNewLines={rawNewLineCount}{filteredCounts}, ShouldOutputIlText={shouldOutputIlText}, IgnoreConfiguredStrings={shouldIgnoreContainingStrings}, IgnoreStringCount={ignoreStringCount}).{consequence}", shouldOutputMessageToConsole: true); } diff --git a/USER_GUIDE.md b/USER_GUIDE.md index 0f8bed9f..33cc5ac7 100644 --- a/USER_GUIDE.md +++ b/USER_GUIDE.md @@ -501,8 +501,8 @@ Important details: - Outside creator mode, effective `ILNormalizeContainingStrings` values are applied in their `config.json` array order. In creator mode, profile values are applied first in profile order, followed by the configured values in their `config.json` array order. The combined configured/profile list is limited to 256 entries of up to 4096 characters each; creator-profile and duplicate entries count toward the limit. The report table preserves the resulting application order. Empty values are omitted and exact duplicates appear only once in the effective table. Configured normalization uses sequential ordinal matching against portions of the raw line that have not already been replaced; inserted markers are protected from later rules. Across all configured rules, one IL line may produce at most 65,536 non-overlapping replacements and a normalized result of at most 4,194,304 UTF-16 code units; exceeding either limit stops the comparison with `InvalidDataException` before the expanded result is allocated. When one distinct value contains another, the result can depend on application order. When normalization is enabled, exact duplicates and containment relationships produce warnings in the console and report, including relationships that arise after creator-profile values are prepended to the configured values. At most 100 warning details are emitted, followed by a summary of any additional suppressed warnings; disabled normalization skips these relationship checks. - Markdown configured-substring tables use reversible `(Escaped)` columns: each literal backslash appears as `\\`, tabs, carriage returns, and line feeds appear as `\t`, `\r`, and `\n`, and every other whitespace, control, or format character appears as `\uXXXX` or `\UXXXXXXXX` (for example, a space is `\u0020`). Markdown punctuation is isolated with numeric character references so values cannot become emphasis, links, images, or other inline syntax. These escapes affect report display only; matching still uses the exact configured string. The HTML report keeps its existing pre-wrapped display for ordinary whitespace but is not the canonical escaped representation. - Configured-substring safety warnings render configured values in a single-line visible escape form for line breaks, other whitespace, control/format characters, combining marks, lone UTF-16 surrogates, and backslashes while keeping CommonMark punctuation inert, so configuration text cannot alter console/log or Markdown/HTML report structure. Matching still uses the original value. -- If raw disassembly returns an empty line set on one or both sides, `nildiff` retries that old/new pair up to 5 attempts. If any raw side is still empty after the retry limit, the comparison fails with an error instead of writing empty `*_IL.txt` output. -- If filtering removes all IL lines on one or both sides after raw disassembly succeeded, `nildiff` logs the empty filtered side but does not retry, because that can be a legitimate result of the configured ignore rules. +- A disassembler run that exits successfully without IL counts as a failed attempt: `nildiff` logs a warning with the tool's stderr and tries the next argument set or disassembler. If no disassembler produces IL for one side, the comparison fails with an error instead of writing empty `*_IL.txt` output. The same old/new pair is not re-disassembled, because an empty result is deterministic for a given tool and assembly. +- If filtering removes all IL lines on one or both sides after raw disassembly succeeded, `nildiff` logs the empty filtered side and continues the comparison, because that can be a legitimate result of the configured ignore rules. - If IL comparison itself fails, the run stops instead of silently falling back to a weaker comparison. @@ -1411,8 +1411,8 @@ flowchart TD - creatorモードでない場合、実効 `ILNormalizeContainingStrings` は `config.json` の配列順で適用します。creatorモードでは、プロファイル値をプロファイル内の順序で先に適用し、その後に設定値を `config.json` の配列順で適用します。設定値とプロファイル値の結合後は最大256件、各値は最大4096文字で、プロファイル値と重複値も件数上限に含みます。レポートの表にも、この結合後の適用順で表示します。空の値は省略し、完全重複値は実効表へ1回だけ表示します。設定正規化は、まだ置換していないraw行部分だけをordinal一致で順番に処理し、挿入済みマーカーを後続規則の処理対象にしません。設定した全規則を合わせて、1 IL行で生成できる非重複置換は最大65,536件、正規化後の結果は最大4,194,304 UTF-16コード単位です。いずれかを超える場合は、展開後の結果を割り当てる前に `InvalidDataException` で比較を停止します。異なる設定値の一方が他方を含む場合は、それでも適用順によって結果が変わり得ます。正規化が有効な場合、完全重複または包含関係があると、creatorプロファイル値を設定値より前へ追加した結果生じた関係も含めて、コンソールとレポートに警告します。警告は最大100件の詳細と超過分の抑制件数を示す要約を出力します。正規化が無効な場合はこれらの関係検査を行いません。 - Markdownレポートの設定部分文字列表では、可逆な `(Escaped)` 列を使います。実際のbackslashは1文字ごとに `\\`、tab、carriage return、line feedは `\t`、`\r`、`\n`、その他の空白・control・format文字は `\uXXXX` または `\UXXXXXXXX`(spaceなら `\u0020`)と表示します。Markdown記号は数値文字参照で分離し、値がemphasis、link、imageなどのinline構文にならないようにします。このescapeはレポート表示だけに適用し、一致判定では設定文字列をそのまま使います。HTMLレポートは通常の空白に対する既存のpre-wrap表示を維持しますが、正本となるescape表現ではありません。 - 設定部分文字列の安全性警告では、改行、その他の空白、control/format文字、combining mark、単独UTF-16 surrogate、backslashを1行の可視escapeとして表示し、CommonMark記号を不活性化します。これにより、設定文字列がconsole/logやMarkdown/HTMLレポートの構造を変更できないようにします。一致判定には元の設定値をそのまま使います。 -- フィルタ前の raw 逆アセンブル結果が old/new の少なくとも片側で空になった場合、`nildiff` は同じペアを最大 5 回まで再試行します。それでも少なくとも片側が空なら、空の `*_IL.txt` を書かずに error で比較を失敗させます。 -- raw 逆アセンブルは成功し、その後のフィルタで少なくとも片側の IL 行がすべて除外された場合は、設定された無視ルールの正当な結果でありえるため、空のフィルタ後行セットをログに残しますが再試行はしません。 +- 正常終了したのに IL を出さなかった逆アセンブラの実行は失敗した試行として扱い、`nildiff` はツールの stderr を含む警告をログ出力して、次の引数セットまたは逆アセンブラを試します。どの逆アセンブラでも片側の IL が得られない場合は、空の `*_IL.txt` を書かずに error で比較を失敗させます。空の結果は同じツールとアセンブリの組み合わせでは毎回同じになるため、同じ old/new ペアを再逆アセンブルすることはしません。 +- raw 逆アセンブルは成功し、その後のフィルタで少なくとも片側の IL 行がすべて除外された場合は、設定された無視ルールの正当な結果でありえるため、空のフィルタ後行セットをログに残したうえで比較を続けます。 - IL 比較そのものに失敗した場合は、弱い比較へ黙って落とさず、その実行全体を停止します。