okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221packaging: the Control python launcher uses no external command (dirname failed inside the AppImage on newer systems); the engine start error names a missing Windows DLL (0xC0000135) and says how to fix itadfb7ecb2

main
4.4 KiB105 linesraw
1"""serve/loader_diag.py - name the file a Windows engine could not load.
2
3A Windows program that imports a DLL which is not there ends with exit code 0xC0000135 and prints nothing. The person only sees
4"the engine stopped". This reads the engine's import table (the same reader as packaging/binary_deps.py, copied because the
5packaging folder does not travel with Control) and lists the DLLs that are neither beside the engine, nor in the Windows
6folders, nor part of the GPU driver, so the start error can say which file is missing.
7"""
8
9from __future__ import annotations
10
11import os
12import struct
13from pathlib import Path
14
15LOADER_FAILURE_CODES = (0xC0000135,)          # STATUS_DLL_NOT_FOUND
16
17def pe_imports(path: Path) -> list[str]:
18    """DLL names a PE file imports at load time (import table) plus delay-load imports."""
19    data = path.read_bytes()
20    if data[:2] != b"MZ":
21        raise ValueError("not a PE file")
22    pe = struct.unpack_from("<I", data, 0x3C)[0]
23    if data[pe:pe + 4] != b"PE\0\0":
24        raise ValueError("bad PE header")
25    nsec, = struct.unpack_from("<H", data, pe + 6)
26    opt_size, = struct.unpack_from("<H", data, pe + 20)
27    opt = pe + 24
28    magic, = struct.unpack_from("<H", data, opt)
29    dd = opt + (112 if magic == 0x20B else 96)
30    sections = []
31    sec = opt + opt_size
32    for i in range(nsec):
33        vsize, va, rsize, raw = struct.unpack_from("<IIII", data, sec + i * 40 + 8)
34        sections.append((va, max(vsize, rsize), raw))
35
36    def off(rva: int) -> int:
37        for va, size, raw in sections:
38            if va <= rva < va + size:
39                return raw + rva - va
40        raise ValueError("RVA outside every section")
41
42    def cstr(o: int) -> str:
43        return data[o:data.index(b"\0", o)].decode("ascii", "replace")
44
45    names: list[str] = []
46    imp_rva, imp_size = struct.unpack_from("<II", data, dd + 8)
47    if imp_rva and imp_size:
48        o = off(imp_rva)
49        while True:
50            _, _, _, name_rva, _ = struct.unpack_from("<IIIII", data, o)
51            if not name_rva:
52                break
53            names.append(cstr(off(name_rva)))
54            o += 20
55    delay_rva, delay_size = struct.unpack_from("<II", data, dd + 13 * 8)
56    if delay_rva and delay_size:
57        o = off(delay_rva)
58        while True:
59            attrs, name_rva = struct.unpack_from("<II", data, o)
60            if not name_rva:
61                break
62            names.append(cstr(off(name_rva)))
63            o += 32
64    return names
65
66
67def missing_files(exe, system_dirs=None) -> list[str]:
68    """DLL names the engine (and the DLLs beside it) import that cannot be found: not in the engine's folder, not a Windows or
69    driver library, and not in a Windows folder on this PC. Sorted, without duplicates; [] when nothing is missing or the file
70    cannot be read (this is advice for an error message, it never raises)."""
71    try:
72        exe = Path(exe)
73        folder = exe.parent
74        here = {p.name.lower() for p in folder.iterdir() if p.is_file()}
75        if system_dirs is None:
76            root = os.environ.get("SystemRoot") or r"C:\Windows"
77            system_dirs = [Path(root) / "System32", Path(root)]
78        files = [exe] + [p for p in sorted(folder.glob("*.dll"))]
79        missing: set[str] = set()
80        for f in files:
81            try:
82                names = pe_imports(f)
83            except (ValueError, OSError, struct.error):
84                continue
85            for name in names:
86                low = name.lower()
87                if low in here or low.startswith(("api-ms-win-", "ext-ms-win-")):
88                    continue                    # beside the engine, or a virtual API-set name Windows resolves itself
89                if any((d / name).exists() for d in system_dirs):
90                    continue
91                missing.add(name)               # not found anywhere the loader looks (a missing driver DLL is named too)
92        return sorted(missing, key=str.lower)
93    except OSError:
94        return []
95
96
97def missing_note(rc, exe) -> str:
98    """The sentence for the start error, or "" when the exit status is not a missing-library one or nothing can be named."""
99    if rc is None or (rc & 0xFFFFFFFF) not in LOADER_FAILURE_CODES or not exe:
100        return ""
101    names = missing_files(exe)
102    if not names:
103        return ""
104    return (f"\n  The engine is missing a file it needs ({', '.join(names)}). Reinstall the engine in Settings > Engine, "
105            f"or send us the log.")