Files
asteria-qt/scripts/verify-windows-dlls.py
2026-11-13 10:56:08 +01:00

330 lines
9.2 KiB
Python
Executable File

#!/usr/bin/env python3
"""
Bundles (optional) and verifies that all non-system PE (.exe / .dll) import
dependencies in a Windows distribution folder are present inside the folder.
Usage:
verify-windows-dlls.py <dist-dir> [--bundle-from <dir> ...]
"""
import argparse
import os
import shutil
import struct
import sys
# Standard Windows OS system DLLs provided by Windows (System32)
SYSTEM_DLLS = {
"advapi32.dll",
"authz.dll",
"bcrypt.dll",
"bcryptprimitives.dll",
"cabinet.dll",
"cfgmgr32.dll",
"combase.dll",
"comctl32.dll",
"comdlg32.dll",
"credui.dll",
"crypt32.dll",
"cryptbase.dll",
"d2d1.dll",
"d3d9.dll",
"d3d10warp.dll",
"d3d11.dll",
"d3d12.dll",
"d3dcompiler_47.dll",
"dbghelp.dll",
"dcomp.dll",
"dhcpcsvc.dll",
"dhcpcsvc6.dll",
"dnsapi.dll",
"dwmapi.dll",
"dwrite.dll",
"dxcore.dll",
"dxgi.dll",
"gdi32.dll",
"gdiplus.dll",
"glu32.dll",
"hid.dll",
"imagehlp.dll",
"imm32.dll",
"iphlpapi.dll",
"kernel32.dll",
"kernelbase.dll",
"ksuser.dll",
"mf.dll",
"mfplat.dll",
"mfreadwrite.dll",
"mfuuid.dll",
"mmdevapi.dll",
"mpr.dll",
"mscms.dll",
"msimg32.dll",
"msvcp_win.dll",
"msvcrt.dll",
"mswsock.dll",
"ncrypt.dll",
"netapi32.dll",
"netutils.dll",
"normaliz.dll",
"ntdll.dll",
"ole32.dll",
"oleaut32.dll",
"opengl32.dll",
"pdh.dll",
"powrprof.dll",
"propsys.dll",
"psapi.dll",
"rpcrt4.dll",
"runtimeobject.dll",
"secur32.dll",
"setupapi.dll",
"shcore.dll",
"shell32.dll",
"shlwapi.dll",
"srvcli.dll",
"synchronization.dll",
"ucrtbase.dll",
"uiautomationcore.dll",
"urlmon.dll",
"user32.dll",
"userenv.dll",
"usp10.dll",
"uxtheme.dll",
"version.dll",
"vulkan-1.dll",
"wevtapi.dll",
"winhttp.dll",
"wininet.dll",
"winmm.dll",
"winspool.drv",
"wkscli.dll",
"wldap32.dll",
"ws2_32.dll",
"wtsapi32.dll",
"xinput1_4.dll",
"xmllite.dll",
}
def is_system_dll(name):
lower = name.lower()
if lower in SYSTEM_DLLS:
return True
if lower.startswith("api-ms-win-") or lower.startswith("ext-ms-win-"):
return True
return False
def rva_to_offset(rva, sections):
for vaddr, vsize, raw_ptr, raw_size in sections:
size = max(vsize, raw_size)
if vaddr <= rva < vaddr + size:
return raw_ptr + (rva - vaddr)
return None
def read_cstring(data, offset):
if offset is None or offset < 0 or offset >= len(data):
return None
end = data.find(b"\x00", offset)
if end == -1:
return None
return data[offset:end].decode("ascii", errors="replace")
def get_pe_imports(filepath):
with open(filepath, "rb") as f:
data = f.read()
if len(data) < 0x40 or data[:2] != b"MZ":
return []
pe_offset = struct.unpack_from("<I", data, 0x3C)[0]
if pe_offset + 24 > len(data) or data[pe_offset : pe_offset + 4] != b"PE\x00\x00":
return []
num_sections = struct.unpack_from("<H", data, pe_offset + 6)[0]
opt_header_size = struct.unpack_from("<H", data, pe_offset + 20)[0]
opt_offset = pe_offset + 24
if opt_offset + opt_header_size > len(data):
return []
magic = struct.unpack_from("<H", data, opt_offset)[0]
if magic == 0x20B: # PE32+ (64-bit: x86_64 / ARM64)
dd_offset = opt_offset + 112
elif magic == 0x10B: # PE32 (32-bit)
dd_offset = opt_offset + 96
else:
return []
num_rva = struct.unpack_from("<I", data, dd_offset - 4)[0]
if num_rva < 2:
return []
import_rva, import_size = struct.unpack_from("<II", data, dd_offset + 8)
if import_rva == 0 or import_size == 0:
return []
sec_offset = opt_offset + opt_header_size
sections = []
for i in range(num_sections):
s_off = sec_offset + i * 40
if s_off + 40 > len(data):
break
vsize, vaddr, raw_size, raw_ptr = struct.unpack_from("<IIII", data, s_off + 8)
sections.append((vaddr, vsize, raw_ptr, raw_size))
imp_offset = rva_to_offset(import_rva, sections)
if imp_offset is None:
return []
imports = []
pos = imp_offset
while pos + 20 <= len(data):
orig_thunk, ts, fwd, name_rva, first_thunk = struct.unpack_from("<IIIII", data, pos)
if orig_thunk == 0 and name_rva == 0 and first_thunk == 0:
break
name_off = rva_to_offset(name_rva, sections)
dll_name = read_cstring(data, name_off)
if dll_name:
imports.append(dll_name)
pos += 20
return imports
def collect_pe_files(dist_dir):
pe_files = []
for root, _, files in os.walk(dist_dir):
for fname in files:
lower = fname.lower()
if lower.endswith(".dll") or lower.endswith(".exe"):
pe_files.append(os.path.join(root, fname))
return sorted(pe_files)
def bundle_transitive_dlls(dist_dir, search_dirs):
"""
Walks all PE files in dist_dir and recursively copies required non-system DLLs
from search_dirs into dist_dir root.
"""
# Build case-insensitive lookup index of available DLLs in search_dirs
available = {}
for sdir in search_dirs:
if not sdir or not os.path.isdir(sdir):
continue
for fname in os.listdir(sdir):
if fname.lower().endswith(".dll"):
lower = fname.lower()
if lower not in available:
available[lower] = os.path.join(sdir, fname)
# Track DLLs already present in dist_dir
present = set()
queue = []
for full_path in collect_pe_files(dist_dir):
present.add(os.path.basename(full_path).lower())
queue.append(full_path)
copied_count = 0
while queue:
current_pe = queue.pop(0)
current_dir = os.path.dirname(current_pe)
local_dlls = {
f.lower()
for f in os.listdir(current_dir)
if f.lower().endswith(".dll") or f.lower().endswith(".exe")
}
for imp in get_pe_imports(current_pe):
imp_lower = imp.lower()
if is_system_dll(imp_lower):
continue
if imp_lower in present or imp_lower in local_dlls:
continue
if imp_lower in available:
src_dll = available[imp_lower]
dst_dll = os.path.join(dist_dir, os.path.basename(src_dll))
shutil.copy2(src_dll, dst_dll)
present.add(imp_lower)
queue.append(dst_dll)
copied_count += 1
print(f"==> Bundled {copied_count} transitive runtime DLLs into {dist_dir}")
def verify_dist_directory(dist_dir):
root_dlls = set()
all_pe_files = []
for root, _, files in os.walk(dist_dir):
for fname in files:
lower = fname.lower()
if lower.endswith(".dll") or lower.endswith(".exe"):
full_path = os.path.join(root, fname)
all_pe_files.append(full_path)
if os.path.abspath(root) == os.path.abspath(dist_dir):
root_dlls.add(lower)
if not all_pe_files:
raise RuntimeError(f"No .exe or .dll files found in {dist_dir}")
missing_by_dll = {}
for pe_file in sorted(all_pe_files):
rel_pe = os.path.relpath(pe_file, dist_dir)
local_dir = os.path.dirname(pe_file)
local_dlls = {
f.lower()
for f in os.listdir(local_dir)
if f.lower().endswith(".dll") or f.lower().endswith(".exe")
}
for imp in get_pe_imports(pe_file):
imp_lower = imp.lower()
if is_system_dll(imp_lower):
continue
if imp_lower not in root_dlls and imp_lower not in local_dlls:
missing_by_dll.setdefault(imp, []).append(rel_pe)
if missing_by_dll:
print(f"FAILED: Found {len(missing_by_dll)} missing DLL dependencies in {dist_dir}:", file=sys.stderr)
for dll, importers in sorted(missing_by_dll.items()):
print(f" [MISSING] {dll} needed by:", file=sys.stderr)
for importer in importers[:5]:
print(f" - {importer}", file=sys.stderr)
if len(importers) > 5:
print(f" ... and {len(importers) - 5} more", file=sys.stderr)
sys.exit(1)
print(
f"==> DLL verification passed: scanned {len(all_pe_files)} binaries in {dist_dir}, "
"0 missing dependencies."
)
def main():
parser = argparse.ArgumentParser(description="Bundle and verify PE DLL imports in a Windows dist directory")
parser.add_argument("dist_dir", help="Path to the distribution directory containing asteria-qt.exe")
parser.add_argument(
"--bundle-from",
nargs="+",
default=[],
help="Optional list of bin directories to copy transitive DLL dependencies from before verifying",
)
args = parser.parse_args()
if not os.path.isdir(args.dist_dir):
print(f"Error: directory does not exist: {args.dist_dir}", file=sys.stderr)
sys.exit(1)
if args.bundle_from:
bundle_transitive_dlls(args.dist_dir, args.bundle_from)
verify_dist_directory(args.dist_dir)
if __name__ == "__main__":
main()