diff options
| -rwxr-xr-x | frame-steamos/patch-frame | 217 | ||||
| -rw-r--r-- | frame-steamos/patches.toml | 118 | ||||
| -rw-r--r-- | frame-steamos/recovery-watchdog.c | 97 | ||||
| -rw-r--r-- | frame-steamos/template.py | 138 | ||||
| -rw-r--r-- | src/steamvr_patches/__init__.py | 18 | ||||
| -rw-r--r-- | src/steamvr_patches/architecture.py | 92 | ||||
| -rw-r--r-- | src/steamvr_patches/elf.py | 75 |
7 files changed, 513 insertions, 242 deletions
diff --git a/frame-steamos/patch-frame b/frame-steamos/patch-frame deleted file mode 100755 index 7f547ad..0000000 --- a/frame-steamos/patch-frame +++ /dev/null @@ -1,217 +0,0 @@ -#!/usr/bin/python3 -I -# SPDX-FileCopyrightText: 2026 Tomasz Kramkowski <tomasz@kramkow.ski> -# SPDX-License-Identifier: CC0-1.0 - -"""A minimally intrusive Frame SteamOS patcher""" - -import argparse -import hashlib -import json -import os -import subprocess -import sys -from dataclasses import dataclass -from pathlib import Path - -MARKER = "x-valve-please-fix" -RUNTIME = Path(os.environ.get("RUNTIME_DIRECTORY", "/run/patcher")) - - -@dataclass(frozen=True) -class Edit: - offset: int - replacement: bytes - - -@dataclass(frozen=True) -class Patch: - original_hash: bytes - edits: tuple[Edit, ...] - - def apply_to(self, data: bytes) -> bytearray: - result = bytearray(data) - for edit in self.edits: - end = edit.offset + len(edit.replacement) - if edit.offset < 0 or end > len(result): - raise ValueError(f"Patch outside file at {edit.offset:#x}") - result[edit.offset : end] = edit.replacement - return result - - -def patch(original_hash: str, edits: tuple[tuple[int, str], ...]) -> Patch: - return Patch( - bytes.fromhex(original_hash), - tuple( - Edit(offset, bytes.fromhex(replacement)) for offset, replacement in edits - ), - ) - - -PATCHES = { - "/opt/steamvr/tools/vrlink/bin/linuxarm64/vrlink": patch( - original_hash="d1d438f00ffd43f21e45a5489081720ca45723af14fadf3ef438111ac28785eb", - edits=( - # Clear submitted frame IDs after a reset so a newly received - # frame cannot be skipped because it was submitted before reset. - # SteamOS 0.5.9 already clears ready IDs and handles DQBUF EAGAIN. - (0x587A4, "f5f70014"), - ( - 0x96778, - "6142229162422a9100008092200081a83f0002ebc1ffff54622200910508ff17", - ), - # Fix a possible bug where a missing frame wouldn't trigger a - # request when a newer frame arrived and the gap straddled the 16 - # bit wrapping boundary. - (0x58940, "a102024b213c00133f080071ab0100547316931a06000014"), - (0x5896C, "613e0053"), - # Ignore packets which are for an older frame when re-assembling. - # There are 16 slots and this could otherwise cause an old packet - # to override a newer one. - (0x58858, "dff70014"), - (0x967D4, "c00a40b96000f837a002004b60007837c03240391d08ff176508ff17"), - # Avoid two corner cases: - # - After reset, wait for a complete recovery frame instead of - # simply waiting for _a_ frame to avoid trying to start decoding - # from a frame which depends on prior ones. - # - Ignore frames which complete reassembly but which are older - # than the last submitted frame. - (0x55C38, "ee020114"), - ( - 0x967F0, - "091c41f92a8940b9ca00f8370b0840b96b010a4b0b017837fd7bbea90cfdfe170a3040398a0000340a544d391f2003d54aff0f37c0035fd6", - ), - # To compensate for the first of the above two fixes, any frames - # which completed out of order before a recovery frame must be - # revisited after that frame. - (0x58480, "411d1f54"), - ( - 0x96828, - "800e4092000f008b000440f9010840b93f00146be1e8e054fefcfe974507ff17", - ), - # If decoder submission fails, request reset without advancing the - # last-submitted frame number as though submission succeeded. - (0x584F8, "d4f80014"), - (0x96848, "40e8e03400cb45f92b07ff17"), - # With FEC, audio gets sent as two blocks (A, B) followed by their - # parity (A^B) block. If the next block arrives (C) while the - # headset has received B but not A and is still waiting for A^B - # then B gets discarded without playing it. This loses two blocks - # worth of audio (10.67ms) rather than just skipping one missed - # block (5.33ms) and flushing the second one (B). This fixes that - # issue by just flushing B in that case. - (0x3E5D0, "a1600114"), - ( - 0x96854, - "2000004b6000f836e2ff9f520000020b1f080071acebd3548beed354620080522308c21a6384021b03ebd3346f9ffe17", - ), - # Patch incorrect sequence gap calculation when sequence numbers - # wrap modulo 65535 (recurring theme...) - (0x3E7D8, "2b600114"), - (0x96884, "6000f836e1ff9f520000010b5b9ffe17"), - # Don't request retransmission of frames that the headset has - # already moved ahead of (i.e. the last-submitted frame or older). - # Assume that a frame with a size of 4 MiB with missing metadata is - # not actually 4 MiB to avoid requesting way too many potentially - # missing fragments automatically. This can cause too many requests - # which triggers an unnecessary stream reset. Requests for the - # frame's metadata fragment continue which will contain and - # populate the size field allowing the retransmit request code to - # work normally from that point. - (0x578D8, "effb0014"), - ( - 0x96894, - "831e41f9648840b99f04003180000054e400044b4493e034e400783780324039e091e035951240b9bf025071f503951a0904ff179204ff17", - ), - # Don't trigger a reset if more than 512 missing fragments need to - # be requested as a result of a time based repair. Instead stop - # early once 20 entries are accumulated, reserving an extra 21st - # entry so that a request for a fresh metadata fragment can always - # be sent. This avoids an unnecessary reset and can speed up - # recovery. - (0x57B6C, "58fb0014"), - ( - 0x968CC, - "130080523f040031e194e05484364079a0fe0f11007c0a539f00006b4294e05402008012e2c30079330080529e04ff17", - ), - (0x57BA8, "55fb0014"), - (0x968FC, "8a3240394a01130a4a4d0011852240b9a804ff17"), - (0x57C18, "7f020a6b6c040054"), - (0x57C78, "7f020a6b6c010054"), - (0x57CA0, "7f020a6bedeaff5453050011647a1f53"), - ), - ), -} - - -def start(): - skipped = False - for name, patch in PATCHES.items(): - target = Path(name).resolve(strict=True) - data = target.read_bytes() - checksum = hashlib.sha256(data).digest() - if checksum != patch.original_hash: - print( - f"Skipping {target}: unrecognised checksum {checksum.hex()}", - file=sys.stderr, - ) - skipped = True - continue - patched = patch.apply_to(data) - source = RUNTIME / hashlib.sha256(os.fsencode(target)).hexdigest() - source.parent.mkdir(parents=True, exist_ok=True) - source.write_bytes(patched) - attributes = target.stat() - os.chown(source, attributes.st_uid, attributes.st_gid) - source.chmod(attributes.st_mode) - subprocess.run( - ["mount", "-o", f"bind,ro,{MARKER}", str(source), str(target)], - check=True, - ) - print(f"Patched {target}", file=sys.stderr) - if skipped: - raise SystemExit(1) - - -def stop(): - result = subprocess.run( - [ - "findmnt", - "--mtab", - "--options", - MARKER, - "--json", - "--output", - "TARGET", - ], - capture_output=True, - text=True, - ) - if ( - result.returncode == 1 - and not result.stdout.strip() - and not result.stderr.strip() - ): - return - result.check_returncode() - for target in reversed( - [ - Path(row["target"]) - for row in json.loads(result.stdout).get("filesystems", []) - ] - ): - subprocess.run(["umount", str(target)], check=True) - print(f"Unmounted {target}", file=sys.stderr) - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("action", choices=("start", "stop")) - args = parser.parse_args() - if args.action == "start": - start() - else: - stop() - - -if __name__ == "__main__": - main() diff --git a/frame-steamos/patches.toml b/frame-steamos/patches.toml new file mode 100644 index 0000000..ba71ff9 --- /dev/null +++ b/frame-steamos/patches.toml @@ -0,0 +1,118 @@ +# SPDX-FileCopyrightText: 2026 Tomasz Kramkowski <tomasz@kramkow.ski> +# SPDX-License-Identifier: CC0-1.0 + +target = "Frame SteamOS 0.5.9, SteamVR build 26655409" +template = "template.py" + +[[targets]] +path = "/opt/steamvr/tools/vrlink/bin/linuxarm64/vrlink" +sha256 = "d1d438f00ffd43f21e45a5489081720ca45723af14fadf3ef438111ac28785eb" +edits = [ + # Clear submitted frame IDs after a reset so a newly received + # frame cannot be skipped because it was submitted before reset. + # SteamOS 0.5.9 already clears ready IDs and handles DQBUF EAGAIN. + [0x587A4, "f5f70014"], + [ + 0x96778, + "6142229162422a9100008092200081a83f0002ebc1ffff54622200910508ff17", + ], + # Fix a possible bug where a missing frame wouldn't trigger a + # request when a newer frame arrived and the gap straddled the 16 + # bit wrapping boundary. + [0x58940, "a102024b213c00133f080071ab0100547316931a06000014"], + [0x5896C, "613e0053"], + # Ignore packets which are for an older frame when re-assembling. + # There are 16 slots and this could otherwise cause an old packet + # to override a newer one. + [0x58858, "dff70014"], + [0x967D4, "c00a40b96000f837a002004b60007837c03240391d08ff176508ff17"], + # Avoid two corner cases: + # - After reset, wait for a complete recovery frame instead of + # simply waiting for _a_ frame to avoid trying to start decoding + # from a frame which depends on prior ones. + # - Ignore frames which complete reassembly but which are older + # than the last submitted frame. + [0x55C38, "ee020114"], + [ + 0x967F0, + "091c41f92a8940b9ca00f8370b0840b96b010a4b0b017837fd7bbea90cfdfe170a3040398a0000340a544d391f2003d54aff0f37c0035fd6", + ], + # To compensate for the first of the above two fixes, any frames + # which completed out of order before a recovery frame must be + # revisited after that frame. + [0x58480, "411d1f54"], + [ + 0x96828, + "800e4092000f008b000440f9010840b93f00146be1e8e054fefcfe974507ff17", + ], + # If decoder submission fails, request reset without advancing the + # last-submitted frame number as though submission succeeded. + [0x584F8, "d4f80014"], + [0x96848, "40e8e03400cb45f92b07ff17"], + # With FEC, audio gets sent as two blocks (A, B) followed by their + # parity (A^B) block. If the next block arrives (C) while the + # headset has received B but not A and is still waiting for A^B + # then B gets discarded without playing it. This loses two blocks + # worth of audio (10.67ms) rather than just skipping one missed + # block (5.33ms) and flushing the second one (B). This fixes that + # issue by just flushing B in that case. + [0x3E5D0, "a1600114"], + [ + 0x96854, + "2000004b6000f836e2ff9f520000020b1f080071acebd3548beed354620080522308c21a6384021b03ebd3346f9ffe17", + ], + # Patch incorrect sequence gap calculation when sequence numbers + # wrap modulo 65535 (recurring theme...) + [0x3E7D8, "2b600114"], + [0x96884, "6000f836e1ff9f520000010b5b9ffe17"], + # Don't request retransmission of frames that the headset has + # already moved ahead of (i.e. the last-submitted frame or older). + # Assume that a frame with a size of 4 MiB with missing metadata is + # not actually 4 MiB to avoid requesting way too many potentially + # missing fragments automatically. This can cause too many requests + # which triggers an unnecessary stream reset. Requests for the + # frame's metadata fragment continue which will contain and + # populate the size field allowing the retransmit request code to + # work normally from that point. + [0x578D8, "effb0014"], + [ + 0x96894, + "831e41f9648840b99f04003180000054e400044b4493e034e400783780324039e091e035951240b9bf025071f503951a0904ff179204ff17", + ], + # Don't trigger a reset if more than 512 missing fragments need to + # be requested as a result of a time based repair. Instead stop + # early once 20 entries are accumulated, reserving an extra 21st + # entry so that a request for a fresh metadata fragment can always + # be sent. This avoids an unnecessary reset and can speed up + # recovery. + [0x57B6C, "58fb0014"], + [ + 0x968CC, + "130080523f040031e194e05484364079a0fe0f11007c0a539f00006b4294e05402008012e2c30079330080529e04ff17", + ], + [0x57BA8, "55fb0014"], + [0x968FC, "8a3240394a01130a4a4d0011852240b9a804ff17"], + [0x57C18, "7f020a6b6c040054"], + [0x57C78, "7f020a6b6c010054"], + [0x57CA0, "7f020a6bedeaff5453050011647a1f53"], + + # Do not send a frame ACK before the frame-history queue has an + # entry. The empty queue otherwise produces a bogus ACK 0 during + # reconnect. + [0x45228, "40bc2854"], + [0x969B0, "941e44f95451d7b4e00315aad115fe9787bafe17"], +] + +[targets.compiled] +sources = ["recovery-watchdog.c"] +imports = { fec_error_check = 0x586f0, check_stuck = 0x34b60, v4l2_vtable = 0x25b7d8 } + +# Keep the existing decoder watchdog running while waiting for a recovery +# frame. This is needed to avoid a lockup caused by the above +# recovery-frame-wait patch where the recovery frame gets lost in transit. +[[targets.compiled.hooks]] +address = 0x4eb28 +length = 4 +kind = "call" +target = "recovery_watchdog" + diff --git a/frame-steamos/recovery-watchdog.c b/frame-steamos/recovery-watchdog.c new file mode 100644 index 0000000..d557c9d --- /dev/null +++ b/frame-steamos/recovery-watchdog.c @@ -0,0 +1,97 @@ +// SPDX-FileCopyrightText: 2026 Tomasz Kramkowski <tomasz@kramkow.ski> +// SPDX-License-Identifier: CC0-1.0 + +#include <stdbool.h> +#include <stddef.h> +#include <stdint.h> + +#define ASSERT_OFFSET(type, field, expected) \ + _Static_assert( \ + offsetof(type, field) == (expected), #type "." #field " offset" \ + ) + +struct CodecVtable; + +// SVLCodecV4L2 +struct Codec { + const struct CodecVtable *vtable; + unsigned char unknown_008[0x30 - 0x08]; + uint8_t initialized; + unsigned char unknown_031[0x13c - 0x31]; + uint8_t media_thread_quitting; + unsigned char unknown_13d[0x154 - 0x13d]; + int32_t reset_state; + unsigned char unknown_158[0x1c8 - 0x158]; + uint8_t reset_thread_quitting; +}; +ASSERT_OFFSET(struct Codec, initialized, 0x30); +ASSERT_OFFSET(struct Codec, media_thread_quitting, 0x13c); +ASSERT_OFFSET(struct Codec, reset_state, 0x154); +ASSERT_OFFSET(struct Codec, reset_thread_quitting, 0x1c8); + +struct Renderer { + unsigned char unknown_000[0x10]; + struct Codec *codec; +}; +ASSERT_OFFSET(struct Renderer, codec, 0x10); + +struct Client { + unsigned char unknown_000[0x1b0]; + struct Renderer *renderer; + unsigned char unknown_1b8[0x7e06 - 0x1b8]; + uint8_t did_ever_receive_bookend; +}; +ASSERT_OFFSET(struct Client, renderer, 0x1b0); +ASSERT_OFFSET(struct Client, did_ever_receive_bookend, 0x7e06); + +struct FecReceiver { + unsigned char unknown_000[0x88]; + int32_t last_submitted_frame; + unsigned char unknown_08c[0xb90 - 0x8c]; + struct Client *client; +}; +ASSERT_OFFSET(struct FecReceiver, last_submitted_frame, 0x88); +ASSERT_OFFSET(struct FecReceiver, client, 0xb90); + +extern const struct CodecVtable v4l2_vtable __attribute__((visibility("hidden"))); +extern void fec_error_check(struct FecReceiver *); +// SVLCodecV4L2::CheckStuck +extern void check_stuck(struct Codec *, bool debug); + +// The `EventsThread` runs separately from the video receiving code, and handles +// scheduled work. +// There's an existing periodic event that re-schedules itself every 1ms that +// handles various network related bookkeeping, checks and maintenance. This +// hooks at the end of that function where it calls a FEC error checking +// function while holding the receiver lock. +void recovery_watchdog(struct FecReceiver *fec) +{ + // Call the function whose call the hook replaces. + fec_error_check(fec); + if (fec->last_submitted_frame != -1) return; + + struct Client *client = fec->client; + if (!client) return; + + // Decoder initialization happens before the host starts sending video. + // Do not run the watchdog until this stream has received its first + // "bookend". + if (!__atomic_load_n(&client->did_ever_receive_bookend, __ATOMIC_ACQUIRE)) + return; + struct Renderer *renderer = client->renderer; + if (!renderer || !renderer->codec) return; + struct Codec *codec = renderer->codec; + if (codec->vtable != &v4l2_vtable) return; + if (__atomic_load_n(&codec->reset_state, __ATOMIC_ACQUIRE)) return; + if (!codec->initialized) return; + if (__atomic_load_n(&codec->media_thread_quitting, __ATOMIC_ACQUIRE)) return; + if (__atomic_load_n(&codec->reset_thread_quitting, __ATOMIC_ACQUIRE)) return; + + // SVLCodecV4L2::CheckStuck is normally called after submitting a frame + // for decoding (and also as part of some decoder error handling) and + // checks if the decoder is making progress. It requests a stream-reset + // after ~330ms of no progress. And then a local decoder reset after + // 800ms of no progress. We call it here solely for the stream-reset + // functionality. + check_stuck(codec, false); +} diff --git a/frame-steamos/template.py b/frame-steamos/template.py new file mode 100644 index 0000000..eff1810 --- /dev/null +++ b/frame-steamos/template.py @@ -0,0 +1,138 @@ +#!/usr/bin/python3 -I +# SPDX-FileCopyrightText: 2026 Tomasz Kramkowski <tomasz@kramkow.ski> +# SPDX-License-Identifier: CC0-1.0 + +"""A minimally intrusive Frame SteamOS patcher. + +This file is generated. + +See https://kramkow.ski/project/steamvr-patches.html and +https://the-tk.com/cgit/steamvr-patches/about/ for more information. +""" + +import argparse +import hashlib +import json +import os +import subprocess +import sys +from dataclasses import dataclass +from io import BytesIO +from pathlib import Path + +MARKER = "x-valve-please-fix" +RUNTIME = Path(os.environ.get("RUNTIME_DIRECTORY", "/run/patcher")) + + +@dataclass(frozen=True) +class Edit: + offset: int + replacement: bytes + + +@dataclass(frozen=True) +class Patch: + original_hash: bytes + patched_hash: bytes + edits: tuple[Edit, ...] + + @classmethod + def from_dict(cls, data: dict) -> "Patch": + return cls( + bytes.fromhex(data["original_hash"]), + bytes.fromhex(data["patched_hash"]), + tuple( + Edit(offset, bytes.fromhex(replacement)) + for offset, replacement in data["edits"] + ), + ) + + def apply_to(self, data: bytes) -> bytes: + result = BytesIO(data) + for edit in self.edits: + result.seek(edit.offset) + result.write(edit.replacement) + patched = result.getvalue() + if hashlib.sha256(patched).digest() != self.patched_hash: + raise ValueError("patched file checksum mismatch") + return patched + + +# Please refer to the source code (linked at the top of this file) if you want +# to know how this data was generated +PATCH_DATA = {} +PATCHES = {name: Patch.from_dict(data) for name, data in PATCH_DATA.items()} + + +def start(): + skipped = False + for name, patch in PATCHES.items(): + target = Path(name).resolve(strict=True) + data = target.read_bytes() + checksum = hashlib.sha256(data).digest() + if checksum != patch.original_hash: + print( + f"Skipping {target}: unrecognised checksum {checksum.hex()}", + file=sys.stderr, + ) + skipped = True + continue + patched = patch.apply_to(data) + source = RUNTIME / hashlib.sha256(os.fsencode(target)).hexdigest() + source.parent.mkdir(parents=True, exist_ok=True) + source.write_bytes(patched) + attributes = target.stat() + os.chown(source, attributes.st_uid, attributes.st_gid) + source.chmod(attributes.st_mode) + subprocess.run( + ["mount", "-o", f"bind,ro,{MARKER}", str(source), str(target)], + check=True, + ) + print(f"Patched {target}", file=sys.stderr) + if skipped: + raise SystemExit(1) + + +def stop(): + result = subprocess.run( + [ + "findmnt", + "--mtab", + "--options", + MARKER, + "--json", + "--output", + "TARGET", + ], + capture_output=True, + text=True, + ) + if ( + result.returncode == 1 + and not result.stdout.strip() + and not result.stderr.strip() + ): + return + result.check_returncode() + for target in reversed( + [ + Path(row["target"]) + for row in json.loads(result.stdout).get("filesystems", []) + ] + ): + subprocess.run(["umount", str(target)], check=True) + print(f"Unmounted {target}", file=sys.stderr) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=("start", "stop")) + args = parser.parse_args() + if args.action == "start": + start() + else: + stop() + + +if __name__ == "__main__": + main() diff --git a/src/steamvr_patches/__init__.py b/src/steamvr_patches/__init__.py index 8ad589a..0daea79 100644 --- a/src/steamvr_patches/__init__.py +++ b/src/steamvr_patches/__init__.py @@ -40,6 +40,7 @@ class PatchSet(BaseModel): target: str targets: list[FilePatch] + template: Path | None = None @field_validator("targets") @classmethod @@ -52,6 +53,8 @@ class PatchSet(BaseModel): @classmethod def parse(cls, config: dict, directory: Path) -> Self: result = cls.model_validate(config) + if result.template is not None: + result.template = directory / result.template for target in result.targets: if target.compiled is not None: target.compiled.sources = [ @@ -87,8 +90,9 @@ def compile_patch(config: FilePatch, source: BinaryIO, output: Path) -> dict: } -def render(patches: dict[str, dict]) -> str: - template = files("steamvr_patches").joinpath("template.py").read_text() +def render(patches: dict[str, dict], template: str | None = None) -> str: + if template is None: + template = files("steamvr_patches").joinpath("template.py").read_text() placeholder = "PATCH_DATA = {}" if template.count(placeholder) != 1: raise ValueError("missing or duplicate runtime patch-table placeholder") @@ -121,11 +125,17 @@ def generate(patch_data: Path, input_root: Path) -> str: patches = {} with tempfile.TemporaryDirectory(prefix="generate-patcher-") as temporary: for index, config in enumerate(definition.targets): - with (input_root / config.path).open("rb") as source: + relative = ( + config.path.relative_to("/") + if config.path.is_absolute() + else config.path + ) + with (input_root / relative).open("rb") as source: patches[config.path.as_posix()] = compile_patch( config, source, Path(temporary) / str(index) ) - return render(patches) + template = definition.template.read_text() if definition.template else None + return render(patches, template) def main() -> None: diff --git a/src/steamvr_patches/architecture.py b/src/steamvr_patches/architecture.py new file mode 100644 index 0000000..2431069 --- /dev/null +++ b/src/steamvr_patches/architecture.py @@ -0,0 +1,92 @@ +# SPDX-FileCopyrightText: 2026 Tomasz Kramkowski <tomasz@kramkow.ski> +# SPDX-License-Identifier: GPL-3.0-or-later + +"""Architecture-specific tools and encodings for the compiled hooks.""" + +import struct +from collections.abc import Callable +from dataclasses import dataclass + +from capstone import CS_ARCH_ARM64, CS_ARCH_X86, CS_MODE_64, CS_MODE_ARM +from elftools.elf.enums import ENUM_RELOC_TYPE_AARCH64, ENUM_RELOC_TYPE_x64 + + +def x86_branch(address: int, target: int, call: bool) -> bytes: + displacement = target - address - 5 + if not -(1 << 31) <= displacement < 1 << 31: + raise ValueError("hook target is outside relative jump range") + return struct.pack("<ci", (b"\xe8" if call else b"\xe9"), displacement) + + +def arm64_branch(address: int, target: int, call: bool) -> bytes: + displacement = target - address + if displacement % 4 or not -(1 << 27) <= displacement < 1 << 27: + raise ValueError("hook target is outside relative jump range") + opcode = 0x94000000 if call else 0x14000000 + return struct.pack("<I", opcode | ((displacement // 4) & 0x3FFFFFF)) + + +@dataclass(frozen=True) +class Architecture: + compiler: tuple[str, ...] + linker: str + flags: tuple[str, ...] + disassembler: tuple[int, int] + branch: Callable[[int, int, bool], bytes] + hook_size: int + ins_alignment: int + nop: bytes + relative_relocs: frozenset[int] + + def validate_site(self, address: int, length: int) -> None: + if length < self.hook_size: + raise ValueError(f"hook requires at least {self.hook_size} bytes") + if address % self.ins_alignment: + raise ValueError( + f"hook address requires {self.ins_alignment}-byte alignment" + ) + + +ARCHITECTURES = { + "EM_X86_64": Architecture( + compiler=("cc",), + linker="ld", + flags=("-mno-red-zone", "-fcf-protection=none"), + disassembler=(CS_ARCH_X86, CS_MODE_64), + branch=x86_branch, + hook_size=5, + ins_alignment=1, + nop=b"\x90", + relative_relocs=frozenset( + ENUM_RELOC_TYPE_x64[name] for name in ("R_X86_64_PC32", "R_X86_64_PLT32") + ), + ), + "EM_AARCH64": Architecture( + compiler=("clang", "--target=aarch64-linux-gnu"), + linker="ld.lld", + flags=("-mbranch-protection=none",), + disassembler=(CS_ARCH_ARM64, CS_MODE_ARM), + branch=arm64_branch, + hook_size=4, + ins_alignment=4, + nop=(0xD503201F).to_bytes(4, "little"), + # PC-relative branches and ADRP + low-12-bit address/load pairs. + relative_relocs=frozenset( + ENUM_RELOC_TYPE_AARCH64[name] + for name in ( + "R_AARCH64_LD_PREL_LO19", + "R_AARCH64_ADR_PREL_LO21", + "R_AARCH64_ADR_PREL_PG_HI21", + "R_AARCH64_ADD_ABS_LO12_NC", + "R_AARCH64_LDST8_ABS_LO12_NC", + "R_AARCH64_TSTBR14", + "R_AARCH64_CONDBR19", + "R_AARCH64_JUMP26", + "R_AARCH64_CALL26", + "R_AARCH64_LDST16_ABS_LO12_NC", + "R_AARCH64_LDST32_ABS_LO12_NC", + "R_AARCH64_LDST64_ABS_LO12_NC", + ) + ), + ), +} diff --git a/src/steamvr_patches/elf.py b/src/steamvr_patches/elf.py index e69c567..00f18db 100644 --- a/src/steamvr_patches/elf.py +++ b/src/steamvr_patches/elf.py @@ -1,14 +1,14 @@ # SPDX-FileCopyrightText: 2026 Tomasz Kramkowski <tomasz@kramkow.ski> # SPDX-License-Identifier: GPL-3.0-or-later -"""Compile C/assembly hooks into one Linux x86-64 ELF patch payload.""" +"""Compile C into ELF patches""" import struct import subprocess from pathlib import Path -from typing import BinaryIO +from typing import BinaryIO, Literal -from capstone import CS_ARCH_X86, CS_MODE_64, Cs +from capstone import Cs from elftools.construct import Container from elftools.elf.constants import P_FLAGS from elftools.elf.elffile import ELFFile @@ -16,13 +16,16 @@ from elftools.elf.relocation import RelocationSection from elftools.elf.sections import SymbolTableSection from pydantic import BaseModel, ConfigDict, Field +from .architecture import ARCHITECTURES + class Hook(BaseModel): model_config = ConfigDict(strict=True, frozen=True, extra="forbid") address: int = Field(ge=0) - length: int = Field(ge=5) + length: int = Field(ge=4) target: str = Field(min_length=1) + kind: Literal["jump", "call"] = "jump" class CompiledPayload: @@ -33,6 +36,7 @@ class CompiledPayload: def __init__(self, source: BinaryIO, targets: list[str]): elf = ELFFile(source) + architecture = ARCHITECTURES[elf["e_machine"]] for section in elf.iter_sections(): if ( section["sh_flags"] & 2 @@ -40,10 +44,10 @@ class CompiledPayload: and section.name != ".payload" ): raise ValueError(f"unsupported allocated section: {section.name}") - # PC32 (2) PLT32 (4) (PC-relative) if isinstance(section, RelocationSection): if any( - r["r_info_type"] not in (2, 4) for r in section.iter_relocations() + r["r_info_type"] not in architecture.relative_relocs + for r in section.iter_relocations() ): raise ValueError("helper contains a non-relative relocation") payload = elf.get_section_by_name(".payload") @@ -82,8 +86,10 @@ def resolve_hook_sites(elf: ELFFile, hooks: list[Hook]) -> list[tuple[Hook, int] """Find file offsets and verify that each hook covers whole instructions.""" source = elf.stream sites = [] - disassembler = Cs(CS_ARCH_X86, CS_MODE_64) + architecture = ARCHITECTURES[elf["e_machine"]] + disassembler = Cs(*architecture.disassembler) for hook in hooks: + architecture.validate_site(hook.address, hook.length) offset = next(elf.address_offsets(hook.address, hook.length)) source.seek(offset) instructions = disassembler.disasm(source.read(hook.length), hook.address) @@ -99,8 +105,10 @@ def compile_code( targets: list[str], code_va: int, output: Path, + machine: str = "EM_X86_64", ) -> CompiledPayload: """Compile and link the patch sources at their destination address.""" + architecture = ARCHITECTURES[machine] output.mkdir(parents=True, exist_ok=False) objects = [] flags = [ @@ -110,17 +118,26 @@ def compile_code( "-fvisibility=hidden", "-fno-stack-protector", "-fno-strict-aliasing", - "-mno-red-zone", "-fno-asynchronous-unwind-tables", "-fno-unwind-tables", - "-fcf-protection=none", "-Wall", "-Wextra", + "-I", + str(Path(__file__).with_name("include")), + *architecture.flags, ] for number, source_path in enumerate(sources): obj = output / f"{number}.o" source_flags = ["-std=c17"] if source_path.suffix == ".c" else [] - run("cc", *flags, *source_flags, "-c", str(source_path), "-o", str(obj)) + run( + *architecture.compiler, + *flags, + *source_flags, + "-c", + str(source_path), + "-o", + str(obj), + ) objects.append(str(obj)) linker_script = output / "layout.ld" @@ -133,9 +150,10 @@ def compile_code( import_args = [f"--defsym={name}={value:#x}" for name, value in imports.items()] linked = output / "helper.elf" run( - "ld", + architecture.linker, "--build-id=none", "--emit-relocs", + f"--entry={targets[0]}", f"--script={linker_script}", *import_args, f"--output={linked}", @@ -146,18 +164,23 @@ def compile_code( def make_hook_edits( - sites: list[tuple[Hook, int]], entries: dict[str, int] + sites: list[tuple[Hook, int]], entries: dict[str, int], machine: str = "EM_X86_64" ) -> list[tuple[int, bytes]]: - """Redirect each hook site to its compiled entry with a relative jump.""" + """Redirect each hook site with a relative jump or call.""" + architecture = ARCHITECTURES[machine] edits = [] for hook, offset in sites: - displacement = entries[hook.target] - hook.address - 5 - if not -(1 << 31) <= displacement < 1 << 31: - raise ValueError( - f"hook target is outside relative jump range: {hook.target}" + architecture.validate_site(hook.address, hook.length) + try: + branch = architecture.branch( + hook.address, entries[hook.target], hook.kind == "call" ) - jump = b"\xe9" + struct.pack("<i", displacement) + b"\x90" * (hook.length - 5) - edits.append((offset, jump)) + except ValueError as error: + raise ValueError(f"{error}: {hook.target}") from error + padding = architecture.nop * ( + (hook.length - len(branch)) // len(architecture.nop) + ) + edits.append((offset, branch + padding)) return edits @@ -182,7 +205,9 @@ def compile_segment( table_size = (len(headers) + 1) * phdr.sizeof() code_delta = align(table_size, 16) code_va = segment_va + code_delta - compiled = compile_code(sources, imports, targets, code_va, output) + compiled = compile_code( + sources, imports, targets, code_va, output, elf["e_machine"] + ) # Relocate the enlarged program-header table into the new segment. table_header = next(header for header in headers if header["p_type"] == "PT_PHDR") @@ -225,8 +250,16 @@ def compile_hooks( output: Path, ) -> list[tuple[int, bytes]]: elf = ELFFile(source) + if ( + elf.elfclass != 64 + or not elf.little_endian + or elf["e_machine"] not in ARCHITECTURES + ): + raise ValueError( + "only little-endian x86-64 and AArch64 ELF files are supported" + ) sites = resolve_hook_sites(elf, hooks) compiled, segment_edits = compile_segment( elf, sources, imports, [hook.target for hook in hooks], output ) - return make_hook_edits(sites, compiled.entries) + segment_edits + return make_hook_edits(sites, compiled.entries, elf["e_machine"]) + segment_edits |
