chore: bundle evbunpack tool and add EVB control/launch fixes

- Add Enigma Virtual Box (EVB) engine support: detection, badge, unpack/restore UI
- Bundle evbunpack.exe under Engines/Evb/Tools/evbunpack (Apache-2.0, with LICENSE/README)
- Copy Engines\\**\\Tools\\** to build output via csproj (publish already covered by publish.ps1)
- Throttle evbunpack progress reporting and shorten timeout to stop UI freeze
- Rename original packed exe to .glbak and write a completion marker; make Restore reverse it
- Launch the unpacked exe from _evb_extracted so script mods apply
- Replace EVB MessageBox dialogs with readable log summaries
- Remove obsolete boxed/7zip extraction code (NwjsPackageUnpacker, TkoolPackagedExtractionService)
This commit is contained in:
armonica committed 2026-10-07 09:30:09 +09:00
1 parent 8cea2a147d
commit 05e7bdb3c0
23 files changed
+1542 -1288

No files matched your search

+204
View File
@@ -0,0 +1,204 @@
using System;
using System.IO;
using System.Linq;
namespace GameLauncher.Engines.Evb
{
/// <summary>
/// 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.
/// </summary>
public static class EvbDetectionHelper
{
/// <summary>Marker string embedded by the Enigma Virtual Box packer.</summary>
private const string EnigmaMarker = "Enigma Virtual Box";
/// <summary>Section names produced by the packer.</summary>
private static readonly string[] EnigmaSections = { ".enigma1", ".enigma2" };
/// <summary>Additional loader identifiers checked during the content scan.</summary>
private static readonly string[] EvbContentMarkers =
{
EnigmaMarker,
"evb.dll",
"EnigmaVB",
};
/// <summary>Returns true when the given executable is packed with EVB.</summary>
/// <remarks>
/// 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").
/// </remarks>
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;
}
}
/// <summary>
/// Scans a game directory for an EVB packed executable.
/// Returns the first decisive match, or null when none is found.
/// </summary>
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;
}
}
/// <summary>
/// Parses the PE section table and checks for the EVB packer's section names.
/// </summary>
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;
}
/// <summary>
/// Scans bounded windows of the executable for EVB loader markers.
/// EVB metadata typically sits near the end of the PE (overlay).
/// </summary>
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;
}
}
}
+62
View File
@@ -0,0 +1,62 @@
using System;
using System.IO;
using GameLauncher.Engines.Common;
namespace GameLauncher.Engines.Evb
{
/// <summary>
/// Backwards-compatible facade over <see cref="EvbDetectionHelper"/>.
///
/// The plan names the detection primitive <see cref="EvbDetectionHelper"/>, but
/// several callers (the engine module, the unpack service and the game scanner)
/// were written against the shorter <c>EvbDetector</c> API. This facade keeps those
/// call sites stable while the authoritative PE-signature logic lives in
/// <see cref="EvbDetectionHelper"/>.
///
/// This class is engine-local and has no side effects.
/// </summary>
public static class EvbDetector
{
/// <summary>
/// Returns true when the game directory holds an EVB packed executable.
/// A packed project file (<c>*.evb</c>) in the folder is also accepted as a
/// decisive signal, in addition to the PE-signature check.
/// </summary>
public static bool IsEvbGame(string gameDirectory)
{
if (string.IsNullOrWhiteSpace(gameDirectory) || !Directory.Exists(gameDirectory))
{
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 executable signature check.
}
return EvbDetectionHelper.FindEvbPackedExecutable(gameDirectory) != null;
}
/// <summary>
/// Resolves the executable that should be passed to the unpacker: the first
/// <c>.exe</c> in the folder that carries a decisive EVB signature, or null.
/// </summary>
public static string? FindPackedExecutable(string gameDirectory)
=> EvbDetectionHelper.FindEvbPackedExecutable(gameDirectory);
/// <summary>Returns true when the given executable is packed with EVB.</summary>
public static bool ContainsEvbSignature(string exePath)
=> EvbDetectionHelper.IsEvbPacked(exePath);
/// <summary>Re-exposes the engine name constant for callers that only reference this helper.</summary>
public static string EngineName => EngineDetectionHelper.EngineEvb;
}
}
+51
View File
@@ -0,0 +1,51 @@
using System;
using GameLauncher.Engines.Common;
using GameLauncher.Models;
namespace GameLauncher.Engines.Evb
{
/// <summary>
/// Engine module for Enigma Virtual Box (EVB) packed applications.
///
/// EVB is a generic packer: it can wrap a game built on any engine (RGSS, NW.js,
/// Wolf, Unity, ...). This module therefore acts as a *pre-stage* — it detects an
/// EVB-packed executable, unpacks it via the bundled evbunpack tool, and then lets
/// the caller re-detect the underlying engine from the unpacked content.
///
/// Per-game hacks never live here; they belong under
/// `Engines/Evb/Games/&lt;GameName&gt;/` and must not affect other games.
/// </summary>
public sealed class EvbEngineModule : IEngineModule
{
/// <inheritdoc />
public string EngineName => EngineDetectionHelper.EngineEvb;
/// <inheritdoc />
public bool Detect(string gameDirectory) => EvbDetector.IsEvbGame(gameDirectory);
/// <summary>
/// EVB is a packaging layer, not a game engine, so it has no script mod of its own.
/// Mods are applied by the underlying engine after unpacking.
/// </summary>
public bool ApplyMod(string gameDirectory, ModPluginDefinition plugin) => false;
/// <summary>EVB has no standalone mod state; nothing is ever "applied".</summary>
public bool IsModApplied(string gameDirectory) => false;
/// <inheritdoc />
public string ResolveToolPath(string toolFileName)
=> AppPathHelperBridge.Resolve(EngineName, toolFileName);
}
/// <summary>
/// Thin indirection so that <see cref="EvbEngineModule"/> can resolve engine tools
/// without taking a hard dependency on the concrete helper type in this file.
/// </summary>
internal static class AppPathHelperBridge
{
public static string Resolve(string engineName, string toolFileName)
=> Helpers.AppPathHelper.ResolveEngineTool(engineName, toolFileName)
?? throw new InvalidOperationException(
$"External tool '{toolFileName}' for engine '{engineName}' was not found.");
}
}
+438
View File
@@ -0,0 +1,438 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using GameLauncher.Engines.Common;
namespace GameLauncher.Engines.Evb
{
/// <summary>
/// Orchestrates detection and unpacking of Enigma Virtual Box (EVB) packed games,
/// then re-detects the real engine from the unpacked content.
///
/// Design (per AGENTS.md):
/// - Everything engine-local lives under `Engines/Evb/`.
/// - The original packed exe is backed up (`.glbak`) before being replaced, so the
/// operation can always be restored (Enigma recovery / manual restore).
/// - Unpacked output is written into a game-local `_evb_extracted` folder, so no
/// other game is ever affected.
/// - The bundled evbunpack tool (see <see cref="EvbUnpackerToolProvider"/>) does the work;
/// if it is missing the operation degrades gracefully (returns a failed result).
/// </summary>
public sealed class EvbUnpackService
{
/// <summary>Game-local folder that receives the unpacked files.</summary>
public const string ExtractedDirName = "_evb_extracted";
/// <summary>Marker file written last when an extraction finished successfully.</summary>
public const string CompleteMarkerName = ".evb_complete";
/// <summary>Backup suffix applied to the original packed executable.</summary>
public const string ExeBackupSuffix = ".glbak";
/// <summary>Result of an unpack attempt.</summary>
public sealed class UnpackResult
{
/// <summary>True when unpacking produced usable output.</summary>
public bool Success { get; init; }
/// <summary>Folder that contains the unpacked files (null on failure).</summary>
public string? OutputDirectory { get; init; }
/// <summary>Absolute path of the original packed executable (null when not found).</summary>
public string? SourceExePath { get; init; }
/// <summary>Absolute path of the backed-up original executable (null when no backup was made).</summary>
public string? BackupExePath { get; init; }
/// <summary>Engine name re-detected from the unpacked content (canonical name).</summary>
public string UnderlyingEngine { get; init; } = EngineDetectionHelper.EngineUnknown;
/// <summary>Human-readable message describing the outcome.</summary>
public string Message { get; init; } = string.Empty;
/// <summary>True when output was already present and re-used (idempotent skip).</summary>
public bool ReusedExisting { get; init; }
}
/// <summary>Game-local extraction folder for the given game root.</summary>
public static string GetExtractedDir(string gameRootDir)
=> Path.Combine(gameRootDir, ExtractedDirName);
/// <summary>Marker file path inside the extraction folder.</summary>
public static string GetCompleteMarkerPath(string outputDirectory)
=> Path.Combine(outputDirectory, CompleteMarkerName);
/// <summary>
/// Resolves the executable to launch from an unpacked output folder.
/// Prefers a well-known game exe name, then the first `.exe` found (top level first,
/// then one level deep). Returns null when nothing usable is found.
/// </summary>
public static string? FindLaunchExecutable(string? outputDirectory)
{
if (string.IsNullOrWhiteSpace(outputDirectory) || !Directory.Exists(outputDirectory))
{
return null;
}
try
{
// Preferred names commonly used by NW.js / RPG Maker / Tyrano bundles.
string[] preferred = { "Game.exe", "game.exe", "nw.exe", "Game_boxed.exe" };
foreach (var name in preferred)
{
var direct = Path.Combine(outputDirectory, name);
if (File.Exists(direct))
{
return direct;
}
}
// First exe at the top level, then one level deeper.
var top = Directory.GetFiles(outputDirectory, "*.exe", SearchOption.TopDirectoryOnly);
if (top.Length > 0)
{
return top[0];
}
foreach (var sub in Directory.GetDirectories(outputDirectory))
{
var nested = Directory.GetFiles(sub, "*.exe", SearchOption.TopDirectoryOnly);
if (nested.Length > 0)
{
return nested[0];
}
}
}
catch
{
// Ignore IO errors and fall back to no result.
}
return null;
}
/// <summary>
/// True when the game folder already holds a completed EVB extraction.
/// A non-empty output folder is NOT enough: the run may have been interrupted,
/// so the presence of the completion marker is required.
/// </summary>
public static bool IsExtractionComplete(string gameRootDir, out string? outputDirectory)
{
outputDirectory = GetExtractedDir(gameRootDir);
try
{
return Directory.Exists(outputDirectory) &&
File.Exists(GetCompleteMarkerPath(outputDirectory));
}
catch
{
return false;
}
}
/// <summary>
/// Unpacks the EVB-packed executable in the game folder and re-detects the
/// underlying engine. Idempotent: a completed prior extraction is re-used.
/// </summary>
/// <param name="gameRootDir">Game root folder containing the packed exe.</param>
/// <param name="progress">Optional progress sink.</param>
public UnpackResult Unpack(
string gameRootDir,
IProgress<string>? progress = null,
bool legacyFileSystem = false,
string? peVariant = null)
{
if (string.IsNullOrWhiteSpace(gameRootDir) || !Directory.Exists(gameRootDir))
{
return new UnpackResult { Success = false, Message = "ゲームフォルダが見つかりません。" };
}
// Idempotent: reuse a previous successful extraction.
if (IsExtractionComplete(gameRootDir, out var existingDir) && existingDir != null)
{
var reusedEngine = EngineDetectionHelper.RepairMisdetection(
existingDir, EngineDetectionHelper.EngineUnknown);
return new UnpackResult
{
Success = true,
OutputDirectory = existingDir,
UnderlyingEngine = reusedEngine,
ReusedExisting = true,
Message = $"既に解凍済みです({ExtractedDirName} を再利用)。",
};
}
var sourceExe = EvbDetectionHelper.FindEvbPackedExecutable(gameRootDir);
if (sourceExe == null)
{
return new UnpackResult
{
Success = false,
Message = "EVB パック済みの実行ファイルが見つかりませんでした。",
};
}
var toolPath = EvbUnpackerToolProvider.GetToolPath();
if (toolPath == null)
{
return new UnpackResult
{
Success = false,
SourceExePath = sourceExe,
Message = "解凍ツール (evbunpack) が見つかりません。Engines\\Evb\\Tools\\evbunpack\\ に配置してください。",
};
}
var outputDir = GetExtractedDir(gameRootDir);
try
{
// Start clean so partial output never mixes with a fresh run.
if (Directory.Exists(outputDir))
{
Directory.Delete(outputDir, recursive: true);
}
Directory.CreateDirectory(outputDir);
progress?.Report($"EVB 解凍を開始します: {Path.GetFileName(sourceExe)}");
var args = EvbUnpackerToolProvider.BuildArguments(sourceExe, outputDir, legacyFileSystem, peVariant);
if (!RunTool(toolPath, args, gameRootDir, progress, out var exitCode))
{
return new UnpackResult
{
Success = false,
SourceExePath = sourceExe,
OutputDirectory = outputDir,
Message = $"evbunpack の実行に失敗しました (exit code={exitCode})。",
};
}
if (!Directory.EnumerateFileSystemEntries(outputDir).Any())
{
return new UnpackResult
{
Success = false,
SourceExePath = sourceExe,
OutputDirectory = outputDir,
Message = "解凍は実行されましたが出力が空でした。PE バリアント (-pe 10_70 / 7_80) を変えて再試行してください。",
};
}
// Move the original packed exe out of the way so it is no longer recognized
// as an executable by the scanner (`.glbak` is not scanned as `*.exe`).
string? backupPath = null;
try
{
backupPath = sourceExe + ExeBackupSuffix;
if (File.Exists(backupPath))
{
// A previous backup exists; remove it so the move can succeed.
File.Delete(backupPath);
}
File.Move(sourceExe, backupPath);
progress?.Report($"元の実行ファイルを退避しました: {Path.GetFileName(backupPath)}");
}
catch (Exception ex)
{
progress?.Report($"バックアップに失敗しました(解凍自体は成功): {ex.Message}");
}
// Completion marker is written last, so an interrupted run is detectable.
File.WriteAllText(GetCompleteMarkerPath(outputDir), DateTime.UtcNow.ToString("o"));
// Re-detect the real engine from the unpacked content.
var underlying = ReDetectUnderlyingEngine(outputDir);
progress?.Report($"解凍後のエンジン再判定: {underlying}");
return new UnpackResult
{
Success = true,
OutputDirectory = outputDir,
SourceExePath = sourceExe,
BackupExePath = backupPath,
UnderlyingEngine = underlying,
Message = $"EVB 解凍が完了しました(再判定エンジン: {underlying})。",
};
}
catch (Exception ex)
{
return new UnpackResult
{
Success = false,
SourceExePath = sourceExe,
OutputDirectory = outputDir,
Message = $"EVB 解凍中にエラーが発生しました: {ex.Message}",
};
}
}
/// <summary>
/// Restores a previously unpacked game by removing the extraction output and
/// the backup copy is kept intact for the user. Returns true when something
/// was restored.
/// </summary>
public static bool Restore(string gameRootDir, IProgress<string>? progress = null)
{
if (string.IsNullOrWhiteSpace(gameRootDir) || !Directory.Exists(gameRootDir))
{
return false;
}
var restored = false;
var outputDir = GetExtractedDir(gameRootDir);
try
{
if (Directory.Exists(outputDir))
{
Directory.Delete(outputDir, recursive: true);
progress?.Report($"解凍フォルダを削除しました: {ExtractedDirName}");
restored = true;
}
}
catch (Exception ex)
{
progress?.Report($"解凍フォルダの削除に失敗しました: {ex.Message}");
}
// Restore the renamed backup back to its original `.exe` name.
try
{
foreach (var backup in Directory.GetFiles(gameRootDir, "*" + ExeBackupSuffix))
{
var original = backup.Substring(0, backup.Length - ExeBackupSuffix.Length);
if (!File.Exists(original))
{
File.Move(backup, original);
progress?.Report($"元の実行ファイルを復元しました: {Path.GetFileName(original)}");
restored = true;
}
}
}
catch (Exception ex)
{
progress?.Report($"元の実行ファイルの復元に失敗しました: {ex.Message}");
}
return restored;
}
/// <summary>
/// Runs the detection helper against the unpacked folder to determine the real engine.
/// </summary>
private static string ReDetectUnderlyingEngine(string outputDir)
{
var engine = EngineDetectionHelper.RepairMisdetection(
outputDir, EngineDetectionHelper.EngineUnknown);
// If the flat output still hides the engine, probe its immediate subfolders
// (evbunpack may keep the original layout one level down).
if (engine == EngineDetectionHelper.EngineUnknown)
{
try
{
foreach (var sub in Directory.GetDirectories(outputDir))
{
var candidate = EngineDetectionHelper.RepairMisdetection(
sub, EngineDetectionHelper.EngineUnknown);
if (candidate != EngineDetectionHelper.EngineUnknown)
{
return candidate;
}
}
}
catch { }
}
return engine;
}
/// <summary>Runs evbunpack with ArgumentList (no manual quoting) and waits for exit.</summary>
private static bool RunTool(
string toolPath,
System.Collections.Generic.IReadOnlyList<string> args,
string workingDir,
IProgress<string>? progress,
out int exitCode)
{
exitCode = -1;
try
{
var psi = new ProcessStartInfo
{
FileName = toolPath,
WorkingDirectory = workingDir,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
foreach (var arg in args)
{
psi.ArgumentList.Add(arg);
}
// Throttle progress reporting: evbunpack emits thousands of lines on large
// bundles, and every Report() is marshalled onto the UI thread. Reporting
// each line saturates the UI and makes the window appear frozen, so only the
// latest line is reported at most a few times per second.
var throttle = Stopwatch.StartNew();
var lastReportUtc = DateTime.MinValue;
var lastLine = string.Empty;
void ReportThrottled(string? data)
{
if (string.IsNullOrWhiteSpace(data))
{
return;
}
lastLine = data!;
var now = DateTime.UtcNow;
if (now - lastReportUtc >= TimeSpan.FromMilliseconds(400))
{
lastReportUtc = now;
progress?.Report(data!);
}
}
using var proc = Process.Start(psi);
if (proc == null)
{
return false;
}
proc.OutputDataReceived += (_, e) => ReportThrottled(e.Data);
proc.ErrorDataReceived += (_, e) => ReportThrottled(e.Data);
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
// evbunpack can take a while on large bundles, but a shorter bound keeps the
// operation from looking hung if the tool never terminates.
if (!proc.WaitForExit(10 * 60 * 1000))
{
try { proc.Kill(entireProcessTree: true); } catch { }
progress?.Report("evbunpack がタイムアウトしました(10分)。処理を中断しました。");
exitCode = -1;
return false;
}
// Flush the final line that throttling may have skipped.
if (!string.IsNullOrWhiteSpace(lastLine))
{
progress?.Report(lastLine);
}
exitCode = proc.ExitCode;
return exitCode == 0;
}
catch (Exception ex)
{
progress?.Report($"evbunpack の起動に失敗しました: {ex.Message}");
return false;
}
}
}
}
+122
View File
@@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GameLauncher.Helpers;
namespace GameLauncher.Engines.Evb
{
/// <summary>
/// Resolves the bundled evbunpack executable used to unpack Enigma Virtual Box (EVB)
/// packed applications.
///
/// Design notes (durable / reusable):
/// - The tool is bundled under `Engines\Evb\Tools\evbunpack\` (per-engine tools folder).
/// - Path resolution goes through <see cref="AppPathHelper"/> so that deployed, production
/// and source-tree layouts are all supported without hard-coding this machine's paths.
/// - CLI argument construction is kept in one place so callers never duplicate the
/// evbunpack invocation contract.
///
/// The evbunpack CLI contract:
/// evbunpack [-pe {10_70,9_70,7_80}] [--legacy-fs] &lt;input exe&gt; &lt;output folder&gt;
/// It restores both the packed virtual file system and the original PE executable.
/// </summary>
public static class EvbUnpackerToolProvider
{
/// <summary>Engine identifier passed to <see cref="AppPathHelper.GetEngineToolsDirectory"/>.</summary>
public const string EngineName = "Evb";
/// <summary>Bundled unpacker executable name.</summary>
public const string DefaultToolExeName = "evbunpack.exe";
/// <summary>Relative subfolder under Engines/Evb/Tools that holds the tool.</summary>
public const string ToolSubDirectory = "evbunpack";
/// <summary>
/// Default PE rebuild variant used when the caller does not specify one.
/// 9_70 works for Enigma Virtual Box 9.70 and 10.70/11.00 in most cases;
/// callers may override via <see cref="BuildArguments"/>.
/// </summary>
public const string DefaultPeVariant = "9_70";
/// <summary>Gets the engine tools directory (Engines/Evb/Tools).</summary>
public static string GetToolsDirectory()
{
return AppPathHelper.GetEngineToolsDirectory(EngineName);
}
/// <summary>Gets the bundled tool subfolder (Engines/Evb/Tools/evbunpack).</summary>
public static string GetToolDirectory()
{
return Path.Combine(GetToolsDirectory(), ToolSubDirectory);
}
/// <summary>
/// Resolves the evbunpack.exe path, or null when the tool is missing.
/// Prefers the bundled subfolder, then falls back to a flat layout inside the
/// engine tools folder (and the shared <see cref="AppPathHelper.ResolveEngineTool"/> probe).
/// </summary>
public static string? GetToolPath()
{
try
{
var candidates = new[]
{
Path.Combine(GetToolDirectory(), DefaultToolExeName),
Path.Combine(GetToolsDirectory(), DefaultToolExeName),
};
var found = candidates.FirstOrDefault(File.Exists);
if (found != null)
{
return found;
}
// Fall back to the shared per-engine resolver (checks deployed + dev layouts).
return AppPathHelper.ResolveEngineTool(
EngineName,
Path.Combine(ToolSubDirectory, DefaultToolExeName));
}
catch
{
return null;
}
}
/// <summary>True when the unpacker executable exists and is usable.</summary>
public static bool IsAvailable() => GetToolPath() != null;
/// <summary>
/// Builds the argument list for the unpacker CLI.
/// Emits the PE variant first, then the optional legacy switch, then the
/// input executable and the output folder. Values are raw (no quoting); callers
/// pass them through <c>ProcessStartInfo.ArgumentList</c> which handles escaping.
/// </summary>
/// <param name="inputExePath">Path to the EVB-packed executable.</param>
/// <param name="outputDirectory">Folder that receives the unpacked files.</param>
/// <param name="legacyFileSystem">When true, adds <c>--legacy-fs</c> for packer version 7.80.</param>
/// <param name="peVariant">PE rebuild variant (10_70/9_70/7_80); defaults to <see cref="DefaultPeVariant"/>.</param>
public static IReadOnlyList<string> BuildArguments(
string inputExePath,
string outputDirectory,
bool legacyFileSystem = false,
string? peVariant = null)
{
var args = new List<string>();
if (legacyFileSystem)
{
args.Add("--legacy-fs");
}
var variant = string.IsNullOrWhiteSpace(peVariant) ? DefaultPeVariant : peVariant.Trim();
args.Add("-pe");
args.Add(variant);
args.Add(inputExePath);
args.Add(outputDirectory);
return args;
}
}
}
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+62
View File
@@ -0,0 +1,62 @@
# evbunpack (bundled tool)
`evbunpack.exe` is a bundled, third-party unpacker used by the **Evb** engine module to
unpack applications protected with **Enigma Virtual Box**.
## Provenance
- Upstream project: https://github.com/mos9527/evbunpack
- Description: Enigma Virtual Box Unpacker / 解包・脱壳工具
- License: Apache-2.0 (see `LICENSE` in this folder for the full text)
- Repository status: **archived (read-only) by the owner on 2026-02-06**
- Version / release: bundled from the upstream Windows builds
(see the "For Windows Users: Builds are available here" link in the upstream README,
which points to the project's GitHub Releases page).
> **NOTE**: The binary in this folder is not committed as part of the normal source
> tree review flow. Place the upstream-release `evbunpack.exe` here before publishing.
> If the file is absent, the `Evb` engine module reports the tool as unavailable and
> skips unpacking instead of throwing (callers degrade gracefully).
## CLI usage
```
evbunpack [-h] [--log-level {DEBUG,INFO,WARNING,ERROR,CRITICAL}] [-l]
[--ignore-fs] [--ignore-pe] [--legacy-fs]
[-pe {10_70,9_70,7_80}] [--out-pe OUT_PE]
file output
```
- `file` : the packed `.exe` (input)
- `output` : the folder that receives the unpacked files (created if missing)
The tool restores **both** the virtual file system contents **and** the original PE
executable, in a single invocation.
### PE variant selection
| Packer version | Unpack with flags |
|----------------|------------------------------|
| 11.00 | `-pe 10_70` |
| 10.70 | `-pe 10_70` |
| 9.70 | `-pe 9_70` |
| 7.80 | `-pe 7_80 --legacy-fs` |
`EvbUnpackerToolProvider.BuildArguments` defaults to `-pe 9_70` and can be overridden
per call.
## Alternatives (when re-bundling is not possible)
- Install via PyPI: `pip install evbunpack` and run `python -m evbunpack ...`
(requires a Python runtime on the target machine).
- Build from source with `setup.py` / `pyinstaller` following the upstream README.
## Where it is used
- `Engines/Evb/EvbUnpackerToolProvider.cs` — resolves the executable and builds CLI arguments.
- `Engines/Evb/EvbUnpackService.cs` — orchestrates detection, unpacking and re-detection.
Resolution order (see `EvbUnpackerToolProvider.GetToolPath`):
1. `Engines/Evb/Tools/evbunpack/evbunpack.exe` (bundled layout, this folder)
2. `Engines/Evb/Tools/evbunpack.exe` (flat layout)
3. `AppPathHelper.ResolveEngineTool("Evb", "evbunpack/evbunpack.exe")` fallback probe.
Binary file not shown.