using System;
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.
///
/// Detection strategy:
/// 1. Parse the PE header and inspect the section table for the packer's sections
/// (".enigma1" / ".enigma2"). A present section is a decisive match.
/// 2. When sections are inconclusive, scan bounded windows of the file for the
/// "Enigma Virtual Box" marker string embedded by the packer.
///
/// This class is engine-local and has no side effects.
///
public static class EvbDetectionHelper
{
/// Marker string embedded by the Enigma Virtual Box packer.
private const string EnigmaMarker = "Enigma Virtual Box";
/// Section names produced by the packer.
private static readonly string[] EnigmaSections = { ".enigma1", ".enigma2" };
/// Additional loader identifiers checked during the content scan.
private static readonly string[] EvbContentMarkers =
{
EnigmaMarker,
"evb.dll",
"EnigmaVB",
};
/// Returns true when the given executable is packed with EVB.
///
/// Step 1 reads the PE section table for the packer's section names.
/// Step 2 falls back to a bounded content scan for the packer marker.
/// Any IO/format error yields false (treated as "not confidently EVB").
///
public static bool IsEvbPacked(string exePath)
{
if (string.IsNullOrWhiteSpace(exePath) || !File.Exists(exePath))
{
return false;
}
try
{
// Step 1: decisive PE section check.
if (HasEnigmaSection(exePath))
{
return true;
}
}
catch
{
// Fall through to the content scan on any parse failure.
}
try
{
// Step 2: content marker scan over bounded windows.
return ContainsEvbContentMarker(exePath);
}
catch
{
return false;
}
}
///
/// Scans a game directory for an EVB packed executable.
/// Returns the first decisive match, or null when none is found.
///
public static string? FindEvbPackedExecutable(string gameDirectory)
{
if (string.IsNullOrWhiteSpace(gameDirectory) || !Directory.Exists(gameDirectory))
{
return null;
}
try
{
return Directory.GetFiles(gameDirectory, "*.exe", SearchOption.TopDirectoryOnly)
.FirstOrDefault(IsEvbPacked);
}
catch
{
return null;
}
}
///
/// Parses the PE section table and checks for the EVB packer's section names.
///
private static bool HasEnigmaSection(string exePath)
{
using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var reader = new BinaryReader(fs);
if (fs.Length < 0x40)
{
return false;
}
// DOS header: check the "MZ" signature and locate the PE header offset.
if (reader.ReadUInt16() != 0x5A4D)
{
return false;
}
fs.Seek(0x3C, SeekOrigin.Begin);
int peOffset = reader.ReadInt32();
if (peOffset <= 0 || peOffset + 24 > fs.Length)
{
return false;
}
fs.Seek(peOffset, SeekOrigin.Begin);
if (reader.ReadUInt32() != 0x00004550) // "PE\0\0"
{
return false;
}
// COFF header: skip machine + number of sections is at offset 2 from here.
fs.Seek(peOffset + 4, SeekOrigin.Begin);
ushort sectionCount = reader.ReadUInt16();
// Optional header size (end of the optional header) 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.
for (int i = 0; i < sectionCount; i++)
{
long offset = sectionTable + (long)i * 40;
if (offset + 8 > fs.Length)
{
break;
}
fs.Seek(offset, SeekOrigin.Begin);
var nameBytes = reader.ReadBytes(8);
var name = System.Text.Encoding.ASCII.GetString(nameBytes).TrimEnd('\0').Trim();
foreach (var section in EnigmaSections)
{
if (string.Equals(name, section, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
}
return false;
}
///
/// Scans bounded windows of the executable for EVB loader markers.
/// EVB metadata typically sits near the end of the PE (overlay).
///
private static bool ContainsEvbContentMarker(string exePath)
{
const int windowSize = 2 * 1024 * 1024;
using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
long size = fs.Length;
if (size < 1024)
{
return false;
}
double[] fractions = { 0.5, 0.8, 0.9, 0.97 };
foreach (var frac in fractions)
{
long start = (long)(size * frac);
int readLen = (int)Math.Min(windowSize, size - start);
if (readLen <= 0)
{
continue;
}
var buf = new byte[readLen];
fs.Seek(start, SeekOrigin.Begin);
int read = fs.Read(buf, 0, buf.Length);
var text = System.Text.Encoding.ASCII.GetString(buf, 0, read);
foreach (var marker in EvbContentMarkers)
{
if (text.IndexOf(marker, StringComparison.OrdinalIgnoreCase) >= 0)
{
return true;
}
}
}
return false;
}
}
}