diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env index 9b4b711705..38a1ff8053 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env @@ -927,6 +927,55 @@ PE = runpy.run_path(str(Path(__file__).resolve().parent / "droiddeck-wine-pe")) pe_machine = PE["pe_machine"] +def newest_foreign_backup(path): + newest = None + backup = path.with_name(path.name + FOREIGN_SUFFIX) + serial = 1 + while os.path.lexists(backup): + newest = backup + backup = path.with_name(path.name + FOREIGN_SUFFIX + ".%d" % serial) + serial += 1 + return newest + + +def restore_x64_guest_dlls(prefix, proton, env=None): + machines_by_folder = PE["proton_pe_machines"](proton, env or {}) + if machines_by_folder is None or 0xA641 not in machines_by_folder["system32"][1]: + return [] + builtins = Path(proton).parent / "files/lib/wine" / machines_by_folder["system32"][0] + system32 = Path(prefix) / "pfx/drive_c/windows/system32" + try: + names = sorted(name for name in os.listdir(system32) if name.lower().endswith(".dll")) + except OSError: + return [] + present, restorable = [], {} + for name in names: + path = system32 / name + if not path.is_symlink(): + if pe_machine(path) == 0x8664: + present.append(name) + continue + if not os.path.realpath(path).startswith(os.path.realpath(builtins) + os.sep): + continue + backup = newest_foreign_backup(path) + if backup and backup.is_file() and not backup.is_symlink() and pe_machine(backup) == 0x8664 \ + and not PE["pe_has_arm64ec_metadata"](backup): + restorable[name] = backup + if not restorable: + return [] + guests = PE["x64_guests"](builtins, present + list(restorable)) + restored = [] + for name, backup in sorted(restorable.items()): + if name.lower() not in guests: + continue + try: + os.replace(backup, system32 / name) + except OSError: + continue + restored.append("system32/" + name) + return restored + + def repair_foreign_system_dlls(prefix, proton, env=None): dist = Path(proton).parent / "files/lib/wine" windows = Path(prefix) / "pfx/drive_c/windows" @@ -944,6 +993,9 @@ def repair_foreign_system_dlls(prefix, proton, env=None): names = sorted(os.listdir(windows / folder)) except OSError: continue + candidates = [name for name in names if name.lower().endswith(".dll") and not (windows / folder / name).is_symlink() + and pe_machine(windows / folder / name) == 0x8664] + guests = PE["x64_guests"](builtins, candidates) if candidates and 0xA641 in machines else frozenset() for name in names: path = windows / folder / name builtin_name = builtin_names.get(name.lower()) @@ -951,7 +1003,7 @@ def repair_foreign_system_dlls(prefix, proton, env=None): if path.is_symlink() or not name.lower().endswith(".dll") or not source.is_file() or not path.is_file(): continue machine = pe_machine(path) - if machine is None or PE["machine_compatible"](path, machines, machine): + if machine is None or PE["machine_compatible"](path, machines, machine, guests): continue link = windows / folder / (name + ".bl-new") backup = windows / folder / (name + FOREIGN_SUFFIX) @@ -1301,6 +1353,14 @@ def main(): if waiting: components = win_components(prefix_path, app_id, command[0], effective_env) if prefix_path and command: + try: + restored = restore_x64_guest_dlls(prefix_path, command[0], effective_env) + except OSError as error: + restored = [] + print("droiddeck-game-env: prefix x64 DLL restore skipped (%s)" % error, file=sys.stderr) + if restored: + print("droiddeck-game-env: restored x64 system DLLs that only x64 code imports: %s" % ", ".join(restored), + file=sys.stderr) try: fixed = repair_foreign_system_dlls(prefix_path, command[0], effective_env) except OSError as error: diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-wincomponents b/tools/linuxfs/overlay/usr/local/bin/droiddeck-wincomponents index dde2d6e6be..e855f95f74 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-wincomponents +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-wincomponents @@ -479,13 +479,34 @@ def save_state(compat, state): os.replace(temp, compat / STATE) -def foreign_component(rel, path, machines): +def system_folder(rel): parts = Path(rel).parts - folder = parts[2] if len(parts) > 2 and parts[:2] == ("drive_c", "windows") else None + return parts[2] if len(parts) > 2 and parts[:2] == ("drive_c", "windows") else None + + +def foreign_component(rel, path, machines, guests=frozenset()): + folder = system_folder(rel) if not machines or folder not in PE_MACHINES or not rel.lower().endswith(".dll"): return False machine = pe_machine(path) - return machine is not None and not machine_compatible(path, machines[folder][1], machine) + return machine is not None and not machine_compatible(path, machines[folder][1], machine, guests, Path(rel).name) + + +def component_guests(pfx, proton, machines, planned): + if not machines or 0xA641 not in machines["system32"][1]: + return frozenset() + system32 = pfx / "drive_c/windows/system32" + names = {Path(rel).name for rel, src in planned + if system_folder(rel) == "system32" and rel.lower().endswith(".dll") and pe_machine(src) == 0x8664} + try: + present = list(os.scandir(system32)) + except OSError: + present = [] + names.update(entry.name for entry in present if entry.name.lower().endswith(".dll") and not entry.is_symlink() + and pe_machine(entry.path) == 0x8664) + if not names: + return frozenset() + return PE["x64_guests"](Path(proton).parent / "files/lib/wine" / machines["system32"][0], names) def pending_for(app_id, pending=PENDING): @@ -559,6 +580,8 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING saved_requires = dict(saved_requires, **{cid: loose}) inferred.add(cid) kept_overrides, kept_requires = {}, {} + planned = [entry for cid in expand(store, ids, saved_requires) for entry in (component(store, cid) or ([], [], [], []))[1]] + guests = component_guests(pfx, proton, machines, planned) for cid in expand(store, ids, saved_requires): found = component(store, cid) if found is None: @@ -585,7 +608,7 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING kept_requires[cid] = list(requires) values += [(cid, value) for value in registry] for rel, src in files: - foreign = foreign_component(rel, src, machines) + foreign = foreign_component(rel, src, machines, guests) if foreign: skipped.add(Path(rel).stem.lower()) changed = False @@ -606,7 +629,7 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING path = existing(pfx / rel) saved = compat / BACKUP / rel if saved.is_file(): - if foreign_component(rel, saved, machines): + if foreign_component(rel, saved, machines, guests): if path is not None and not path.is_symlink(): path.unlink() continue diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-wine-pe b/tools/linuxfs/overlay/usr/local/bin/droiddeck-wine-pe index 65c3446a2a..8e4d7e5624 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-wine-pe +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-wine-pe @@ -1,4 +1,5 @@ #!/usr/bin/python3 +import os import re from pathlib import Path @@ -82,9 +83,119 @@ VC_RUNTIME = re.compile(r"(msvc[pr]\d.*|vcruntime\d.*|vcomp\d*|vcamp\d.*|vccorli re.IGNORECASE) -def machine_compatible(path, machines, machine=None): +def pe_imports(path): + try: + with open(path, "rb") as image: + head = image.read(64) + if head[:2] != b"MZ" or len(head) < 64: + return [] + pe_offset = int.from_bytes(head[60:64], "little") + image.seek(pe_offset) + if image.read(4) != b"PE\0\0": + return [] + coff = image.read(20) + if len(coff) != 20: + return [] + section_count = int.from_bytes(coff[2:4], "little") + optional_size = int.from_bytes(coff[16:18], "little") + if section_count > 96: + return [] + optional = image.read(optional_size) + if len(optional) != optional_size or len(optional) < 2: + return [] + magic = int.from_bytes(optional[:2], "little") + directories = {0x20B: 112, 0x10B: 96}.get(magic) + if directories is None: + return [] + sections = [] + for _ in range(section_count): + section = image.read(40) + if len(section) != 40: + return [] + sections.append((int.from_bytes(section[12:16], "little"), + max(int.from_bytes(section[8:12], "little"), int.from_bytes(section[16:20], "little")), + int.from_bytes(section[20:24], "little"))) + + def offset(rva): + for start, size, raw in sections: + if start <= rva < start + size: + return raw + rva - start + return None + + def directory(index): + at = directories + index * 8 + if len(optional) < at + 8: + return 0 + return int.from_bytes(optional[at:at + 4], "little") + + def name_at(rva): + at = offset(rva) + if at is None: + return None + image.seek(at) + raw = image.read(256).split(b"\0", 1)[0] + return raw.decode("ascii", "replace").lower() or None + + names = [] + for index, size, field in ((1, 20, 12), (13, 32, 4)): + at = offset(directory(index)) if directory(index) else None + while at is not None and len(names) < 512: + image.seek(at) + entry = image.read(size) + if len(entry) != size or not any(entry): + break + name = name_at(int.from_bytes(entry[field:field + 4], "little")) + if name: + names.append(name) + at += size + return names + except (OSError, OverflowError, ValueError): + return [] + + +IMPORTERS = {} + + +def builtin_importers(builtins): + try: + stamp = os.stat(builtins).st_mtime_ns + except OSError: + return {} + cached = IMPORTERS.get(str(builtins)) + if cached and cached[0] == stamp: + return cached[1] + importers = {} + try: + entries = list(os.scandir(builtins)) + except OSError: + return {} + for entry in entries: + if entry.name.lower().endswith(".dll"): + for name in pe_imports(entry.path): + importers.setdefault(name, set()).add(entry.name.lower()) + IMPORTERS[str(builtins)] = (stamp, importers) + return importers + + +def x64_guests(builtins, names): + importers = builtin_importers(builtins) + guests = {name.lower() for name in names} + changed = True + while changed: + changed = False + for name in sorted(guests): + if not importers.get(name, set()) <= guests: + guests.discard(name) + changed = True + return guests + + +def machine_compatible(path, machines, machine=None, guests=frozenset(), name=None): machine = pe_machine(path) if machine is None else machine - if machine == 0x8664 and 0xA641 in machines and VC_RUNTIME.fullmatch(Path(path).name): + name = name or Path(path).name + if machine == 0x8664 and 0xA641 in machines and VC_RUNTIME.fullmatch(name): + return True + if machine == 0x8664 and 0xA641 in machines and name.lower() in guests and not pe_has_arm64ec_metadata(path): return True if machine == 0x8664 and pe_has_arm64ec_metadata(path): return 0xA641 in machines diff --git a/tools/tests/test_game_environment.py b/tools/tests/test_game_environment.py index 768ee0660d..7d6b69dcbf 100644 --- a/tools/tests/test_game_environment.py +++ b/tools/tests/test_game_environment.py @@ -2806,6 +2806,38 @@ def arm64ec_pe_image(): return bytes(image) +def pe_image_importing(machine, imports=(), delayed=()): + image = bytearray(0x600) + image[:2] = b"MZ" + image[60:64] = (64).to_bytes(4, "little") + image[64:68] = b"PE\0\0" + coff = 68 + image[coff:coff + 2] = machine.to_bytes(2, "little") + image[coff + 2:coff + 4] = (1).to_bytes(2, "little") + image[coff + 16:coff + 18] = (240).to_bytes(2, "little") + optional = coff + 20 + image[optional:optional + 2] = (0x20B).to_bytes(2, "little") + image[optional + 108:optional + 112] = (16).to_bytes(4, "little") + section = optional + 240 + image[section + 8:section + 12] = (0x400).to_bytes(4, "little") + image[section + 12:section + 16] = (0x1000).to_bytes(4, "little") + image[section + 16:section + 20] = (0x400).to_bytes(4, "little") + image[section + 20:section + 24] = (0x200).to_bytes(4, "little") + names = 0x1200 + for index, size, field, entries in ((1, 20, 12, imports), (13, 32, 4, delayed)): + if not entries: + continue + table = 0x1000 if index == 1 else 0x1100 + image[optional + 112 + index * 8:optional + 116 + index * 8] = table.to_bytes(4, "little") + for number, name in enumerate(entries): + entry = 0x200 + table - 0x1000 + number * size + image[entry + field:entry + field + 4] = names.to_bytes(4, "little") + raw = name.encode() + b"\0" + image[0x200 + names - 0x1000:0x200 + names - 0x1000 + len(raw)] = raw + names += len(raw) + return bytes(image) + + class ForeignSystemDllTest(unittest.TestCase): def prefix(self, tmp, arm=True): proton = Path(tmp) / "Proton" @@ -2818,6 +2850,8 @@ class ForeignSystemDllTest(unittest.TestCase): (dist / libdir).mkdir(parents=True) for name in ("ucrtbase.dll", "rpcrt4.dll"): (dist / libdir / name).write_bytes(pe_image(machine)) + (dist / libdir / "kernel32.dll").write_bytes( + pe_image_importing(machine, ("ucrtbase.dll", "rpcrt4.dll"), ("msvcp_win.dll",))) windows = Path(tmp) / "compat/pfx/drive_c/windows" for folder in ("system32", "syswow64"): (windows / folder).mkdir(parents=True) @@ -2868,6 +2902,87 @@ class ForeignSystemDllTest(unittest.TestCase): self.assertFalse((windows / "system32/msvcp140.dll").is_symlink()) self.assertFalse((windows / "system32/VCRUNTIME140.dll").is_symlink()) + def test_x64_dlls_only_imported_by_each_other_stay_in_arm64_system32(self): + with tempfile.TemporaryDirectory() as tmp: + proton, compat, windows = self.prefix(tmp) + builtins = proton.parent / "files/lib/wine/aarch64-windows" + builtins.joinpath("d3dcompiler_43.dll").write_bytes(pe_image(0xAA64)) + builtins.joinpath("d3dx9_43.dll").write_bytes(pe_image_importing(0xAA64, ("d3dcompiler_43.dll",))) + for name in ("d3dcompiler_43.dll", "D3DX9_43.dll", "ucrtbase.dll"): + (windows / "system32" / name).write_bytes(pe_image(0x8664)) + self.assertEqual(["system32/ucrtbase.dll (machine 0x8664)"], self.run_repair(compat, proton)) + self.assertEqual([], self.run_repair(compat, proton)) + for name in ("d3dcompiler_43.dll", "D3DX9_43.dll"): + self.assertFalse((windows / "system32" / name).is_symlink()) + self.assertEqual(0x8664, MODULE["pe_machine"](windows / "system32" / name)) + + def test_x64_dlls_replaced_by_an_earlier_build_are_restored_and_core_dlls_are_not(self): + with tempfile.TemporaryDirectory() as tmp: + proton, compat, windows = self.prefix(tmp) + builtins = proton.parent / "files/lib/wine/aarch64-windows" + builtins.joinpath("d3dcompiler_43.dll").write_bytes(pe_image(0xAA64)) + builtins.joinpath("d3dx9_43.dll").write_bytes(pe_image_importing(0xAA64, ("d3dcompiler_43.dll",))) + for name in ("d3dcompiler_43.dll", "d3dx9_43.dll", "ucrtbase.dll"): + (windows / "system32" / name).write_bytes(pe_image(0x8664)) + for name in ("d3dcompiler_43.dll", "d3dx9_43.dll", "ucrtbase.dll"): + path = windows / "system32" / name + os.replace(path, path.with_name(name + ".foreign-arch")) + os.symlink(os.path.relpath(builtins / name, path.parent), path) + restored = MODULE["restore_x64_guest_dlls"](str(compat), str(proton)) + self.assertEqual(["system32/d3dcompiler_43.dll", "system32/d3dx9_43.dll"], restored) + for name in ("d3dcompiler_43.dll", "d3dx9_43.dll"): + self.assertFalse((windows / "system32" / name).is_symlink()) + self.assertEqual(0x8664, MODULE["pe_machine"](windows / "system32" / name)) + self.assertTrue((windows / "system32/ucrtbase.dll").is_symlink()) + self.assertEqual([], self.run_repair(compat, proton)) + self.assertEqual([], MODULE["restore_x64_guest_dlls"](str(compat), str(proton))) + + def test_restore_leaves_x64_proton_prefixes_and_user_files_alone(self): + with tempfile.TemporaryDirectory() as tmp: + proton, compat, windows = self.prefix(tmp, arm=False) + (windows / "system32/d3dx9_43.dll").write_bytes(pe_image(0x8664)) + (windows / "system32/d3dx9_43.dll.foreign-arch").write_bytes(pe_image(0xAA64)) + self.assertEqual([], MODULE["restore_x64_guest_dlls"](str(compat), str(proton))) + self.assertEqual(0x8664, MODULE["pe_machine"](windows / "system32/d3dx9_43.dll")) + with tempfile.TemporaryDirectory() as tmp: + proton, compat, windows = self.prefix(tmp) + mine = Path(tmp) / "mine.dll" + mine.write_bytes(pe_image(0xAA64)) + os.symlink(mine, windows / "system32/userlib.dll") + (windows / "system32/userlib.dll.foreign-arch").write_bytes(pe_image(0x8664)) + self.assertEqual([], MODULE["restore_x64_guest_dlls"](str(compat), str(proton))) + self.assertEqual(mine, Path(os.readlink(windows / "system32/userlib.dll"))) + + def test_x64_dll_imported_by_a_builtin_that_stays_is_replaced(self): + with tempfile.TemporaryDirectory() as tmp: + proton, compat, windows = self.prefix(tmp) + builtins = proton.parent / "files/lib/wine/aarch64-windows" + builtins.joinpath("d3dcompiler_43.dll").write_bytes(pe_image(0xAA64)) + builtins.joinpath("d3dx9_43.dll").write_bytes(pe_image_importing(0xAA64, ("d3dcompiler_43.dll",))) + (windows / "system32/d3dcompiler_43.dll").write_bytes(pe_image(0x8664)) + (windows / "system32/d3dx9_43.dll").write_bytes(pe_image(0xAA64)) + self.assertEqual(["system32/d3dcompiler_43.dll (machine 0x8664)"], self.run_repair(compat, proton)) + self.assertEqual(0xAA64, MODULE["pe_machine"](windows / "system32/d3dcompiler_43.dll")) + + def test_x64_proton_prefix_ignores_builtin_imports(self): + with tempfile.TemporaryDirectory() as tmp: + proton, compat, windows = self.prefix(tmp, arm=False) + builtins = proton.parent / "files/lib/wine/x86_64-windows" + builtins.mkdir(parents=True) + builtins.joinpath("d3dx9_43.dll").write_bytes(pe_image(0x8664)) + (windows / "system32/d3dx9_43.dll").write_bytes(pe_image(0xAA64)) + self.assertEqual(["system32/d3dx9_43.dll (machine 0xaa64)"], self.run_repair(compat, proton)) + + def test_import_tables_and_delay_imports_are_read(self): + with tempfile.TemporaryDirectory() as tmp: + dll = Path(tmp) / "a.dll" + dll.write_bytes(pe_image_importing(0xAA64, ("UCRTBASE.dll", "ntdll.dll"), ("msvcp_win.dll",))) + self.assertEqual(["ucrtbase.dll", "ntdll.dll", "msvcp_win.dll"], MODULE["PE"]["pe_imports"](dll)) + dll.write_bytes(pe_image(0x8664)) + self.assertEqual([], MODULE["PE"]["pe_imports"](dll)) + dll.write_bytes(b"MZ") + self.assertEqual([], MODULE["PE"]["pe_imports"](dll)) + def test_final_arm64ec_image_is_not_repaired_as_a_foreign_x64_dll(self): with tempfile.TemporaryDirectory() as tmp: proton, compat, windows = self.prefix(tmp) diff --git a/tools/tests/test_wincomponents.py b/tools/tests/test_wincomponents.py index 7423fb2bbf..d8f4573001 100644 --- a/tools/tests/test_wincomponents.py +++ b/tools/tests/test_wincomponents.py @@ -9,6 +9,7 @@ from unittest import mock BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" MODULE = runpy.run_path(str(BIN / "droiddeck-wincomponents")) GAME_ENV = runpy.run_path(str(BIN / "droiddeck-game-env")) +pe_image_importing = runpy.run_path(str(Path(__file__).with_name("test_game_environment.py")))["pe_image_importing"] class WinComponentsTest(unittest.TestCase): @@ -41,6 +42,10 @@ class WinComponentsTest(unittest.TestCase): def proton(self, arm=True): root = Path(self.tmp.name) / ("arm-proton" if arm else "x64-proton") (root / "files/lib/wine" / ("aarch64-unix" if arm else "x86_64-unix")).mkdir(parents=True) + builtins = root / "files/lib/wine" / ("aarch64-windows" if arm else "x86_64-windows") + builtins.mkdir(parents=True) + builtins.joinpath("kernel32.dll").write_bytes(pe_image_importing(0xAA64 if arm else 0x8664, ("ucrtbase.dll",))) + builtins.joinpath("d3dx9_43.dll").write_bytes(pe_image_importing(0xAA64 if arm else 0x8664, ("d3dcompiler_43.dll",))) return root / "proton" def pe_image(self, machine): @@ -104,6 +109,32 @@ class WinComponentsTest(unittest.TestCase): self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/msvcp140.dll"), 0x8664) self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/vcruntime140_1.dll"), 0x8664) + def test_x64_d3dx9_and_its_compiler_are_placed_in_arm64_system32(self): + proton = self.proton() + self.component("d3dx9", ["d3dx9_43"], { + "system32/d3dx9_43.dll": self.pe_image(0x8664), + "syswow64/d3dx9_43.dll": self.pe_image(0x14C), + }) + self.component("d3dcompiler", ["d3dcompiler_43"], {"system32/d3dcompiler_43.dll": self.pe_image(0x8664)}) + self.pick("d3dx9", "d3dcompiler") + names, _ = self.apply(proton) + self.assertEqual(names, ["d3dx9_43", "d3dcompiler_43"]) + self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dx9_43.dll"), 0x8664) + self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dcompiler_43.dll"), 0x8664) + names, _ = self.apply(proton) + self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dcompiler_43.dll"), 0x8664) + + def test_x64_compiler_alone_is_skipped_while_the_builtin_d3dx9_imports_it(self): + proton = self.proton() + self.component("d3dcompiler", ["d3dcompiler_43"], { + "system32/d3dcompiler_43.dll": self.pe_image(0x8664), + "syswow64/d3dcompiler_43.dll": self.pe_image(0x14C), + }) + self.pick("d3dcompiler") + names, _ = self.apply(proton) + self.assertEqual(names, ["d3dcompiler_43"]) + self.assertFalse((self.pfx / "system32/d3dcompiler_43.dll").exists()) + def test_compatible_copy_keeps_override_when_other_architecture_copy_is_skipped(self): proton = self.proton() self.component("vc", ["ucrtbase"], {