Ship a self-contained Windows GUI with game shortcuts and application icons
This commit is contained in:
1 parent
329a1ad4df
commit
3ea497d38a
16 files changed
+589
-58
No files matched your search
@@ -0,0 +1,53 @@
|
||||
"""Check the packaged Windows executable on the native runner."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import tomllib
|
||||
import zipfile
|
||||
|
||||
import pefile
|
||||
from windows_deps import resolve_dependencies
|
||||
|
||||
|
||||
def check_package(directory):
|
||||
with (Path(__file__).resolve().parents[1] / "Cargo.toml").open("rb") as stream:
|
||||
package = tomllib.load(stream)["package"]
|
||||
name, version = package["name"], package["version"]
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
unpacked = Path(temp) / "portable"
|
||||
with zipfile.ZipFile(directory / f"{name}-{version}-windows-x86_64.zip") as archive:
|
||||
archive.extractall(unpacked)
|
||||
exe = unpacked / f"{name}.exe"
|
||||
# Verify closure using only files that made it into the ZIP. A globally
|
||||
# installed DLL on the build machine could otherwise mask an omission.
|
||||
resolve_dependencies(exe, require_static_crt=True)
|
||||
with pefile.PE(str(exe), fast_load=True) as pe:
|
||||
if pe.OPTIONAL_HEADER.Subsystem != pefile.SUBSYSTEM_TYPE["IMAGE_SUBSYSTEM_WINDOWS_GUI"]:
|
||||
raise ValueError("The packaged executable opens a console window")
|
||||
pe.parse_data_directories([pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_RESOURCE"]])
|
||||
resources = {entry.id for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries}
|
||||
if not {pefile.RESOURCE_TYPE["RT_ICON"], pefile.RESOURCE_TYPE["RT_GROUP_ICON"]} <= resources:
|
||||
raise ValueError("The packaged executable is missing its application icon")
|
||||
|
||||
windows = Path(os.environ["SystemRoot"])
|
||||
env = {**os.environ, "PATH": os.pathsep.join(map(str, (windows / "System32", windows)))}
|
||||
for argument, code, expected in [
|
||||
("--version", 0, f"{name} {version}"),
|
||||
("--help", 0, "poe2"),
|
||||
("invalid-game", 2, "invalid-game"),
|
||||
]:
|
||||
# Exercise both pipes together and each redirected stream independently.
|
||||
result = subprocess.run([exe, argument], cwd=temp, env=env, text=True, timeout=30,
|
||||
stdout=subprocess.PIPE if not code else None,
|
||||
stderr=subprocess.PIPE if argument != "--help" else None)
|
||||
output = result.stderr if code else result.stdout
|
||||
if result.returncode != code or expected not in output:
|
||||
raise ValueError(f"{argument} returned {result.returncode:#x}: {output.strip()}")
|
||||
print(f"Verified the packaged {name} {version}, its GUI subsystem, icon and CLI output.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
check_package(Path(sys.argv[1]))
|
||||
+67
-6
@@ -38,19 +38,70 @@ def check_binary(binary, platform):
|
||||
raise ValueError(f"{binary} is not an x86_64 {platform} executable")
|
||||
|
||||
|
||||
def package_windows(binary, work):
|
||||
def windows_inventory(payload, include):
|
||||
from windows_deps import safe_basename
|
||||
|
||||
paths = sorted(payload.rglob("*"), key=lambda p: p.relative_to(payload).as_posix().lower())
|
||||
files, directories, seen = [], [], set()
|
||||
for path in paths:
|
||||
relative = path.relative_to(payload)
|
||||
for part in relative.parts:
|
||||
safe_basename(part)
|
||||
key = relative.as_posix().lower()
|
||||
if key in seen or key == "uninstall.exe":
|
||||
raise ValueError(f"Conflicting Windows payload filename: {relative}")
|
||||
seen.add(key)
|
||||
if path.is_symlink():
|
||||
raise ValueError(f"Symlink in Windows payload: {relative}")
|
||||
if path.is_dir():
|
||||
directories.append(relative)
|
||||
elif path.is_file():
|
||||
files.append(relative)
|
||||
else:
|
||||
raise ValueError(f"Not a regular payload file: {relative}")
|
||||
install = ["!macro InstallPayload"]
|
||||
previous = None
|
||||
for path in files:
|
||||
parent = "\\".join(path.parts[:-1])
|
||||
destination = "$INSTDIR" + ("\\" + parent if parent else "")
|
||||
if destination != previous:
|
||||
install.append(f' SetOutPath "{destination}"')
|
||||
previous = destination
|
||||
source = "\\".join(path.parts)
|
||||
install.append(f' File "payload\\{source}"')
|
||||
install.extend([' SetOutPath "$INSTDIR"', "!macroend", "", "!macro UninstallPayload"])
|
||||
for path in files:
|
||||
name = "\\".join(path.parts)
|
||||
install.append(f' Delete "$INSTDIR\\{name}"')
|
||||
for path in sorted(directories, key=lambda p: (-len(p.parts), p.as_posix().lower())):
|
||||
name = "\\".join(path.parts)
|
||||
install.append(f' RMDir "$INSTDIR\\{name}"')
|
||||
install.append("!macroend")
|
||||
include.write_text("\n".join(install) + "\n", encoding="utf-8")
|
||||
return files
|
||||
|
||||
|
||||
def package_windows(binary, work, dll_dirs=(), require_static_crt=False):
|
||||
from windows_deps import resolve_dependencies, safe_basename
|
||||
|
||||
safe_basename(NAME)
|
||||
safe_basename(VERSION)
|
||||
dependencies = resolve_dependencies(binary, dll_dirs, require_static_crt)
|
||||
stem = f"{NAME}-{VERSION}-windows-x86_64"
|
||||
payload = work / "payload"
|
||||
(payload / "licenses").mkdir(parents=True)
|
||||
shutil.copyfile(binary, payload / f"{NAME}.exe")
|
||||
for name, source in dependencies.items():
|
||||
shutil.copyfile(source, payload / name)
|
||||
for name, source in NOTICES.items():
|
||||
shutil.copyfile(source, payload / "licenses" / name)
|
||||
|
||||
# Freeze one validated inventory for the archive and both NSIS macros.
|
||||
inventory = windows_inventory(payload, work / "payload-files.nsh")
|
||||
archive = work / f"{stem}.zip"
|
||||
with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as bundle:
|
||||
for path in sorted(payload.rglob("*")):
|
||||
if path.is_file():
|
||||
bundle.write(path, path.relative_to(payload))
|
||||
for relative in inventory:
|
||||
bundle.write(payload / relative, relative.as_posix())
|
||||
|
||||
makensis = shutil.which("makensis")
|
||||
if not makensis and os.name == "nt":
|
||||
@@ -63,6 +114,7 @@ def package_windows(binary, work):
|
||||
if not makensis:
|
||||
raise ValueError("Install NSIS 3 and make makensis available")
|
||||
shutil.copyfile(ROOT / "packaging/windows/installer.nsi", work / "installer.nsi")
|
||||
shutil.copyfile(ROOT / "assets/icon.ico", work / "app.ico")
|
||||
define = "/D" if os.name == "nt" else "-D"
|
||||
installer = work / f"{stem}-setup.exe"
|
||||
subprocess.run(
|
||||
@@ -137,14 +189,23 @@ def main():
|
||||
parser.add_argument("platform", choices=("windows", "linux"))
|
||||
parser.add_argument("binary", type=Path)
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "target/dist")
|
||||
parser.add_argument("--dll-dir", type=Path, action="append", default=[], metavar="DIR",
|
||||
help="Windows DLL source directory (repeatable; no PATH search)")
|
||||
parser.add_argument("--require-static-crt", action="store_true",
|
||||
help="Reject direct/delay CRT imports in the Windows executable")
|
||||
args = parser.parse_args()
|
||||
if args.platform != "windows" and (args.dll_dir or args.require_static_crt):
|
||||
parser.error("--dll-dir and --require-static-crt apply only to Windows")
|
||||
binary = args.binary.resolve()
|
||||
output = args.output.resolve()
|
||||
check_binary(binary, args.platform)
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(dir=output) as temp:
|
||||
package = package_windows if args.platform == "windows" else package_linux
|
||||
for artifact in package(binary, Path(temp)):
|
||||
if args.platform == "windows":
|
||||
artifacts = package_windows(binary, Path(temp), args.dll_dir, args.require_static_crt)
|
||||
else:
|
||||
artifacts = package_linux(binary, Path(temp))
|
||||
for artifact in artifacts:
|
||||
destination = output / artifact.name
|
||||
artifact.replace(destination)
|
||||
print(destination)
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
param(
|
||||
[string]$OutputDirectory = (Join-Path $PSScriptRoot '..\..\target\dist'),
|
||||
[string[]]$DllDirectory = @()
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repo = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||
$destination = [IO.Path]::GetFullPath($OutputDirectory)
|
||||
$dllDirs = @($DllDirectory | ForEach-Object { (Resolve-Path -LiteralPath $_).Path })
|
||||
if (-not [Environment]::Is64BitProcess) { throw 'Run this build in x64 PowerShell.' }
|
||||
|
||||
$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
|
||||
$vs = & $vswhere -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
|
||||
if ($LASTEXITCODE -ne 0 -or -not $vs) { throw 'Install the Visual Studio C++ x64 build tools and Windows SDK.' }
|
||||
Import-Module (Join-Path $vs 'Common7\Tools\Microsoft.VisualStudio.DevShell.dll')
|
||||
Enter-VsDevShell -VsInstallPath $vs -SkipAutomaticLocation -DevCmdArguments '-arch=x64 -host_arch=x64'
|
||||
|
||||
# A short, fresh target path keeps link.exe below MAX_PATH on service-account runners.
|
||||
$work = New-Item -ItemType Directory -Path (Join-Path ([IO.Path]::GetTempPath()) ([IO.Path]::GetRandomFileName()))
|
||||
Push-Location $repo
|
||||
try {
|
||||
$env:CARGO_TARGET_DIR = Join-Path $work.FullName 'b'
|
||||
# With --target, Cargo applies this to target crates only. The encoded setting
|
||||
# takes precedence over inherited RUSTFLAGS, including on self-hosted runners.
|
||||
$env:CARGO_ENCODED_RUSTFLAGS = '-Ctarget-feature=+crt-static'
|
||||
$env:VCPKGRS_DISABLE = '1'
|
||||
cargo build --locked --release --target x86_64-pc-windows-msvc --features vendored-lua,curl/static-curl
|
||||
if ($LASTEXITCODE -ne 0) { throw "Windows build failed ($LASTEXITCODE)." }
|
||||
$binary = Join-Path $env:CARGO_TARGET_DIR 'x86_64-pc-windows-msvc\release\rusty-path-of-building.exe'
|
||||
|
||||
$venv = Join-Path $work.FullName 'py'
|
||||
python -m venv $venv
|
||||
if ($LASTEXITCODE -ne 0) { throw "Could not create the packaging environment ($LASTEXITCODE)." }
|
||||
$packagingPython = Join-Path $venv 'Scripts\python.exe'
|
||||
& $packagingPython -m pip install --disable-pip-version-check --no-input --require-hashes -r packaging/windows/requirements.txt
|
||||
if ($LASTEXITCODE -ne 0) { throw "Windows packaging dependency installation failed ($LASTEXITCODE)." }
|
||||
|
||||
# A third-party DLL can itself use the VC runtime. Use the selected toolset's
|
||||
# app-local redistributables when needed, even on a host with a global redist.
|
||||
if ($env:VCToolsRedistDir) {
|
||||
$x64 = Join-Path $env:VCToolsRedistDir 'x64'
|
||||
if (Test-Path -LiteralPath $x64) {
|
||||
$dllDirs += @(Get-ChildItem -LiteralPath $x64 -Directory -Filter 'Microsoft.VC*.CRT' | ForEach-Object { $_.FullName })
|
||||
}
|
||||
}
|
||||
$packageArgs = @('packaging/package.py', 'windows', $binary, '--output', $destination, '--require-static-crt')
|
||||
foreach ($dir in $dllDirs) { $packageArgs += @('--dll-dir', $dir) }
|
||||
& $packagingPython @packageArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "Windows packaging failed ($LASTEXITCODE)." }
|
||||
& $packagingPython packaging/check_windows_release.py $destination
|
||||
if ($LASTEXITCODE -ne 0) { throw "Packaged Windows executable failed verification ($LASTEXITCODE)." }
|
||||
} finally {
|
||||
Pop-Location
|
||||
Remove-Item -LiteralPath $work.FullName -Recurse -Force -ErrorAction Continue
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
Unicode true
|
||||
!define MUI_ICON "app.ico"
|
||||
!define MUI_UNICON "app.ico"
|
||||
!include "MUI2.nsh"
|
||||
!include "payload-files.nsh"
|
||||
|
||||
Name "Rusty Path of Building"
|
||||
OutFile "${OUTPUT}"
|
||||
@@ -24,15 +27,12 @@ FunctionEnd
|
||||
|
||||
Section "Rusty Path of Building"
|
||||
SetShellVarContext current
|
||||
SetOutPath "$INSTDIR"
|
||||
File "payload\${APP}"
|
||||
SetOutPath "$INSTDIR\licenses"
|
||||
File "payload\licenses\LICENSE.txt"
|
||||
File "payload\licenses\LiberationSans.txt"
|
||||
File "payload\licenses\VeraMono.txt"
|
||||
!insertmacro InstallPayload
|
||||
SetOutPath "$INSTDIR"
|
||||
WriteUninstaller "$INSTDIR\Uninstall.exe"
|
||||
CreateShortcut "$SMPROGRAMS\Rusty Path of Building.lnk" "$INSTDIR\${APP}"
|
||||
CreateShortcut "$SMPROGRAMS\Rusty Path of Building - PoE 1.lnk" "$INSTDIR\${APP}" "poe1"
|
||||
CreateShortcut "$SMPROGRAMS\Rusty Path of Building - PoE 2.lnk" "$INSTDIR\${APP}" "poe2"
|
||||
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayName" "Rusty Path of Building"
|
||||
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayVersion" "${VERSION}"
|
||||
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayIcon" "$INSTDIR\${APP}"
|
||||
@@ -46,11 +46,9 @@ Section "Uninstall"
|
||||
SetRegView 64
|
||||
SetShellVarContext current
|
||||
Delete "$SMPROGRAMS\Rusty Path of Building.lnk"
|
||||
Delete "$INSTDIR\${APP}"
|
||||
Delete "$INSTDIR\licenses\LICENSE.txt"
|
||||
Delete "$INSTDIR\licenses\LiberationSans.txt"
|
||||
Delete "$INSTDIR\licenses\VeraMono.txt"
|
||||
RMDir "$INSTDIR\licenses"
|
||||
Delete "$SMPROGRAMS\Rusty Path of Building - PoE 1.lnk"
|
||||
Delete "$SMPROGRAMS\Rusty Path of Building - PoE 2.lnk"
|
||||
!insertmacro UninstallPayload
|
||||
Delete "$INSTDIR\Uninstall.exe"
|
||||
RMDir "$INSTDIR"
|
||||
DeleteRegKey HKCU "${UNINSTALL_KEY}"
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# Windows packaging only; the universal wheel digest is from PyPI.
|
||||
--only-binary=:all:
|
||||
pefile==2024.8.26 --hash=sha256:76f8b485dcd3b1bb8166f1128d395fa3d87af26360c2358fb75b80019b957c6f
|
||||
@@ -0,0 +1,202 @@
|
||||
"""Resolve the app-local PE dependency closure without consulting PATH or System32."""
|
||||
|
||||
from collections import deque
|
||||
from dataclasses import dataclass
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
|
||||
# Windows 10+ supplies these libraries. Redistributables and driver-provided
|
||||
# libraries deliberately do not belong here. UCRT is an OS component on 10+.
|
||||
SYSTEM_DLLS = frozenset("""
|
||||
advapi32.dll avrt.dll bcrypt.dll bcryptprimitives.dll cabinet.dll cfgmgr32.dll
|
||||
clbcatq.dll comctl32.dll comdlg32.dll combase.dll crypt32.dll cryptbase.dll
|
||||
cryptnet.dll cryptsp.dll d2d1.dll d3d11.dll d3d12.dll d3d9.dll dcomp.dll
|
||||
dbghelp.dll dnsapi.dll dwrite.dll dwmapi.dll dxgi.dll gdi32.dll
|
||||
gdi32full.dll hid.dll imagehlp.dll imm32.dll iphlpapi.dll kernel32.dll
|
||||
kernelbase.dll mpr.dll msimg32.dll msvcrt.dll mswsock.dll ncrypt.dll
|
||||
netapi32.dll normaliz.dll nsi.dll ntdll.dll ole32.dll oleacc.dll oleaut32.dll
|
||||
opengl32.dll powrprof.dll propsys.dll psapi.dll rpcrt4.dll sechost.dll
|
||||
secur32.dll setupapi.dll shcore.dll shell32.dll shlwapi.dll sspicli.dll
|
||||
ucrtbase.dll user32.dll userenv.dll usp10.dll uxtheme.dll version.dll
|
||||
wer.dll windowscodecs.dll winhttp.dll wininet.dll winmm.dll winspool.drv
|
||||
wintrust.dll wldap32.dll ws2_32.dll wtsapi32.dll
|
||||
""".split())
|
||||
API_SET = re.compile(r"(?:api|ext)-ms-[a-z0-9-]+-l\d+-\d+-\d+\.dll\Z")
|
||||
VC_RUNTIME = re.compile(r"(?:vcruntime|msvcp|msvcr|msvcm|concrt|vcomp|vccorlib)\d[\w]*\.dll\Z")
|
||||
DEBUG_RUNTIME = re.compile(
|
||||
r"(?:(?:vcruntime|msvcp|msvcr|msvcm|concrt|vcomp|vccorlib)\d[\w]*d(?:_\w+)?"
|
||||
r"|mfc(?:m)?\d+u?d|ucrtbased|msvcrtd)\.dll\Z"
|
||||
)
|
||||
DEVICE_NAME = re.compile(r"(?:con|prn|aux|nul|com[1-9]|lpt[1-9])\Z", re.I)
|
||||
|
||||
|
||||
def safe_basename(name):
|
||||
"""Use a portable subset of Windows filenames that is also literal NSIS text."""
|
||||
if (not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.+ -]{0,254}", name)
|
||||
or name.endswith((".", " "))
|
||||
or DEVICE_NAME.fullmatch(name.split(".")[0].rstrip())):
|
||||
raise ValueError(f"Unsafe Windows/NSIS filename: {name!r}")
|
||||
return name
|
||||
|
||||
|
||||
def dll_name(value):
|
||||
name = safe_basename(value.decode("ascii")).lower()
|
||||
if not name.endswith((".dll", ".drv")):
|
||||
raise ValueError(f"Expected a DLL basename, got {name!r}")
|
||||
return name
|
||||
|
||||
|
||||
def dynamic_crt(name):
|
||||
return (bool(VC_RUNTIME.fullmatch(name)) or name in {"msvcrt.dll", "ucrtbase.dll"}
|
||||
or name.startswith(("api-ms-win-crt-", "ext-ms-win-crt-")))
|
||||
|
||||
|
||||
@dataclass
|
||||
class Imports:
|
||||
libraries: dict[str, set[bytes | int]]
|
||||
forwarders: dict[bytes | int, tuple[str, bytes | int]]
|
||||
|
||||
|
||||
def descriptor_count(pe, directory, width):
|
||||
"""pefile can skip unreadable DLL entries. Compare with the on-disk descriptors."""
|
||||
if not (directory.VirtualAddress or directory.Size):
|
||||
return 0
|
||||
if not directory.VirtualAddress or directory.Size < width:
|
||||
raise ValueError("Truncated PE import directory")
|
||||
data = pe.get_data(directory.VirtualAddress, directory.Size)
|
||||
if len(data) != directory.Size:
|
||||
raise ValueError("Truncated PE import directory")
|
||||
for offset in range(0, len(data) - width + 1, width):
|
||||
if not any(data[offset:offset + width]):
|
||||
return offset // width
|
||||
raise ValueError("Unterminated PE import directory")
|
||||
|
||||
|
||||
def inspect_pe(path, *, dll=False):
|
||||
# Linux packaging never imports pefile or needs its wheel installed.
|
||||
try:
|
||||
import pefile
|
||||
except ImportError as error:
|
||||
raise ValueError("Windows packaging requires: python -m pip install --require-hashes "
|
||||
"-r packaging/windows/requirements.txt") from error
|
||||
try:
|
||||
with pefile.PE(str(path), fast_load=True) as pe:
|
||||
if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B:
|
||||
raise ValueError("Expected an AMD64 PE32+ image")
|
||||
if not pe.FILE_HEADER.Characteristics & 0x0002:
|
||||
raise ValueError("PE is not an executable image")
|
||||
if bool(pe.FILE_HEADER.Characteristics & 0x2000) != dll:
|
||||
raise ValueError("Expected a DLL image" if dll else "Expected an executable, not a DLL")
|
||||
directories = pe.OPTIONAL_HEADER.DATA_DIRECTORY
|
||||
if pe.OPTIONAL_HEADER.NumberOfRvaAndSizes > len(directories):
|
||||
raise ValueError("Truncated PE data directories")
|
||||
before = len(pe.get_warnings())
|
||||
pe.parse_data_directories([0, 1, 13])
|
||||
# This heuristic says nothing about malformed data; real plugins may
|
||||
# import only LoadLibrary/GetProcAddress. All parsing warnings fail.
|
||||
warnings = [w for w in pe.get_warnings()[before:] if w !=
|
||||
"Imported symbols contain entries typical of packed executables."]
|
||||
if warnings:
|
||||
raise ValueError("Malformed PE dependency data: " + "; ".join(warnings))
|
||||
libraries = {}
|
||||
for index, width, attr in ((1, 20, "DIRECTORY_ENTRY_IMPORT"),
|
||||
(13, 32, "DIRECTORY_ENTRY_DELAY_IMPORT")):
|
||||
if index >= len(directories):
|
||||
continue
|
||||
entries = getattr(pe, attr, [])
|
||||
if len(entries) != descriptor_count(pe, directories[index], width):
|
||||
raise ValueError(f"Incomplete PE directory {index}: parser skipped descriptors")
|
||||
for entry in entries:
|
||||
name = dll_name(entry.dll)
|
||||
symbols = libraries.setdefault(name, set())
|
||||
for symbol in entry.imports:
|
||||
if symbol.import_by_ordinal:
|
||||
symbols.add(symbol.ordinal)
|
||||
else:
|
||||
if not symbol.name or symbol.name == b"*invalid*":
|
||||
raise ValueError(f"Malformed imported symbol in {name}")
|
||||
symbols.add(symbol.name)
|
||||
|
||||
forwarders = {}
|
||||
exports = getattr(pe, "DIRECTORY_ENTRY_EXPORT", None)
|
||||
if directories and directories[0].VirtualAddress and exports is None:
|
||||
raise ValueError("Unparsed PE export directory")
|
||||
if exports is not None:
|
||||
for symbol in exports.symbols:
|
||||
if symbol.forwarder is None:
|
||||
continue
|
||||
forwarder = symbol.forwarder
|
||||
library, separator, target = forwarder.rpartition(b".")
|
||||
if not library or not separator or not target:
|
||||
raise ValueError(f"Malformed forwarded export {forwarder!r}")
|
||||
name = dll_name(library if library.lower().endswith(b".dll") else library + b".dll")
|
||||
if target.startswith(b"#"):
|
||||
if not target[1:].isdigit() or not 0 < int(target[1:]) <= 65535:
|
||||
raise ValueError(f"Malformed forwarded ordinal {target!r}")
|
||||
target = int(target[1:])
|
||||
forwarders[symbol.ordinal] = (name, target)
|
||||
if symbol.name is not None:
|
||||
forwarders[symbol.name] = (name, target)
|
||||
return Imports(libraries, forwarders)
|
||||
except (pefile.PEFormatError, ValueError, OSError) as error:
|
||||
raise ValueError(f"{path}: {error}") from error
|
||||
|
||||
|
||||
def resolve_dependencies(binary, dll_dirs=(), require_static_crt=False):
|
||||
"""Return {Windows basename: source path}, with only imported DLLs selected."""
|
||||
binary = Path(binary).resolve()
|
||||
directories = list(dict.fromkeys([binary.parent, *(Path(p).resolve() for p in dll_dirs)]))
|
||||
candidates = {}
|
||||
for directory in directories:
|
||||
if not directory.is_dir():
|
||||
raise ValueError(f"DLL source is not a directory: {directory}")
|
||||
for path in sorted(directory.iterdir(), key=lambda p: p.name):
|
||||
candidates.setdefault(path.name.lower(), []).append(path)
|
||||
|
||||
root = inspect_pe(binary)
|
||||
if require_static_crt:
|
||||
dynamic = sorted(name for name in root.libraries if dynamic_crt(name) or DEBUG_RUNTIME.fullmatch(name))
|
||||
if dynamic:
|
||||
raise ValueError(f"{binary.name}: --require-static-crt rejects dynamic CRT imports: "
|
||||
+ ", ".join(dynamic))
|
||||
pending = deque((name, symbols, (binary.name, name)) for name, symbols in sorted(root.libraries.items()))
|
||||
selected, inspected, visited = {}, {}, {}
|
||||
while pending:
|
||||
name, symbols, chain = pending.popleft()
|
||||
try:
|
||||
if DEBUG_RUNTIME.fullmatch(name):
|
||||
raise ValueError(f"Debug VC runtime cannot be redistributed: {name}")
|
||||
if name in SYSTEM_DLLS or API_SET.fullmatch(name):
|
||||
continue
|
||||
if name not in inspected:
|
||||
paths = candidates.get(name, [])
|
||||
if not paths:
|
||||
raise ValueError(f"Missing {name}; supply its redistributable directory with --dll-dir. "
|
||||
f"Searched: {', '.join(map(str, directories))}")
|
||||
for path in paths:
|
||||
if path.is_symlink() or not path.is_file():
|
||||
raise ValueError(f"DLL source must be a regular, non-symlink file: {path}")
|
||||
safe_basename(path.name)
|
||||
if len(paths) > 1:
|
||||
digests = set()
|
||||
for path in paths:
|
||||
with path.open("rb") as stream:
|
||||
digests.add(hashlib.file_digest(stream, "sha256").digest())
|
||||
if len(digests) != 1:
|
||||
raise ValueError(f"Ambiguous differing sources for {name}: {', '.join(map(str, paths))}")
|
||||
selected[name] = paths[0]
|
||||
inspected[name] = inspect_pe(paths[0], dll=True)
|
||||
pending.extend((dependency, requested, (*chain, dependency)) for dependency, requested
|
||||
in sorted(inspected[name].libraries.items()))
|
||||
seen = visited.setdefault(name, set())
|
||||
for symbol in symbols - seen:
|
||||
forwarded = inspected[name].forwarders.get(symbol)
|
||||
if forwarded:
|
||||
dependency, target = forwarded
|
||||
pending.append((dependency, {target}, (*chain, dependency)))
|
||||
seen.update(symbols)
|
||||
except (ValueError, OSError) as error:
|
||||
raise ValueError(f"{' -> '.join(chain)}: {error}") from error
|
||||
return dict(sorted(selected.items()))
|
||||
Reference in new issue
Block a user