diff --git a/setup.py b/setup.py index 14d982ca..e15612f8 100644 --- a/setup.py +++ b/setup.py @@ -2142,21 +2142,40 @@ def hip_lib_dirs(eng: Path) -> list[Path]: HIP_RUNTIME_DLLS = ("amdhip64_*.dll", "amd_comgr*.dll") +def hip_runtime_closure(d: Path) -> list[str]: + """The DLLs of `d` (the engine's rocm/bin) that amdhip64_7.dll and amd_comgr.dll need, the two included, read from + their PE import tables and followed recursively (tools/hip/dll_closure.py). #461: amdhip64_7.dll imports + rocm_kpack.dll, which imports the MSVC runtime; with only the two DLLs beside strata.exe the full-path load fails + (error 126), Windows falls back to System32's copy of the runtime, and the first big prompt dies with + hipErrorInvalidDeviceFunction. Falls back to the names above when the helper cannot be read.""" + roots = sorted({p.name for pat in HIP_RUNTIME_DLLS for p in d.glob(pat)}) + try: + sys.path.insert(0, str(ROOT / "tools" / "hip")) + from dll_closure import dll_closure + return dll_closure(d, roots) + except Exception: # noqa: BLE001 - a missing helper must not stop setup + return roots + finally: + if str(ROOT / "tools" / "hip") in sys.path: + sys.path.remove(str(ROOT / "tools" / "hip")) + + def hip_runtime_beside_exe(eng: Path) -> None: - """Copy the bundled HIP runtime DLLs from rocm/bin next to the engine's exes when missing or different (a 0.1.34 - install, whose zip had them in rocm/bin only, is fixed on its next start).""" + """Copy the bundled HIP runtime DLLs and everything they import from rocm/bin next to the engine's exes when + missing or different (a 0.1.34 install, whose zip had them in rocm/bin only, is fixed on its next start; a + 0.1.40.2 install, which got only the two runtime DLLs, gets rocm_kpack.dll and the C++ runtime now, #461).""" for d in hip_lib_dirs(eng): - for pat in HIP_RUNTIME_DLLS: - for src in d.glob(pat): - dst = eng / src.name - try: - if dst.exists() and dst.stat().st_size == src.stat().st_size and \ - dst.stat().st_mtime >= src.stat().st_mtime: - continue - shutil.copy2(src, dst) - except OSError as e: # e.g. the engine is running and holds the old copy - warn(f"could not put {src.name} next to the AMD engine ({e}); if the engine stops on its first " - "request, close Strata and run START-HERE.bat again") + for name in hip_runtime_closure(d): + src = d / name + dst = eng / src.name + try: + if dst.exists() and dst.stat().st_size == src.stat().st_size and \ + dst.stat().st_mtime >= src.stat().st_mtime: + continue + shutil.copy2(src, dst) + except OSError as e: # e.g. the engine is running and holds the old copy + warn(f"could not put {src.name} next to the AMD engine ({e}); if the engine stops on its first " + "request, close Strata and run START-HERE.bat again") def hip_match(card: dict, listed: list[dict], hip: list[dict]) -> dict | None: diff --git a/src/program/generate.cpp b/src/program/generate.cpp index a78d0886..5a01ac2b 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -3972,11 +3972,25 @@ int main(int argc, char** argv) { const size_t cut = beside.find_last_of("\\/"); beside = (cut == std::string::npos ? std::string() : beside.substr(0, cut + 1)) + "amdhip64_7.dll"; if (GetFileAttributesA(beside.c_str()) != INVALID_FILE_ATTRIBUTES && - _stricmp(beside.c_str(), path) != 0) + _stricmp(beside.c_str(), path) != 0) { std::fprintf(stderr, "strata generate: WARNING: the HIP runtime in use is not the bundled one beside " "the engine (%s): if prompts fail with hipErrorInvalidDeviceFunction, tell the " "maintainers with this log (#1261)\n", beside.c_str()); + // #461: why the bundled one lost. Its imports (rocm_kpack.dll and the C++ runtime) must be beside the + // exe too; LoadLibraryEx on it with the search limited to its own folder says what is missing (126 = + // a dependency). A diagnostic only: the copy it loads is released at once and nothing is forced. + SetLastError(0); + HMODULE probe = LoadLibraryExA(beside.c_str(), nullptr, + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); + const DWORD le = probe != nullptr ? 0 : GetLastError(); + if (probe != nullptr) FreeLibrary(probe); + std::fprintf(stderr, "strata generate: the bundled runtime beside the engine %s (GetLastError %lu)%s\n", + probe != nullptr ? "loads on its own" : "does NOT load", (unsigned long) le, + le == 126 ? ": a DLL it imports is missing from the engine's folder (rocm_kpack.dll, " + "msvcp140.dll, vcruntime140.dll, vcruntime140_1.dll); run START-HERE.bat " + "again (0.1.40.3 and later copy them)" : ""); + } } } } diff --git a/tools/hip/dll_closure.py b/tools/hip/dll_closure.py new file mode 100644 index 00000000..4a56f6a3 --- /dev/null +++ b/tools/hip/dll_closure.py @@ -0,0 +1,117 @@ +"""tools/hip/dll_closure.py - which DLLs a DLL needs, read from the PE import tables (no pefile, no objdump). + + python tools/hip/dll_closure.py DIR amdhip64_7.dll amd_comgr.dll # prints the closure inside DIR + +Why: the Windows HIP engine puts amdhip64_7.dll and amd_comgr.dll next to strata.exe so that Windows binds THEM and not +an AMD driver's copy in System32 (#468, #461). But amdhip64_7.dll itself imports rocm_kpack.dll, which imports the +MSVC runtime; with only the two DLLs beside the exe the full-path load fails (error 126, ERROR_MOD_NOT_FOUND), Windows +falls back to System32's copy, and the first big prompt dies with hipErrorInvalidDeviceFunction (#461, maraa081). So +what goes beside the exe is the DLLs' whole dependency closure, computed here from the files actually shipped rather +than from a list of names that goes stale with the next ROCm. + +A name is followed only when the DLL exists in `search_dir` (the bundle's rocm/bin). Everything else - kernel32, +user32, setupapi, the api-ms-win-* forwarders - is a Windows system DLL and is left alone. +""" +from __future__ import annotations + +import struct +import sys +from pathlib import Path + + +def pe_imports(path) -> list[str]: + """The DLL names in a PE file's import table and delay-import table, in file order. [] for a file that is not a + PE image (or is truncated): the caller treats it as a leaf.""" + try: + data = Path(path).read_bytes() + except OSError: + return [] + try: + if data[:2] != b"MZ": + return [] + pe = struct.unpack_from(" list[str]: + """`roots` (file names inside `search_dir`) plus every DLL in `search_dir` they import, followed recursively. + The names are returned as spelled on disk, roots first, the rest in discovery order. A root that is not in the + directory is skipped; an import that is not in the directory (a Windows system DLL) is not followed.""" + d = Path(search_dir) + on_disk = {p.name.lower(): p.name for p in d.iterdir() if p.is_file() and p.suffix.lower() == ".dll"} \ + if d.is_dir() else {} + out: list[str] = [] + todo = [r for r in roots] + seen: set[str] = set() + while todo: + name = todo.pop(0) + low = name.lower() + if low in seen or low not in on_disk: + continue + seen.add(low) + real = on_disk[low] + out.append(real) + for dep in imports(d / real): + if dep.lower() not in seen: + todo.append(dep) + return out + + +def main() -> int: + if len(sys.argv) < 3: + print(__doc__) + return 2 + for n in dll_closure(sys.argv[1], sys.argv[2:]): + print(n) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/hip/package_windows.py b/tools/hip/package_windows.py index 1ece8f0d..a2104e81 100644 --- a/tools/hip/package_windows.py +++ b/tools/hip/package_windows.py @@ -7,7 +7,7 @@ tools/hip/build_windows.bat runs it after the build. The zip holds: strata.exe, strata-device.exe, BUILD.json (backend "hip", the archs, the ROCm and hipBLASLt versions) - amdhip64_7.dll, amd_comgr.dll the HIP runtime beside the exes too (#468 #461: before System32) + amdhip64_7.dll, amd_comgr.dll + what they import the HIP runtime beside the exes too (#468 #461: before System32) rocm/bin/*.dll the ROCm DLLs the two programs load (their import tables, followed through the ROCm DLLs, + amd_comgr.dll, which the HIP runtime loads by name) and the Microsoft C++ runtime they import @@ -108,9 +108,13 @@ def main() -> int: # #468 #461: the HIP runtime (and the compiler it loads by name) next to the exes as well - Windows searches the # exe's folder before System32, where an AMD driver may install its own amdhip64_7.dll (found before PATH's # rocm/bin); rocBLAS/hipBLASLt stay in rocm/bin, which they resolve their kernel libraries and ../.kpack from - for pat in ("amdhip64_*.dll", "amd_comgr*.dll"): - for f in (stage / "rocm" / "bin").glob(pat): - shutil.copy2(f, stage / f.name) + # #461: and everything those two import (amdhip64_7.dll needs rocm_kpack.dll and the C++ runtime, or its full-path + # load fails with error 126 and Windows falls back to System32's copy): the closure of their PE import tables + sys.path.insert(0, str(Path(__file__).resolve().parent)) + from dll_closure import dll_closure + roots = sorted(f.name for pat in ("amdhip64_*.dll", "amd_comgr*.dll") for f in (stage / "rocm" / "bin").glob(pat)) + for name in dll_closure(stage / "rocm" / "bin", roots): + shutil.copy2(stage / "rocm" / "bin" / name, stage / name) # the GEMM kernels and the libraries' own device code, for these archs lib = stage / "rocm" / "bin" / "rocblas" / "library" diff --git a/tools/test_dll_closure.py b/tools/test_dll_closure.py new file mode 100644 index 00000000..5d4e4ca9 --- /dev/null +++ b/tools/test_dll_closure.py @@ -0,0 +1,155 @@ +"""#461: the DLLs the Windows HIP runtime needs beside strata.exe, from the PE import tables. + + python tools/test_dll_closure.py (the real-zip test skips when the 0.1.40.2 HIP zip is not here) + +Covers tools/hip/dll_closure.py and setup.hip_runtime_beside_exe on a fake engine folder. +""" +import os +import struct +import sys +import tempfile +import unittest +import zipfile +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "tools" / "hip")) +sys.path.insert(0, str(ROOT)) + +import dll_closure as dc # noqa: E402 +import setup # noqa: E402 + + +def fake_pe(imports, delay=()): + """A minimal PE32+ image whose import table (and delay-import table) names `imports` (`delay`).""" + text = bytearray() + va = 0x1000 + + def add_str(s): + off = len(text) + text.extend(s.encode() + b"\0") + return va + off + + names = [add_str(n) for n in imports] + dnames = [add_str(n) for n in delay] + while len(text) % 8: + text.append(0) + imp_off = len(text) + for rva in names: + text.extend(struct.pack("