Add guarded UPX exe packing flow

This commit is contained in:
Your Name committed 2026-06-18 00:25:21 +08:00
1 parent 11de0f75c7
commit abcee63776
4 files changed
+251 -1

No files matched your search

+8
View File
@@ -29,6 +29,14 @@ powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_
注意:PyArmor 试用版会在混淆文件头部留下 trial 标记,正式分发前建议购买/配置正式授权后重新打包。
如果要尝试对根目录 exe 做 UPX 加壳/压缩,可额外加 `-PackExe -UpxDir <UPX目录>`:
```powershell
powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall -Obfuscate -PackExe -UpxDir C:\path\to\upx
```
当前 PyInstaller 生成的 exe 带 `GUARD_CF`,UPX 默认会拒绝压缩。脚本提供 `-PackExeForce` 仅用于实验;验证中它会导致 exe 启动失败并报 `Failed to load Python DLL`,脚本已加入加壳后 smoke 检查,失败会中止打包。正式分发目前建议使用 `-Obfuscate`,不要启用 `-PackExeForce`。
如果要生成带本地授权的测试包,先生成当前机器的 `license.dat`:
```powershell
+18 -1
View File
@@ -1,7 +1,10 @@
param(
[string]$Version = "",
[switch]$SkipInstall,
[switch]$Obfuscate
[switch]$Obfuscate,
[switch]$PackExe,
[switch]$PackExeForce,
[string]$UpxDir = ""
)
$ErrorActionPreference = "Stop"
@@ -85,6 +88,20 @@ if (Test-Path $licensePath) {
Copy-Item -LiteralPath (Join-Path $Root "README.md") -Destination (Join-Path $DistRoot "README.md") -Force
if ($PackExe) {
$PackArgs = @($DistRoot)
if ($UpxDir) {
$PackArgs += @("--upx-dir", $UpxDir)
}
if ($PackExeForce) {
$PackArgs += "--force"
}
python -m tools.exe_packing @PackArgs
if ($LASTEXITCODE -ne 0) {
throw "UPX packing failed with exit code $LASTEXITCODE"
}
}
python -m tools.distribution_manifest $DistRoot
Write-Host "[OK] Portable package: $DistRoot"
+125
View File
@@ -0,0 +1,125 @@
from __future__ import annotations
import subprocess
from pathlib import Path
import pytest
def _write_exe(path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b"MZfake")
def test_pack_distribution_exes_invokes_upx_for_root_exes_only(tmp_path, monkeypatch):
from tools.exe_packing import pack_distribution_exes
dist = tmp_path / "dist"
for name in ("DouyinGuajiGUI.exe", "web_gui.exe", "run_cli.exe"):
_write_exe(dist / name)
_write_exe(dist / "_internal" / "python312.dll")
_write_exe(dist / "_internal" / "helper.exe")
calls: list[list[str]] = []
monkeypatch.setattr("tools.exe_packing.shutil.which", lambda name: "upx.exe")
def fake_runner(cmd, *, check):
calls.append([str(x) for x in cmd])
assert check is True
return subprocess.CompletedProcess(cmd, 0)
packed = pack_distribution_exes(dist, runner=fake_runner)
assert packed == [
dist / "DouyinGuajiGUI.exe",
dist / "web_gui.exe",
dist / "run_cli.exe",
]
assert len(calls) == 3
assert all(call[:3] == ["upx.exe", "--best", "--lzma"] for call in calls)
assert all("_internal" not in " ".join(call) for call in calls)
def test_pack_distribution_exes_can_force_guard_cf_files(tmp_path, monkeypatch):
from tools.exe_packing import pack_distribution_exes
dist = tmp_path / "dist"
for name in ("DouyinGuajiGUI.exe", "web_gui.exe", "run_cli.exe"):
_write_exe(dist / name)
calls: list[list[str]] = []
monkeypatch.setattr("tools.exe_packing.shutil.which", lambda name: "upx.exe")
def fake_runner(cmd, *, check):
calls.append([str(x) for x in cmd])
return subprocess.CompletedProcess(cmd, 0)
pack_distribution_exes(dist, force=True, runner=fake_runner)
assert all("--force" in call for call in calls)
def test_smoke_check_packed_exes_runs_after_packing(tmp_path):
from tools.exe_packing import smoke_check_distribution_exes
dist = tmp_path / "dist"
for name in ("DouyinGuajiGUI.exe", "web_gui.exe", "run_cli.exe"):
_write_exe(dist / name)
calls: list[list[str]] = []
def fake_runner(cmd, *, capture_output, text, timeout):
calls.append([str(x) for x in cmd])
assert capture_output is True
assert text is True
assert timeout == 20
return subprocess.CompletedProcess(cmd, 0, stdout="ok")
smoke_check_distribution_exes(dist, runner=fake_runner)
assert calls == [
[str(dist / "run_cli.exe"), "--help"],
[str(dist / "web_gui.exe"), "--help"],
]
def test_smoke_check_packed_exes_fails_on_broken_exe(tmp_path):
from tools.exe_packing import smoke_check_distribution_exes
dist = tmp_path / "dist"
for name in ("DouyinGuajiGUI.exe", "web_gui.exe", "run_cli.exe"):
_write_exe(dist / name)
def fake_runner(cmd, *, capture_output, text, timeout):
return subprocess.CompletedProcess(cmd, 1, stdout="", stderr="Failed to load Python DLL")
with pytest.raises(RuntimeError, match="smoke check failed"):
smoke_check_distribution_exes(dist, runner=fake_runner)
def test_pack_distribution_exes_requires_upx(tmp_path, monkeypatch):
from tools.exe_packing import pack_distribution_exes
for name in ("DouyinGuajiGUI.exe", "web_gui.exe", "run_cli.exe"):
_write_exe(tmp_path / "dist" / name)
monkeypatch.setattr("tools.exe_packing.shutil.which", lambda name: None)
with pytest.raises(FileNotFoundError, match="upx"):
pack_distribution_exes(tmp_path / "dist")
def test_pack_distribution_exes_requires_expected_exes(tmp_path, monkeypatch):
from tools.exe_packing import pack_distribution_exes
monkeypatch.setattr("tools.exe_packing.shutil.which", lambda name: "upx.exe")
_write_exe(tmp_path / "dist" / "run_cli.exe")
with pytest.raises(RuntimeError, match="DouyinGuajiGUI.exe"):
pack_distribution_exes(tmp_path / "dist")
def test_windows_packaging_script_exposes_pack_exe_switch():
script = Path("packaging/pyinstaller/build_windows.ps1").read_text(encoding="utf-8")
assert "[switch]$PackExe" in script
assert "[switch]$PackExeForce" in script
assert "[string]$UpxDir" in script
assert "tools.exe_packing" in script
assert "if ($LASTEXITCODE -ne 0)" in script
+100
View File
@@ -0,0 +1,100 @@
from __future__ import annotations
import argparse
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Callable, Sequence
ROOT_EXES = ("DouyinGuajiGUI.exe", "web_gui.exe", "run_cli.exe")
SMOKE_COMMANDS = (
("run_cli.exe", "--help"),
("web_gui.exe", "--help"),
)
Runner = Callable[..., subprocess.CompletedProcess]
def resolve_upx(upx_dir: str | None = None) -> str:
if upx_dir:
candidate = Path(upx_dir) / ("upx.exe" if sys.platform.startswith("win") else "upx")
if candidate.exists():
return str(candidate)
raise FileNotFoundError(f"upx executable not found in {upx_dir}")
found = shutil.which("upx")
if not found:
raise FileNotFoundError("upx executable not found")
return found
def pack_distribution_exes(
dist_dir: str | Path,
*,
upx_dir: str | None = None,
force: bool = False,
runner: Runner = subprocess.run,
) -> list[Path]:
root = Path(dist_dir)
missing = [name for name in ROOT_EXES if not (root / name).is_file()]
if missing:
raise RuntimeError(f"missing root exe files: {', '.join(missing)}")
upx = resolve_upx(upx_dir)
packed: list[Path] = []
for name in ROOT_EXES:
exe = root / name
cmd = [upx, "--best", "--lzma"]
if force:
cmd.append("--force")
cmd.append(str(exe))
runner(cmd, check=True)
packed.append(exe)
return packed
def smoke_check_distribution_exes(
dist_dir: str | Path,
*,
runner: Runner = subprocess.run,
timeout: int = 20,
) -> None:
root = Path(dist_dir)
for exe_name, arg in SMOKE_COMMANDS:
exe = root / exe_name
proc = runner([str(exe), arg], capture_output=True, text=True, timeout=timeout)
if proc.returncode != 0:
detail = (proc.stderr or proc.stdout or "").strip().replace("\r", " ").replace("\n", " ")
raise RuntimeError(f"smoke check failed for {exe_name}: exit={proc.returncode} {detail}")
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="使用 UPX 加壳/压缩分发目录根部 exe")
parser.add_argument("dist_dir", help="例如 dist/DouyinGuaji-3.3.3")
parser.add_argument("--upx-dir", default="", help="UPX 所在目录;为空则从 PATH 查找")
parser.add_argument("--force", action="store_true", help="强制加壳 GUARD_CF 等 UPX 默认拒绝的 exe")
parser.add_argument("--no-smoke", action="store_true", help="跳过加壳后的 exe 启动冒烟检查")
args = parser.parse_args(argv)
try:
packed = pack_distribution_exes(args.dist_dir, upx_dir=args.upx_dir or None, force=args.force)
if not args.no_smoke:
smoke_check_distribution_exes(args.dist_dir)
except FileNotFoundError as exc:
print(f"[PACK-EXE] FAIL {exc}. Download UPX and pass -UpxDir <dir>.", file=sys.stderr)
return 2
except subprocess.CalledProcessError as exc:
print(f"[PACK-EXE] FAIL upx exited with code {exc.returncode}", file=sys.stderr)
return exc.returncode or 1
except Exception as exc:
print(f"[PACK-EXE] FAIL {exc}", file=sys.stderr)
return 1
print(f"[PACK-EXE] PASS packed={len(packed)}")
for exe in packed:
print(f" {exe}")
return 0
if __name__ == "__main__":
raise SystemExit(main())