From 363fe07ad4cd514d907647ee0eda2310f6efa3c0 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Tue, 17 Nov 2026 17:03:49 +0000 Subject: frame-steamos: fix a couple of bugs It's possible to hang after a reset waiting for the first frame if that frame never arrives. This adds calls to the existing decoder watchdog handler to ensure this is recoverable. Sub-optimal but better than nothing. Shouldn't happen normally anyway, and the patch is still worth it as it fixes genuine repeat resets in much more common cases. Additionally, the headset can send an ack even when there is nothing to ack, and it acks frame ID 0 in that case, this breaks the steamvr patch which keeps the ACK cutoff at all times (it can cause things to get stuck in 3.3FPS mode). --- src/steamvr_patches/elf.py | 75 +++++++++++++++++++++++++++++++++------------- 1 file changed, 54 insertions(+), 21 deletions(-) (limited to 'src/steamvr_patches/elf.py') 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 # 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(" 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 -- cgit v1.3.1