diff --git a/Engines/Evb/EvbDetectionHelper.cs b/Engines/Evb/EvbDetectionHelper.cs index 953b03e..fe8e165 100644 --- a/Engines/Evb/EvbDetectionHelper.cs +++ b/Engines/Evb/EvbDetectionHelper.cs @@ -1,30 +1,40 @@ -using System; +using System; +using System.Collections.Generic; using System.IO; using System.Linq; namespace GameLauncher.Engines.Evb { /// - /// Detects Enigma Virtual Box (EVB) packed executables using reliable PE signatures - /// only. Heuristic checks such as file name or extension are intentionally avoided so - /// that ordinary (unpacked) games are never misclassified. + /// Detects Enigma Virtual Box (EVB) packed executables that are actually compressed + /// with EVB and unpackable by evbunpack. /// /// Detection strategy: - /// Parse the PE header and inspect the section table for the packer's sections - /// (".enigma1" / ".enigma2"). A present section is a decisive match; anything else - /// is treated as "not EVB" so plain (unpacked) games are never misclassified. + /// 1. Parse the PE header and inspect the section table for the packer's + /// .enigma1 section (required by evbunpack to restore the PE). + /// 2. Verify the presence of the EVB virtual filesystem pack header signature + /// ("EVB\0" / 0x45, 0x56, 0x42, 0x00) inside the Enigma section + /// data or PE overlay (required by evbunpack to extract the VFS, and + /// distinguishes Enigma Virtual Box from commercial Enigma Protector DRM which + /// cannot be unpacked). /// /// This class is engine-local and has no side effects. /// public static class EvbDetectionHelper { - /// Section names produced by the packer. - private static readonly string[] EnigmaSections = { ".enigma1", ".enigma2" }; + /// Primary section name required by evbunpack. + private const string EnigmaPrimarySection = ".enigma1"; - /// Returns true when the given executable is packed with EVB. + /// Secondary section name produced by the packer. + private const string EnigmaSecondarySection = ".enigma2"; + + /// EVB virtual filesystem header magic ("EVB\0"). + private static readonly byte[] EvbMagic = { 0x45, 0x56, 0x42, 0x00 }; + + /// Returns true when the given executable is packed with EVB and can be unpacked. /// - /// Reads the PE section table for the packer's section names. Any IO/format error - /// yields false (treated as "not confidently EVB"). + /// Reads the PE section table for .enigma1 and verifies the EVB\0 + /// virtual filesystem header. Any IO/format error yields false. /// public static bool IsEvbPacked(string exePath) { @@ -35,8 +45,7 @@ namespace GameLauncher.Engines.Evb try { - // Decisive: the packer's own PE sections are the only reliable signal. - return HasEnigmaSection(exePath); + return HasExtractableEnigmaPackage(exePath); } catch { @@ -58,8 +67,11 @@ namespace GameLauncher.Engines.Evb try { - return Directory.GetFiles(gameDirectory, "*.exe", SearchOption.TopDirectoryOnly) - .FirstOrDefault(IsEvbPacked); + var exes = Directory.GetFiles(gameDirectory, "*.exe", SearchOption.TopDirectoryOnly) + .Where(f => !IsExcludedUtilityExe(Path.GetFileName(f))) + .OrderBy(f => string.Equals(Path.GetFileName(f), "Game.exe", StringComparison.OrdinalIgnoreCase) ? 0 : 1); + + return exes.FirstOrDefault(IsEvbPacked); } catch { @@ -67,6 +79,15 @@ namespace GameLauncher.Engines.Evb } } + private static bool IsExcludedUtilityExe(string fileName) + { + if (string.IsNullOrEmpty(fileName)) return true; + return fileName.StartsWith("unins", StringComparison.OrdinalIgnoreCase) || + fileName.StartsWith("UnityCrashHandler", StringComparison.OrdinalIgnoreCase) || + fileName.Equals("notification_helper.exe", StringComparison.OrdinalIgnoreCase) || + fileName.Equals("crashpad_handler.exe", StringComparison.OrdinalIgnoreCase); + } + /// /// Returns true when the game directory already holds a completed EVB extraction. /// @@ -97,9 +118,10 @@ namespace GameLauncher.Engines.Evb } /// - /// Parses the PE section table and checks for the EVB packer's section names. + /// Parses the PE section table, verifies the .enigma1 section, and checks + /// for the EVB\0 virtual filesystem header required by evbunpack. /// - private static bool HasEnigmaSection(string exePath) + private static bool HasExtractableEnigmaPackage(string exePath) { using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using var reader = new BinaryReader(fs); @@ -128,22 +150,30 @@ namespace GameLauncher.Engines.Evb return false; } - // COFF header: skip machine + number of sections is at offset 2 from here. - fs.Seek(peOffset + 4, SeekOrigin.Begin); + // COFF header: number of sections is at offset 6 from PE signature (peOffset + 6). + fs.Seek(peOffset + 6, SeekOrigin.Begin); ushort sectionCount = reader.ReadUInt16(); + if (sectionCount == 0 || sectionCount > 96) + { + return false; + } - // Optional header size (end of the optional header) is at offset 20 in the COFF header. + // Optional header size is at offset 20 in the COFF header. fs.Seek(peOffset + 20, SeekOrigin.Begin); ushort optionalHeaderSize = reader.ReadUInt16(); // Section table starts right after the optional header. long sectionTable = peOffset + 24 + optionalHeaderSize; - // Each section header is 40 bytes; the section name is the first 8 bytes. + bool hasEnigma1 = false; + var enigmaRanges = new List<(long Offset, long Size)>(); + long maxSectionEnd = 0; + + // Each section header is 40 bytes. for (int i = 0; i < sectionCount; i++) { long offset = sectionTable + (long)i * 40; - if (offset + 8 > fs.Length) + if (offset + 40 > fs.Length) { break; } @@ -152,13 +182,100 @@ namespace GameLauncher.Engines.Evb var nameBytes = reader.ReadBytes(8); var name = System.Text.Encoding.ASCII.GetString(nameBytes).TrimEnd('\0').Trim(); - foreach (var section in EnigmaSections) + fs.Seek(offset + 16, SeekOrigin.Begin); + uint rawSize = reader.ReadUInt32(); + uint rawPtr = reader.ReadUInt32(); + + if (rawPtr > 0 && rawSize > 0) { - if (string.Equals(name, section, StringComparison.OrdinalIgnoreCase)) + long end = (long)rawPtr + rawSize; + if (end > maxSectionEnd && end <= fs.Length) { - return true; + maxSectionEnd = end; } } + + if (string.Equals(name, EnigmaPrimarySection, StringComparison.OrdinalIgnoreCase)) + { + hasEnigma1 = true; + if (rawPtr > 0 && rawSize > 0 && rawPtr < fs.Length) + { + enigmaRanges.Insert(0, (rawPtr, Math.Min((long)rawSize, fs.Length - rawPtr))); + } + } + else if (string.Equals(name, EnigmaSecondarySection, StringComparison.OrdinalIgnoreCase)) + { + if (rawPtr > 0 && rawSize > 0 && rawPtr < fs.Length) + { + enigmaRanges.Add((rawPtr, Math.Min((long)rawSize, fs.Length - rawPtr))); + } + } + } + + // evbunpack requires the .enigma1 section to unpack and rebuild the executable. + if (!hasEnigma1) + { + return false; + } + + // Also include PE overlay if any bytes exist after the last section. + if (maxSectionEnd > 0 && maxSectionEnd + 64 <= fs.Length) + { + enigmaRanges.Add((maxSectionEnd, fs.Length - maxSectionEnd)); + } + + // Verify that the EVB virtual filesystem signature ("EVB\0") exists in the + // Enigma sections or overlay so that Enigma Protector DRM executables (which + // have .enigma1/.enigma2 but no unpackable EVB VFS) are not misclassified. + foreach (var (rangeOffset, rangeSize) in enigmaRanges) + { + if (ContainsEvbMagicInRange(fs, rangeOffset, rangeSize)) + { + return true; + } + } + + return false; + } + + /// + /// Searches for the "EVB\0" pack header signature within the given file range + /// (scanning up to the first 16 MB of the range in 64 KB chunks). + /// + private static bool ContainsEvbMagicInRange(FileStream fs, long startOffset, long length) + { + const int chunkSize = 64 * 1024; + long maxScan = Math.Min(length, 16L * 1024 * 1024); + if (maxScan < EvbMagic.Length) + { + return false; + } + + var buffer = new byte[chunkSize + EvbMagic.Length]; + long scanned = 0; + + while (scanned < maxScan) + { + long readPos = startOffset + scanned; + int toRead = (int)Math.Min(buffer.Length, (startOffset + maxScan) - readPos); + if (toRead < EvbMagic.Length) + { + break; + } + + fs.Seek(readPos, SeekOrigin.Begin); + int read = fs.Read(buffer, 0, toRead); + if (read < EvbMagic.Length) + { + break; + } + + if (buffer.AsSpan(0, read).IndexOf(EvbMagic) >= 0) + { + return true; + } + + scanned += chunkSize; } return false; diff --git a/Engines/Evb/EvbDetector.cs b/Engines/Evb/EvbDetector.cs index e55d195..5406826 100644 --- a/Engines/Evb/EvbDetector.cs +++ b/Engines/Evb/EvbDetector.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using GameLauncher.Engines.Common; @@ -19,12 +19,12 @@ namespace GameLauncher.Engines.Evb { /// /// Returns true when the game directory holds an EVB packed executable - /// (or a completed extraction of one). + /// that can actually be unpacked (or a completed extraction of one). /// - /// Accepts any of the following decisive signals: - /// 1. A packed project file (*.evb) in the folder. - /// 2. A top-level executable carrying a decisive EVB PE signature. - /// 3. An already-unpacked game (game-local "_evb_extracted" with a completion + /// Accepts only the following decisive signals: + /// 1. A top-level executable carrying both a decisive EVB PE section (.enigma1) + /// and the EVB virtual filesystem signature ("EVB\0"), so it is unpackable. + /// 2. An already-unpacked game (game-local "_evb_extracted" with a completion /// marker). This is required because unpacking renames the original packed exe /// to "*.glbak", after which the signature check alone would no longer detect /// the game and its launch / icon resolution would break. @@ -36,19 +36,6 @@ namespace GameLauncher.Engines.Evb return false; } - try - { - // A packed project file in the folder is the strongest single signal. - if (Directory.GetFiles(gameDirectory, "*.evb", SearchOption.TopDirectoryOnly).Length > 0) - { - return true; - } - } - catch - { - // Fall through to the remaining checks. - } - // A completed extraction keeps the game recognized even without the packed exe. if (EvbDetectionHelper.IsExtracted(gameDirectory)) { diff --git a/Services/GameScannerService.cs b/Services/GameScannerService.cs index ce24c70..3d999c1 100644 --- a/Services/GameScannerService.cs +++ b/Services/GameScannerService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; @@ -270,6 +270,26 @@ namespace GameLauncher.Services } } + // 既存キャッシュの自動修復: 実際にEVBで圧縮され解凍可能なもののみ IsEvbPacked を維持 + if (Directory.Exists(item.RootDirectory)) + { + string? actualEvbOutDir = null; + bool actualEvb = EvbDetector.IsEvbGame(item.RootDirectory); + bool actualEvbExtracted = actualEvb && EvbUnpackService.IsExtractionComplete(item.RootDirectory, out actualEvbOutDir); + item.IsEvbPacked = actualEvb; + item.IsEvbExtracted = actualEvbExtracted; + if (!actualEvb) + { + item.EvbExtractedDirPath = null; + item.EvbBackupPath = null; + item.EvbUnderlyingEngine = string.Empty; + } + else if (actualEvbExtracted && !string.IsNullOrEmpty(actualEvbOutDir)) + { + item.EvbExtractedDirPath = actualEvbOutDir; + } + } + list.Add(item); } } @@ -739,6 +759,28 @@ namespace GameLauncher.Services } } + // EVB 梱包・解凍状態の最新同期(実際にEVB圧縮・解凍可能なもののみバッジ表示) + string? currentEvbOutDir = null; + bool currentIsEvb = EvbDetector.IsEvbGame(tg.RootDirectory); + bool currentIsEvbExtracted = currentIsEvb && EvbUnpackService.IsExtractionComplete(tg.RootDirectory, out currentEvbOutDir); + if (tg.IsEvbPacked != currentIsEvb || tg.IsEvbExtracted != currentIsEvbExtracted) + { + tg.IsEvbPacked = currentIsEvb; + tg.IsEvbExtracted = currentIsEvbExtracted; + if (!currentIsEvb) + { + tg.EvbExtractedDirPath = null; + tg.EvbBackupPath = null; + tg.EvbUnderlyingEngine = string.Empty; + } + else if (currentIsEvbExtracted && !string.IsNullOrEmpty(currentEvbOutDir)) + { + tg.EvbExtractedDirPath = currentEvbOutDir; + } + cacheNeedsSave = true; + onGameUpdated(tg); + } + // 実在検証 if (tg.IsWolf) { @@ -1162,6 +1204,10 @@ namespace GameLauncher.Services // 既に解凍済みなら出力フォルダから本来エンジンを再判定する。 var underlying = EngineDetectionHelper.EngineUnknown; var isExtracted = EvbUnpackService.IsExtractionComplete(dirPath, out var evbOutDir); + if (packedExe == null && !isExtracted) + { + return null; + } if (isExtracted && evbOutDir != null) { underlying = EngineDetectionHelper.RepairMisdetection( @@ -1370,7 +1416,7 @@ namespace GameLauncher.Services bool isModded = false; if (isExtracted && File.Exists(plannedJsPath)) { - isModded = inspect.IsTyranoGame + isModded = inspect.IsTyranoGame ? TyranoModService.CheckIsModded(plannedJsPath) : TkoolModService.CheckIsModded(plannedJsPath); } @@ -2118,7 +2164,7 @@ namespace GameLauncher.Services if (!Directory.Exists(dir)) return false; // 1. data.dts または runtime.rts または environment.evs の存在 - if (File.Exists(Path.Combine(dir, "data.dts")) || + if (File.Exists(Path.Combine(dir, "data.dts")) || File.Exists(Path.Combine(dir, "runtime.rts")) || File.Exists(Path.Combine(dir, "environment.evs"))) { @@ -2126,7 +2172,7 @@ namespace GameLauncher.Services } // 2. 解凍済みフォルダ (project.srpgs または project.dat) の存在 - if (File.Exists(Path.Combine(dir, "project.srpgs")) || + if (File.Exists(Path.Combine(dir, "project.srpgs")) || File.Exists(Path.Combine(dir, "project.dat")) || File.Exists(Path.Combine(dir, "data_extracted", "project.srpgs"))) {