Merge pull request #151 from MartinCajiao/feat/guest-intel-trampolines

feat(relinker): support Intel trampolines in guest modules
This commit is contained in:
boykopovar
2026-09-30 19:24:46 +03:00
committed by GitHub
8 changed files with 210 additions and 2 deletions
+2
View File
@@ -28,6 +28,8 @@ The [shader recompiler](core/shader/recompiler/Recompiler.cpp) successfully prod
The relinker uses only the C++20 standard library and should build with any conforming compiler.
On Intel hosts, pass `--to-intel` to the relinker to lower supported AMD-only instructions in the executable and bundled `sce_module`/`sce_modules` PRX files. Unsupported instructions or stub jumps outside the x86-64 relative branch range produce an error.
[libc.prx](core/libs/prx/libc) implementations contain compiler-specific code. Linux builds work with GCC; on Windows, MinGW-w64 GCC 15.2.0 (`winlibs-gcc15`, `x86_64-ucrt-posix-seh`) is currently required.
The project targets maximum compiler portability. Support for additional compilers will be addressed after the first successful game launch.
+2
View File
@@ -157,6 +157,8 @@ if(BUILD_TESTING)
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_linux_load_alignment.py $<TARGET_FILE:relinker>)
add_test(NAME windows_gui COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_windows_gui.py $<TARGET_FILE:relinker>)
add_test(NAME guest_intel_trampolines COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_guest_intel_trampolines.py $<TARGET_FILE:relinker>)
else()
message(STATUS "Python3 interpreter not found; skipping Python relinker tests")
endif()
@@ -1,4 +1,5 @@
#include <elfpatcher/general/GuestModuleWriter.hpp>
#include <codegen/x86/Amd64OnlySubstitutionTable.hpp>
#include <io/BufferUtils.hpp>
#include <algorithm>
#include <limits>
@@ -100,6 +101,63 @@ std::vector<std::uint8_t> GuestModuleWriter::WriteLinux(const Relinker::GuestIma
tag(30, 8);
tag(0, 0);
const auto dynamicSize = bytes.size() - dynamicOffset;
using namespace Codegen::Amd64OnlySubstitutionTable;
const auto checkedAdd = [](const std::uint64_t left, const std::uint64_t right, const std::uint64_t offset) {
if (right > std::numeric_limits<std::uint64_t>::max() - left)
throw Domain::RelinkerException("AMD-only guest stub address overflow", offset);
return left + right;
};
const auto displacement = [](const std::uint64_t target, const std::uint64_t next, const std::uint64_t offset) {
if (target >= next) {
const auto distance = target - next;
if (distance > static_cast<std::uint64_t>(std::numeric_limits<std::int32_t>::max()))
throw Domain::RelinkerException("AMD-only guest stub exceeds rel32 range", offset);
return static_cast<std::int32_t>(distance);
}
const auto distance = next - target;
if (distance > static_cast<std::uint64_t>(std::numeric_limits<std::int32_t>::max()) + 1)
throw Domain::RelinkerException("AMD-only guest stub exceeds rel32 range", offset);
return static_cast<std::int32_t>(-static_cast<std::int64_t>(distance));
};
for (const auto& site : image.Trampolines) {
if (site.Length < kJmpRel32.Size || site.OriginalBytes.size() != site.Length ||
site.Body.size() < kJmpRel32.Size ||
site.ReturnBranchOffset > site.Body.size() - kJmpRel32.Size ||
site.Body[site.ReturnBranchOffset] != kJmpRel32.Bytes[0])
throw Domain::RelinkerException("Invalid AMD-only guest trampoline site", site.Offset);
if (site.Offset > image.Bytes.size() || site.Length > image.Bytes.size() - site.Offset)
throw Domain::RelinkerException("AMD-only guest instruction is outside the original image", site.Offset);
const auto mapped = std::any_of(image.Headers.begin(), image.Headers.end(), [&](const auto& header) {
if (header.Type != 1 || (header.Flags & 1) == 0 ||
site.Address < header.MappedAddress || site.Offset < header.Offset)
return false;
const auto addressDelta = site.Address - header.MappedAddress;
const auto offsetDelta = site.Offset - header.Offset;
return addressDelta == offsetDelta && addressDelta <= header.FileSize &&
site.Length <= header.FileSize - addressDelta;
});
if (!mapped)
throw Domain::RelinkerException("AMD-only guest instruction is outside an executable segment", site.Offset);
if (!std::equal(site.OriginalBytes.begin(), site.OriginalBytes.end(),
bytes.begin() + static_cast<std::ptrdiff_t>(site.Offset)))
throw Domain::RelinkerException("AMD-only guest site bytes changed before patching", site.Offset);
bytes.resize(Io::AlignUp(bytes.size(), kStubAlignment), kTrapFill);
const auto stubOffset = bytes.size();
const auto stubAddress = checkedAdd(extraAddress, stubOffset - extraOffset, site.Offset);
checkedAdd(stubAddress, site.Body.size(), site.Offset);
const auto returnAddress = checkedAdd(site.Address, site.Length, site.Offset);
const auto stubReturn = checkedAdd(stubAddress, site.ReturnBranchOffset + kJmpRel32.Size, site.Offset);
const auto siteNext = checkedAdd(site.Address, kJmpRel32.Size, site.Offset);
const auto returnDisplacement = displacement(returnAddress, stubReturn, site.Offset);
const auto siteDisplacement = displacement(stubAddress, siteNext, site.Offset);
bytes.insert(bytes.end(), site.Body.begin(), site.Body.end());
Io::WriteU32(bytes, stubOffset + site.ReturnBranchOffset + 1,
static_cast<std::uint32_t>(returnDisplacement));
std::fill_n(bytes.begin() + static_cast<std::ptrdiff_t>(site.Offset), site.Length, kNop1.Bytes[0]);
bytes[static_cast<std::size_t>(site.Offset)] = kJmpRel32.Bytes[0];
Io::WriteU32(bytes, static_cast<std::size_t>(site.Offset + 1),
static_cast<std::uint32_t>(siteDisplacement));
}
const auto phOffset = bytes.size();
const auto phCount = headers.size() + 2;
if (phCount > std::numeric_limits<std::uint16_t>::max()) throw Domain::RelinkerException("Too many guest program headers");
@@ -3,6 +3,7 @@
#include <elfpatcher/windows/WindowsTlsBuilder.hpp>
#include <elfpatcher/windows/WindowsPeWriter.hpp>
#include <elfpatcher/windows/WindowsRelocationBuilder.hpp>
#include <elfpatcher/windows/WindowsTrampolineBuilder.hpp>
#include <io/BufferUtils.hpp>
#include <algorithm>
#include <map>
@@ -79,6 +80,7 @@ std::vector<std::uint8_t> GuestModuleWriter::WriteWindows(const Relinker::GuestI
std::array<PeDirectory, 16> directories{};
std::uint32_t tlsIndex = 0;
directories[9] = WindowsTlsBuilder().Build(guest.Bytes, guest.Headers, image, sections, relocations, nextRva, &tlsIndex);
WindowsTrampolineBuilder().Build(guest.Trampolines, image, sections, nextRva);
for (const auto& [target, rva] : tlsModules) {
if (tlsIndex == 0) throw Domain::RelinkerException("Guest TLS relocation has no TLS block", target);
bool written = false;
@@ -1,6 +1,7 @@
#ifndef RELINKER_GUESTIMAGE_HPP
#define RELINKER_GUESTIMAGE_HPP
#include <codegen/CodegenTypes.hpp>
#include <domain/Types.hpp>
#include <relinker/domain/ISyscallScanner.hpp>
#include <filesystem>
@@ -24,6 +25,7 @@ struct GuestImage {
std::filesystem::path SourcePath;
std::string OutputName;
std::vector<std::uint8_t> Bytes;
std::vector<Codegen::TrampolineSite> Trampolines;
std::vector<Domain::ProgramHeader> Headers;
std::vector<GuestSymbol> Symbols;
std::vector<std::string> Dependencies;
@@ -62,7 +62,7 @@ std::vector<GuestArtifact> GuestModuleBuilder::Build(const std::filesystem::path
for (const auto& header : image.Headers) if (header.Type == 1 && (header.Flags & 1) != 0) codeHeaders.push_back(header);
if (toIntel) {
auto converted = Codegen::MakeAmd64OnlyConverter()->Convert(std::move(image.Bytes), codeHeaders);
if (!converted.Trampolines.empty()) throw Domain::RelinkerException("--to-intel needs " + std::to_string(converted.Trampolines.size()) + " stub(s) in guest module " + path.string() + "; stub sections are not written for guest modules");
image.Trampolines = std::move(converted.Trampolines);
image.Bytes = std::move(converted.Bytes);
}
for (const auto& header : codeHeaders) {
@@ -0,0 +1,142 @@
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
from test_linux_load_alignment import fixture as executable_fixture
SITE = bytes.fromhex("f2 0f 78 db 08 08")
SITE_ADDRESSES = (0x1002, 0x1012)
PLAIN_SITE = b"\x90" * len(SITE)
def guest_fixture(site):
image = bytearray(0xA00)
image[:16] = b"\x7fELF\x02\x01\x01" + bytes(9)
struct.pack_into("<HHIQQQIHHHHHH", image, 16,
3, 62, 1, 0x1000, 64, 0, 0, 64, 56, 3, 64, 0, 0)
struct.pack_into("<IIQQQQQQ", image, 64,
1, 5, 0x400, 0x1000, 0x1000, 0x100, 0x100, 0x100)
struct.pack_into("<IIQQQQQQ", image, 120,
1, 6, 0x600, 0x2000, 0x2000, 0x400, 0x400, 0x100)
tags = [(5, 0x2200), (10, 1), (6, 0x2220), (11, 24),
(4, 0x2240), (7, 0x2300), (8, 0), (9, 24), (0, 0)]
struct.pack_into("<IIQQQQQQ", image, 176,
2, 6, 0x600, 0x2000, 0x2000, len(tags) * 16, len(tags) * 16, 8)
image[0x400:0x500] = b"\x90" * 0x100
image[0x400:0x409] = b"\xeb\x06" + site + b"\xc3"
image[0x410:0x419] = b"\xeb\x06" + site + b"\xc3"
for index, tag in enumerate(tags):
struct.pack_into("<qQ", image, 0x600 + index * 16, *tag)
struct.pack_into("<II", image, 0x840, 1, 1)
return image
def main_fixture():
image = executable_fixture()
struct.pack_into("<Q", image, 24, 0x4000)
struct.pack_into("<QQ", image, 64 + 16, 0x4000, 0x4000)
struct.pack_into("<QQ", image, 120 + 16, 0x4600, 0x4600)
for index in (0, 2, 4):
address, = struct.unpack_from("<Q", image, 0x4600 + index * 16 + 8)
struct.pack_into("<Q", image, 0x4600 + index * 16 + 8, address + 0x4000)
return image
def elf_loads(data):
offset, = struct.unpack_from("<Q", data, 32)
size, count = struct.unpack_from("<HH", data, 54)
headers = [struct.unpack_from("<IIQQQQQQ", data, offset + index * size)
for index in range(count)]
return [header for header in headers if header[0] == 1]
def elf_bytes_at(data, loads, address, size):
for header in loads:
_, flags, offset, mapped, _, file_size, _, _ = header
if flags & 1 and mapped <= address and address + size <= mapped + file_size:
start = offset + address - mapped
return data[start:start + size]
raise AssertionError(f"Executable ELF address is unmapped: {address:#x}")
def pe_sections(data):
header, = struct.unpack_from("<I", data, 0x3C)
count, = struct.unpack_from("<H", data, header + 6)
optional_size, = struct.unpack_from("<H", data, header + 20)
offset = header + 24 + optional_size
sections = []
for index in range(count):
current = offset + index * 40
name = data[current:current + 8].split(b"\0", 1)[0]
_, rva, raw_size, raw_offset = struct.unpack_from("<IIII", data, current + 8)
flags, = struct.unpack_from("<I", data, current + 36)
sections.append((name, rva, raw_size, raw_offset, flags))
return sections
def pe_bytes_at(data, sections, address, size):
for _, rva, raw_size, raw_offset, flags in sections:
if flags & 0x20000000 and rva <= address and address + size <= rva + raw_size:
start = raw_offset + address - rva
return data[start:start + size]
raise AssertionError(f"Executable PE RVA is unmapped: {address:#x}")
def check_trampoline(read, site_address):
patched = read(site_address, len(SITE))
assert patched[0] == 0xE9 and patched[5] == 0x90, patched.hex()
target = site_address + 5 + struct.unpack_from("<i", patched, 1)[0]
body = read(target, 14)
assert body[:5] == bytes.fromhex("66 0f 38 00 1d"), body.hex()
assert body[9] == 0xE9, body.hex()
continuation = target + 14 + struct.unpack_from("<i", body, 10)[0]
assert continuation == site_address + len(SITE), (target, continuation)
def main():
relinker = Path(sys.argv[1]).resolve()
with tempfile.TemporaryDirectory(prefix="anyps5-guest-intel-") as directory:
work = Path(directory)
for windows in (False, True):
for has_stub in (False, True):
case = work / ("windows" if windows else "linux") / ("stub" if has_stub else "plain")
module_dir = case / "sce_module"
module_dir.mkdir(parents=True)
source = case / "input.elf"
output = case / ("output.exe" if windows else "output.elf")
source.write_bytes(main_fixture())
(module_dir / "sample.prx").write_bytes(guest_fixture(SITE if has_stub else PLAIN_SITE))
arguments = [str(relinker), "--to-intel"]
if windows:
arguments.append("--windows")
result = subprocess.run(arguments + [str(source), str(output)],
capture_output=True, text=True, timeout=30)
assert result.returncode == 0, (windows, has_stub, result.stdout, result.stderr)
module = case / "app0" / "sce_module" / "sample.prx.guest.prx"
data = module.read_bytes()
if windows:
assert data[:2] == b"MZ", (windows, has_stub)
sections = pe_sections(data)
code = next(section for section in sections if section[0] == b".elf0")
site_addresses = (code[1] + 2, code[1] + 0x12)
read = lambda address, size: pe_bytes_at(data, sections, address, size)
assert any(section[0] == b".amdstub" for section in sections) == has_stub
else:
assert data[:4] == b"\x7fELF", (windows, has_stub)
loads = elf_loads(data)
site_addresses = SITE_ADDRESSES
read = lambda address, size: elf_bytes_at(data, loads, address, size)
if has_stub:
for site_address in site_addresses:
check_trampoline(read, site_address)
else:
for site_address in site_addresses:
assert read(site_address, len(SITE)) == PLAIN_SITE
print("Guest Intel trampoline integration tests passed")
if __name__ == "__main__":
main()
+1 -1
View File
@@ -38,5 +38,5 @@ Throughout the project, every function at every stage either **does exactly what
- The length-changing path of the [instruction rewriter](../../core/relinker/codegen/src/x86/X64InstructionRewriter.cpp) is not used by the [converter](../../core/relinker/codegen/src/Amd64OnlyConverter.cpp): it does not adjust VEX/0F38/0F3A RIP-relative operands, data-to-code references (relocations, FDEs, jump tables) or segment sizes, so every substitution keeps the instruction length.
- The Linux placement of the `--to-intel` stubs in the [ELF patcher](../../core/relinker/elfpatcher/src/linux/LinuxElfPatcher.cpp) is covered only by a synthetic test.
- The libc [SSE4a trap emulation](../../core/libs/prx/libc/src/specifics/windows/Sse4aEmulation.hpp) on Windows is superseded by `--to-intel` and remains only until the relinked title has been verified without it.
- `--to-intel` lowerings that need a stub section are rejected for `sce_module` guest modules: the [guest module builder](../../core/relinker/relinker/src/guest/GuestModuleBuilder.cpp) does not pass stub sites to the [guest module writer](../../core/relinker/elfpatcher/include/elfpatcher/general/GuestModuleWriter.hpp).
- `--to-intel` guest module trampolines are covered only by a synthetic relinker test; no game title has been verified with them on Linux or Windows.
- [libScePlayerInvitationDialog](../../core/libs/prx/libScePlayerInvitationDialog/libScePlayerInvitationDialog.cpp) simulates dialog completion without displaying UI or sending invitations; its parameter ABI remains unverified.