diff --git a/win/tools/autopatch/README.md b/win/tools/autopatch/README.md index 5ee2dde..051a506 100644 --- a/win/tools/autopatch/README.md +++ b/win/tools/autopatch/README.md @@ -44,9 +44,9 @@ optional arguments: -P PATCH_NAME [PATCH_NAME ...], --patch-name PATCH_NAME [PATCH_NAME ...] relative filename(s) of generated patch(es) (default: ['nvencodeapi64.1337', 'nvencodeapi.1337']) -S SEARCH [SEARCH ...], --search SEARCH [SEARCH ...] - representation of search pattern(s) binary string (default: ['8BF085C0750549892FEB', '89450885C075048937EB']) + representation of search pattern(s) binary string (default: auto-detect from the target library). Separate fallback alternatives with commas; alternatives are tried in order and the first one found is used -R REPLACEMENT [REPLACEMENT ...], --replacement REPLACEMENT [REPLACEMENT ...] - representation of replacement(s) binary string (default: ['33C08BF0750549892FEB', '33C089450875048937EB']) + representation of replacement(s) binary string (default: auto-detect from the target library). Fallback alternatives must match search order -o, --stdout output into stdout (default: False) -D, --direct supply patched library directly instead of installer file (default: False) ``` diff --git a/win/tools/autopatch/autopatch.py b/win/tools/autopatch/autopatch.py index d594bce..738d65c 100755 --- a/win/tools/autopatch/autopatch.py +++ b/win/tools/autopatch/autopatch.py @@ -18,6 +18,54 @@ LINE_FORMAT = CRLF + b"%016X:%02X->%02X" OFFSET_ADJUSTMENT = 0xC00 # shift specific to x64dbg .1337 format +# NVENC libraries ship exactly one of a handful of bytecode generations, +# depending on the driver family. Historically the newest generation was +# hardcoded as the default and bumped by hand whenever a new driver changed the +# code, which silently broke every older driver. Listing the known generations +# here (newest first) and auto-selecting the one that matches lets a single +# build of this tool handle every driver without editing the defaults. +# Each entry is a (search, replacement) pair of equal-length hex strings; both +# the 64-bit and 32-bit libraries follow the same table because their patterns +# are disjoint. Values are taken from this file's own history. +BYTECODE_GENERATIONS = ( + # 591.xx and newer + ("8BF04533FF85C0", "33C08BF04533FF"), + ("8985ECFBFFFF85C08B85DCFBFFFF7504", + "31C08985ECFBFFFF8B85DCFBFFFF7504"), + # ~2022-06 variant (x64) + ("8BF085C0750549892FEB", "33C08BF0750549892FEB"), + # ~2022-02 era (x64) + ("8BE885C0750548893EEB", "33C08BE8750548893EEB"), + # ~2022 era (x86) + ("89450885C08B450C75048938EB", "33C08945088B450C75048938EB"), + # ~2022 (x86) shorter fallback: a prefix of the entry above, used only when + # the full 13-byte pattern does not match exactly once. Kept last among the + # ~2022 entries so the longer, more specific pattern is always preferred. + ("89450885C08B450C7504", "33C08945088B450C7504"), + # ~2019-11 (x86) + ("89450885C075048937EB", "33C089450875048937EB"), + # ~2019-10 + ("FF909800000084C075", "FF90980000000C0175"), + ("8B404CFFD084C075", "8B404CFFD00C0175"), + # Legacy x86 (nvencodeapi.dll) pair, previously only available through the + # explicit -S/-R arguments of legacy.sh (commit 353019c). + ("8BD885DB75048937EB", "33C08BD875048937EB"), +) + + +def select_bytecode(data): + """Return the ``(search, replacement)`` pair matching ``data`` exactly once. + + Returns ``None`` when no known generation matches unambiguously, so the + caller can report a clear error instead of guessing. + """ + for search_hex, replacement_hex in BYTECODE_GENERATIONS: + search = unhexlify(search_hex) + if data.count(search) == 1: + return search, unhexlify(replacement_hex) + return None + + def parse_args(): parser = argparse.ArgumentParser( description="Generates .1337 patch for Nvidia drivers for Windows", @@ -53,20 +101,17 @@ def parse_args(): help="relative filename(s) of generated patch(es)") parser.add_argument("-S", "--search", nargs="+", - default=[ - "8BF04533FF85C0,8BF085C0750549892FEB", - "8985ECFBFFFF85C08B85DCFBFFFF7504,89450885C08B450C7504", - ], - help="representation of search pattern(s) binary string. " - "Separate fallback alternatives with commas; " - "alternatives are tried in order and the first one found is used") + default=None, + help="representation of search pattern(s) binary " + "string (default: auto-detect from the target " + "library). Separate fallback alternatives with " + "commas; alternatives are tried in order and the " + "first one found is used") parser.add_argument("-R", "--replacement", nargs="+", - default=[ - "33C08BF04533FF,33C08BF0750549892FEB", - "31C08985ECFBFFFF8B85DCFBFFFF7504,33C08945088B450C7504", - ], - help="representation of replacement(s) binary string. " + default=None, + help="representation of replacement(s) binary string " + "(default: auto-detect from the target library). " "Fallback alternatives must match search order") parser.add_argument("-o", "--stdout", action="store_true", @@ -97,6 +142,28 @@ class UnknownPlatformException(Exception): class InstallerNotFoundException(Exception): pass + +def _alternate_target_names(arch_tgt): + """Return ``arch_tgt`` plus its ``.dll``/``.dl_`` spelling variant. + + NVENC libraries are stored either raw (``nvencodeapi64.dll``) or + LZMA-compressed (``nvencodeapi64.dl_``) depending on the driver + generation, and the caller may request either spelling. Both are tried so + that a target present under the other name is still picked up. + """ + names = [arch_tgt] + basename = os.path.basename(arch_tgt) + if basename.endswith(".dll"): + alternate = basename[:-len(".dll")] + ".dl_" + elif basename.endswith(".dl_"): + alternate = basename[:-len(".dl_")] + ".dll" + else: + alternate = None + if alternate is not None: + names.append(os.path.join(os.path.dirname(arch_tgt), alternate)) + return names + + class ExtractedTarget: name = None @@ -107,20 +174,29 @@ class ExtractedTarget: self._arch_tgt = arch_tgt def __enter__(self): - ret = subprocess.call([self._sevenzip, - "e", - "-o" + self._dst_dir, - self._archive, - self._arch_tgt], - stdout=sys.stderr) - if ret != 0: - raise ExtractException("Subprocess returned non-zero exit code.") - name = os.path.join(self._dst_dir, os.path.basename(self._arch_tgt)) - self.name = name - return name + # 7z exits 0 with "No files to process" when the requested member is + # absent, so a successful return code is not enough: verify a file + # actually appeared and fall back to the .dll/.dl_ spelling variant. + for arch_tgt in _alternate_target_names(self._arch_tgt): + ret = subprocess.call([self._sevenzip, + "e", + "-o" + self._dst_dir, + self._archive, + arch_tgt], + stdout=sys.stderr) + if ret != 0: + raise ExtractException( + "Subprocess returned non-zero exit code.") + name = os.path.join(self._dst_dir, os.path.basename(arch_tgt)) + if os.path.isfile(name): + self.name = name + return name + raise ExtractException( + "Target %r not found in archive %r (also tried the .dll/.dl_ " + "variant)." % (self._arch_tgt, self._archive)) def __exit__(self, exc_type, exc_value, traceback): - if self.name is not None: + if self.name is not None and os.path.isfile(self.name): os.remove(self.name) @@ -174,18 +250,29 @@ def make_patch(archive, *, f = fo.read() else: f = expand(tgt, sevenzip=sevenzip) - selected = None - for pattern, patched_pattern in zip(search, replacement): - offset = f.find(pattern) - if offset == -1: - continue - if f[offset + len(pattern):].find(pattern) != -1: - raise MultipleOccurencesException("Multiple occurences of pattern found!") - selected = (offset, pattern, patched_pattern) - break - if selected is None: - raise PatternNotFoundException("Pattern not found.") - offset, matched_search, matched_replacement = selected + if search is None: + # Auto-detect: the first known generation that matches exactly once. + selected = select_bytecode(f) + if selected is None: + raise PatternNotFoundException( + "No known NVENC bytecode generation matched exactly once in " + "%r; pass -S/-R explicitly." % (arch_tgt,)) + matched_search, matched_replacement = selected + offset = f.find(matched_search) + else: + # Explicit alternatives: the first one found is used. + selected = None + for pattern, patched_pattern in zip(search, replacement): + found = f.find(pattern) + if found == -1: + continue + if f[found + len(pattern):].find(pattern) != -1: + raise MultipleOccurencesException("Multiple occurences of pattern found!") + selected = (found, pattern, patched_pattern) + break + if selected is None: + raise PatternNotFoundException("Pattern not found.") + offset, matched_search, matched_replacement = selected del f print("Pattern found @ %016X" % (offset,), file=sys.stderr) @@ -217,11 +304,16 @@ def format_patch(diff, filename): def patch_flow(installer_file, search, replacement, target, target_name, patch_name, *, tempdir, direct=False, stdout=False, sevenzip="7z"): - search = parse_binary_alternatives(search) - replacement = parse_binary_alternatives(replacement) - assert len(search) == len(replacement), "count of search and replacement alternatives is not equal" - for search_item, replacement_item in zip(search, replacement): - assert len(search_item) == len(replacement_item), "len() of search and replacement is not equal" + if (search is None) != (replacement is None): + raise ValueError( + "Both -S/--search and -R/--replacement must be given together, " + "or neither (to auto-detect).") + if search is not None: + search = parse_binary_alternatives(search) + replacement = parse_binary_alternatives(replacement) + assert len(search) == len(replacement), "count of search and replacement alternatives is not equal" + for search_item, replacement_item in zip(search, replacement): + assert len(search_item) == len(replacement_item), "len() of search and replacement is not equal" # Check if installer file exists or try to download @@ -305,11 +397,24 @@ def patch_flow(installer_file, search, replacement, target, target_name, patch_n def main(): args = parse_args() + if (args.search is None) != (args.replacement is None): + raise ValueError( + "Both -S/--search and -R/--replacement must be given together, " + "or neither (to auto-detect).") + if args.search is None: + # No explicit patterns: auto-detect per target library. + count = len(args.installer_file) if args.direct else len(args.target) + search = [None] * count + replacement = [None] * count + else: + search = args.search + replacement = args.replacement + if args.direct: - combinations = zip(args.installer_file, args.search, args.replacement, + combinations = zip(args.installer_file, search, replacement, args.target, args.target_name, args.patch_name) else: - base_params = zip(args.search, args.replacement, args.target, args.target_name, args.patch_name) + base_params = zip(search, replacement, args.target, args.target_name, args.patch_name) combinations = ((l,) + r for l, r in itertools.product(args.installer_file, base_params)) with tempfile.TemporaryDirectory() as tempdir: diff --git a/win/tools/autopatch/test_autopatch.py b/win/tools/autopatch/test_autopatch.py new file mode 100644 index 0000000..7737faf --- /dev/null +++ b/win/tools/autopatch/test_autopatch.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 + +"""Regression tests for autopatch.py target extraction. + +The NVENC libraries in Nvidia installer archives are stored under different +names depending on the driver generation: + + * older drivers (e.g. 496.13): ``Display.Driver/nvencodeapi64.dl_`` + (LZMA-compressed, extension ``.dl_``) + * newer drivers: ``Display.Driver/nvencodeapi64.dll`` + (stored raw, extension ``.dll``) + +autopatch.py defaults to the ``.dll`` spelling, so it must fall back to the +``.dl_`` spelling when the archive only contains the compressed variant. +Before the fix, a missing target silently produced nothing (7z exits 0 with +"No files to process"), and the subsequent ``open()``/``os.remove()`` raised a +confusing ``FileNotFoundError`` that masked the real problem. + +These tests build a throw-away archive with 7z so they do not depend on a +multi-hundred-megabyte driver download. +""" + +import io +import lzma +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) + +import autopatch # noqa: E402 (path is prepared above) + +SEVENZIP = os.environ.get("SEVENZIP", "7z") + +SEARCH = b"\x8b\xf0\x45\x33\xff\x85\xc0" +REPLACEMENT = b"\x33\xc0\x8b\xf0\x45\x33\xff" + + +def _payload(): + # Unique context around the pattern so `find` is unambiguous. + return b"NVENC-HEADER" + SEARCH + b"NVENC-TAIL" + b"\x00" * 16 + + +def _make_archive(tmpdir, member, data, *, compress): + """Create a 7z archive containing ``member`` (forward-slash path).""" + tree = os.path.join(tmpdir, "tree") + abs_member = os.path.join(tree, *member.split("/")) + os.makedirs(os.path.dirname(abs_member), exist_ok=True) + with open(abs_member, "wb") as fo: + fo.write(lzma.compress(data) if compress else data) + + archive = os.path.join(tmpdir, "archive.7z") + root = os.path.join(tree, member.split("/")[0]) + subprocess.check_call( + [SEVENZIP, "a", "-t7z", archive, root], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + return archive + + +@unittest.skipUnless(shutil.which(SEVENZIP), "7z is not installed") +class MakePatchTargetResolutionTest(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self._tmp, ignore_errors=True) + + def _run(self, member, *, compress): + archive = _make_archive(self._tmp, member, _payload(), + compress=compress) + # mirror the default --target spelling (.dll) + return autopatch.make_patch( + archive, + arch_tgt="Display.Driver/nvencodeapi64.dll", + search=[SEARCH], + replacement=[REPLACEMENT], + tmpdir=self._tmp, + sevenzip=SEVENZIP, + ) + + def test_raw_dll_target_is_found(self): + diff = self._run("Display.Driver/nvencodeapi64.dll", compress=False) + self.assertTrue(diff, "expected a non-empty diff for a raw .dll member") + + def test_compressed_dl_target_is_found(self): + # 496.13-style archive: only the compressed .dl_ member exists. + diff = self._run("Display.Driver/nvencodeapi64.dl_", compress=True) + self.assertTrue( + diff, + "expected autopatch to fall back to the .dl_ member and find the " + "pattern", + ) + + def test_missing_target_raises_extract_exception(self): + # Neither spelling is present: must raise a clear error, not a bare + # FileNotFoundError from open()/os.remove(). + archive = _make_archive(self._tmp, "Display.Driver/somethingelse.dll", + _payload(), compress=False) + with self.assertRaises(autopatch.ExtractException): + autopatch.make_patch( + archive, + arch_tgt="Display.Driver/nvencodeapi64.dll", + search=[SEARCH], + replacement=[REPLACEMENT], + tmpdir=self._tmp, + sevenzip=SEVENZIP, + ) + + +# --------------------------------------------------------------------------- +# Bytecode generation auto-detection, explicit -S/-R alternatives and argument +# validation. These use direct (-D) mode so they need no 7z and no installer. +# --------------------------------------------------------------------------- + +NEUTRAL = b"\x90" * 8 # padding that matches none of the known patterns + +PRIMARY_S = "8BF04533FF85C0" +PRIMARY_R = "33C08BF04533FF" +FALLBACK_S = "8BF085C0750549892FEB" +FALLBACK_R = "33C08BF0750549892FEB" + + +def _hex(value): + return bytes.fromhex(value) + + +def _expected_diff(offset, search, replacement): + return [(offset + i, a, b) for i, (a, b) in enumerate(zip(search, replacement)) if a != b] + + +class BytecodeAutoDetectTest(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self._tmp, ignore_errors=True) + + def _direct(self, data, search, replacement): + path = os.path.join(self._tmp, "lib.bin") + with open(path, "wb") as fo: + fo.write(data) + return autopatch.make_patch( + path, + arch_tgt="unused.dll", + search=search, + replacement=replacement, + tmpdir=self._tmp, + direct=True, + ) + + def test_auto_detect_picks_each_generation(self): + # Each table entry, alone in the binary, must be selected and must + # produce exactly the same diff as passing that pattern explicitly. + for search_hex, replacement_hex in autopatch.BYTECODE_GENERATIONS: + with self.subTest(generation=search_hex): + search = _hex(search_hex) + replacement = _hex(replacement_hex) + data = NEUTRAL + search + NEUTRAL + self.assertEqual(autopatch.select_bytecode(data), (search, replacement)) + auto = self._direct(data, None, None) + explicit = self._direct(data, [search], [replacement]) + self.assertEqual(auto, explicit) + self.assertEqual(auto, _expected_diff(len(NEUTRAL), search, replacement)) + + def test_auto_detect_fails_when_no_generation_matches(self): + self.assertIsNone(autopatch.select_bytecode(NEUTRAL)) + with self.assertRaises(autopatch.PatternNotFoundException): + self._direct(NEUTRAL, None, None) + + def test_explicit_comma_alternatives_use_the_one_present(self): + search = autopatch.parse_binary_alternatives(PRIMARY_S + "," + FALLBACK_S) + replacement = autopatch.parse_binary_alternatives(PRIMARY_R + "," + FALLBACK_R) + data = NEUTRAL + _hex(FALLBACK_S) + NEUTRAL + self.assertEqual( + self._direct(data, search, replacement), + _expected_diff(len(NEUTRAL), _hex(FALLBACK_S), _hex(FALLBACK_R)), + ) + + def test_explicit_first_listed_alternative_wins(self): + # Both alternatives occur once; the first one *in list order* is used, + # regardless of where it sits in the binary. + data = _hex(FALLBACK_S) + NEUTRAL + _hex(PRIMARY_S) + primary = (_hex(PRIMARY_S), _hex(PRIMARY_R)) + fallback = (_hex(FALLBACK_S), _hex(FALLBACK_R)) + + diff = self._direct(data, [primary[0], fallback[0]], [primary[1], fallback[1]]) + self.assertEqual(diff, _expected_diff(len(FALLBACK_S) // 2 + len(NEUTRAL), *primary)) + + diff = self._direct(data, [fallback[0], primary[0]], [fallback[1], primary[1]]) + self.assertEqual(diff, _expected_diff(0, *fallback)) + + def test_duplicate_fallback_does_not_break_unique_primary(self): + # Regression for #1074: a fallback that occurs twice must not cause a + # failure when the primary occurs exactly once. + search = [_hex(PRIMARY_S), _hex(FALLBACK_S)] + replacement = [_hex(PRIMARY_R), _hex(FALLBACK_R)] + data = _hex(PRIMARY_S) + NEUTRAL + _hex(FALLBACK_S) + NEUTRAL + _hex(FALLBACK_S) + self.assertEqual( + self._direct(data, search, replacement), + _expected_diff(0, _hex(PRIMARY_S), _hex(PRIMARY_R)), + ) + + def test_duplicate_selected_pattern_is_rejected(self): + data = _hex(PRIMARY_S) + NEUTRAL + _hex(PRIMARY_S) + with self.assertRaises(autopatch.MultipleOccurencesException): + self._direct(data, [_hex(PRIMARY_S)], [_hex(PRIMARY_R)]) + + +class ArgumentValidationTest(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self._tmp, ignore_errors=True) + + def test_empty_alternative_is_rejected(self): + for value in ["", "8BF0,", ",8BF0", "8BF0,,33C0"]: + with self.subTest(value=value): + with self.assertRaises(ValueError): + autopatch.parse_binary_alternatives(value) + + def test_defaults_are_none_when_omitted(self): + with mock.patch.object(sys, "argv", ["autopatch.py", "installer.exe"]): + args = autopatch.parse_args() + self.assertIsNone(args.search) + self.assertIsNone(args.replacement) + + def test_search_without_replacement_is_rejected(self): + argv = ["autopatch.py", "installer.exe", "-S", PRIMARY_S] + with mock.patch.object(sys, "argv", argv): + with self.assertRaises(ValueError): + autopatch.main() + + def test_replacement_without_search_is_rejected(self): + argv = ["autopatch.py", "installer.exe", "-R", PRIMARY_R] + with mock.patch.object(sys, "argv", argv): + with self.assertRaises(ValueError): + autopatch.main() + + def test_patch_flow_rejects_search_without_replacement(self): + with self.assertRaises(ValueError): + autopatch.patch_flow("installer.exe", PRIMARY_S, None, "t.dll", "t.dll", + "t.1337", tempdir=self._tmp, direct=True) + + +if __name__ == "__main__": + unittest.main()