aboutsummaryrefslogtreecommitdiffstats
path: root/src/steamvr_patches/elf.py
blob: 00f18db24bb8c1f41748c5d670ab65881a11d656 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# SPDX-FileCopyrightText: 2026 Tomasz Kramkowski <tomasz@kramkow.ski>
# SPDX-License-Identifier: GPL-3.0-or-later

"""Compile C into ELF patches"""

import struct
import subprocess
from pathlib import Path
from typing import BinaryIO, Literal

from capstone import Cs
from elftools.construct import Container
from elftools.elf.constants import P_FLAGS
from elftools.elf.elffile import ELFFile
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=4)
    target: str = Field(min_length=1)
    kind: Literal["jump", "call"] = "jump"


class CompiledPayload:
    """Position-independent code with resolved entry addresses inside it."""

    code: bytes
    entries: dict[str, int]

    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
                and section["sh_size"]
                and section.name != ".payload"
            ):
                raise ValueError(f"unsupported allocated section: {section.name}")
            if isinstance(section, RelocationSection):
                if any(
                    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")
        if payload is None:
            raise ValueError("missing compiled payload")
        self.code = payload.data()
        symbols = elf.get_section_by_name(".symtab")
        if not isinstance(symbols, SymbolTableSection):
            raise ValueError("missing compiled symbol table")
        payload_index = elf.get_section_index(".payload")
        address = payload["sh_addr"]
        self.entries = {}
        for target in targets:
            matches = symbols.get_symbol_by_name(target) or []
            if len(matches) != 1 or matches[0]["st_shndx"] != payload_index:
                raise ValueError(
                    f"hook target is not a unique payload symbol: {target}"
                )
            entry = matches[0]["st_value"]
            if not address <= entry < address + len(self.code):
                raise ValueError(
                    f"hook target is outside the compiled payload: {target}"
                )
            self.entries[target] = entry


def align(value: int, boundary: int) -> int:
    return (value + boundary - 1) & -boundary


def run(*args: str) -> str:
    return subprocess.check_output(args, text=True)


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 = []
    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)
        if sum(i.size for i in instructions) != hook.length:
            raise ValueError("hook length cuts an instruction or contains invalid code")
        sites.append((hook, offset))
    return sites


def compile_code(
    sources: list[Path],
    imports: dict[str, int],
    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 = [
        "-Os",
        "-ffreestanding",
        "-fPIE",
        "-fvisibility=hidden",
        "-fno-stack-protector",
        "-fno-strict-aliasing",
        "-fno-asynchronous-unwind-tables",
        "-fno-unwind-tables",
        "-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(
            *architecture.compiler,
            *flags,
            *source_flags,
            "-c",
            str(source_path),
            "-o",
            str(obj),
        )
        objects.append(str(obj))

    linker_script = output / "layout.ld"
    linker_script.write_text(
        "PHDRS { code PT_LOAD FLAGS(5); }\n"  # PF_R | PF_X: readable/executable.
        f"SECTIONS {{ . = {code_va:#x};\n"
        " .payload : { *(.text.entry) *(.text*) *(.rodata*) } :code\n"
        " /DISCARD/ : { *(.comment) *(.note.GNU-stack) }\n}\n"
    )
    import_args = [f"--defsym={name}={value:#x}" for name, value in imports.items()]
    linked = output / "helper.elf"
    run(
        architecture.linker,
        "--build-id=none",
        "--emit-relocs",
        f"--entry={targets[0]}",
        f"--script={linker_script}",
        *import_args,
        f"--output={linked}",
        *objects,
    )
    with linked.open("rb") as compiled:
        return CompiledPayload(compiled, targets)


def make_hook_edits(
    sites: list[tuple[Hook, int]], entries: dict[str, int], machine: str = "EM_X86_64"
) -> list[tuple[int, bytes]]:
    """Redirect each hook site with a relative jump or call."""
    architecture = ARCHITECTURES[machine]
    edits = []
    for hook, offset in sites:
        architecture.validate_site(hook.address, hook.length)
        try:
            branch = architecture.branch(
                hook.address, entries[hook.target], hook.kind == "call"
            )
        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


def compile_segment(
    elf: ELFFile,
    sources: list[Path],
    imports: dict[str, int],
    targets: list[str],
    output: Path,
) -> tuple[CompiledPayload, list[tuple[int, bytes]]]:
    """Place the compiled code and enlarged program-header table in a new segment."""
    phdr = elf.structs.Elf_Phdr
    headers = [segment.header for segment in elf.iter_segments()]
    # Place the new segment after all existing loadable mappings.
    load_end = max(
        header["p_vaddr"] + header["p_memsz"]
        for header in headers
        if header["p_type"] == "PT_LOAD"
    )
    segment_va = align(load_end, 4096)
    segment_offset = align(elf.stream_len, 4096)
    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, 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")
    table_header.update(
        p_flags=P_FLAGS.PF_R,
        p_offset=segment_offset,
        p_vaddr=segment_va,
        p_paddr=segment_va,
        p_filesz=table_size,
        p_memsz=table_size,
        p_align=8,
    )
    segment_size = code_delta + len(compiled.code)
    headers.append(
        Container(
            p_type="PT_LOAD",
            p_flags=P_FLAGS.PF_R | P_FLAGS.PF_X,
            p_offset=segment_offset,
            p_vaddr=segment_va,
            p_paddr=segment_va,
            p_filesz=segment_size,
            p_memsz=segment_size,
            p_align=4096,
        )
    )
    edits = [
        (0x20, struct.pack("<Q", segment_offset)),  # Elf64_Ehdr.e_phoff
        (0x38, struct.pack("<H", len(headers))),  # Elf64_Ehdr.e_phnum
        (segment_offset, b"".join(phdr.build(header) for header in headers)),
        (segment_offset + code_delta, compiled.code),
    ]
    return compiled, edits


def compile_hooks(
    source: BinaryIO,
    sources: list[Path],
    imports: dict[str, int],
    hooks: list[Hook],
    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, elf["e_machine"]) + segment_edits