From ace7999dce121b11c0e864ead36869bccdde702d Mon Sep 17 00:00:00 2001 From: Hashaam Zafar Date: Wed, 7 Oct 2026 11:44:34 -0700 Subject: [PATCH] feat(relinker): load Windows guest TLS values through register addresses mov r64 and mov r32 from fs:[mem], where mem has a base or an index register, now relink for Windows (64 48 8b 03, mov rax, fs:[rbx], in #217). The stub computes the offset with lea on the original address, adds the thread pointer and loads. These sites can be shorter than the 5-byte jump. A short site moves the following sequential instructions into its stub and relocates RIP-relative ones; a branch, a return or another TLS access after it fails the relink. A TLS site shorter than a jump is now rejected instead of overwriting the next instruction. Co-Authored-By: Claude Opus 5.5 --- .../src/windows/WindowsTlsBuilder.cpp | 94 ++++++++++++- .../tests/test_tls_function_coverage.py | 129 +++++++++++++++++- 2 files changed, 220 insertions(+), 3 deletions(-) diff --git a/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp b/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp index cec6aec7e..26cc1272c 100644 --- a/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp +++ b/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -16,6 +17,14 @@ namespace Elfpatcher::Windows { namespace { +constexpr std::size_t kJumpSize = 5; + +struct MovedInstruction { + std::uint32_t Rva; + std::vector Bytes; + std::optional RipDisplacement; +}; + struct TlsAccess { std::uint32_t Rva; Domain::FileByteOffset FileOffset; @@ -25,17 +34,48 @@ struct TlsAccess { std::uint8_t Register; std::uint32_t Displacement; std::uint8_t AluOpcode; + std::vector Address = {}; + bool Wide = true; + std::vector Moved = {}; }; bool isAluReadOpcode(std::uint8_t opcode) { return opcode == 0x03 || opcode == 0x0b || opcode == 0x13 || opcode == 0x1b || opcode == 0x23 || opcode == 0x2b || opcode == 0x33 || opcode == 0x3b; } +std::optional> registerAddress(const std::uint8_t* bytes, const std::size_t position, const std::size_t length, const std::uint8_t rex) { + if (length - position < 2) + return std::nullopt; + const auto modrm = bytes[position + 1]; + const auto mod = modrm >> 6; + if (mod == 3 || (mod == 0 && (modrm & 7) == 5)) + return std::nullopt; + std::size_t size = 2; + if ((modrm & 7) == 4) { + if (length - position < 3) + return std::nullopt; + const auto sib = bytes[position + 2]; + const bool noBase = mod == 0 && (sib & 7) == 5; + const bool noIndex = ((sib >> 3) & 7) == 4 && (rex & 2) == 0; + if ((noBase && noIndex) || ((sib & 7) == 4 && (rex & 1) == 0)) + return std::nullopt; + size += noBase ? 5 : 1; + } + size += mod == 1 ? 1 : mod == 2 ? 4 : 0; + if (length - position != size) + return std::nullopt; + std::vector address{static_cast(0x48 | (rex & 3)), 0x8d, static_cast(modrm & 0xc7)}; + address.insert(address.end(), bytes + position + 2, bytes + length); + return address; +} + void patchAccess(std::vector& sections, const TlsAccess& access, const std::uint32_t target) { for (auto& section : sections) { if (access.Rva < section.Rva || access.Rva - section.Rva >= section.Data.size()) continue; const auto offset = access.Rva - section.Rva; + if (access.Length < kJumpSize) + throw Domain::RelinkerException("TLS instruction is shorter than a jump", access.Rva); if (access.Length > section.Data.size() - offset) throw Domain::RelinkerException("TLS instruction crosses a PE section boundary", access.Rva); WindowsStubEmitter jump(access.Rva); @@ -91,6 +131,24 @@ PeDirectory WindowsTlsBuilder::Build(const std::vector& source, co const bool loadValue = supportedPrefixes && (info.RexPrefix == 0x48 || info.RexPrefix == 0x4c) && loadRegister != 4 && bytes[position] == 0x8b && (bytes[position + 1] & 0xc7) == 0x04 && bytes[position + 2] == 0x25; const bool storeImmediate = supportedPrefixes && !hasOperandSizePrefix && (info.RexPrefix == 0 || info.RexPrefix == 0x40) && info.Length - position == 11 && bytes[position] == 0xc7 && bytes[position + 1] == 0x04 && bytes[position + 2] == 0x25 && Io::ReadU32(source, header.Offset + offset + position + 3) == 0x28; const bool aluRead = supportedPrefixes && (info.RexPrefix == 0x48 || info.RexPrefix == 0x4c) && loadRegister != 4 && info.Length - position == 7 && isAluReadOpcode(bytes[position]) && (bytes[position + 1] & 0xc7) == 0x04 && bytes[position + 2] == 0x25; + const bool wide = (info.RexPrefix & 8) != 0; + const auto address = supportedPrefixes && !loadValue && !aluRead && bytes[position] == 0x8b && (wide || !hasOperandSizePrefix) ? registerAddress(bytes, position, info.Length, info.RexPrefix) : std::nullopt; + const auto addressRegister = static_cast(((bytes[position + 1] >> 3) & 7) | ((info.RexPrefix & 4) << 1)); + if (address && addressRegister != 4) { + std::vector moved; + auto length = info.Length; + while (length < kJumpSize) { + if (length >= header.FileSize - offset) + throw Domain::RelinkerException("Short guest TLS instruction ends its segment", header.Offset + offset); + const auto next = decoder.DecodeInstruction(bytes + length, header.FileSize - offset - length); + if (next.FlowKind != Codegen::ControlFlowKind::Sequential || next.HasBranchTarget || next.SegmentPrefix != 0) + throw Domain::RelinkerException("Short guest TLS instruction is followed by an instruction that cannot move", header.Offset + offset + length); + moved.push_back({CheckedRva(rva + length), std::vector(bytes + length, bytes + length + next.Length), next.HasRipRelativeDisp ? std::optional(next.RipRelativeDispOffset) : std::nullopt}); + length += next.Length; + } + accesses.push_back({rva, header.Offset + offset, length, false, 0, addressRegister, 0, 0, *address, wide, std::move(moved)}); + continue; + } if (!loadValue && !storeImmediate && !aluRead) { std::ostringstream message; message << "Unsupported Windows guest TLS instruction (bytes:" << std::hex << std::setfill('0'); @@ -162,7 +220,29 @@ PeDirectory WindowsTlsBuilder::Build(const std::vector& source, co throw Domain::RelinkerException("Branch enters a guest TLS instruction", *target); patchAccess(sections, access, code.GetRva()); code.Emit({0x48, 0x8d, 0x64, 0x24, 0x80}); - if (access.AluOpcode != 0 && access.Register == 0) { + if (!access.Address.empty()) { + code.Emit({0x51}); + code.Emit({0x50}); + for (const auto byte : access.Address) + code.Emit({byte}); + code.Emit({0x50}); + loadPointer(); + code.Emit({0x59}); + const auto rex = static_cast((access.Wide ? 0x48 : 0x40) | ((access.Register >> 3) << 2)); + if (rex != 0x40) + code.Emit({rex}); + code.Emit({0x8b, static_cast(0x04 | ((access.Register & 7) << 3)), 0x08}); + if (access.Register == 0) { + code.Emit({0x48, 0x8d, 0x64, 0x24, 0x08}); + code.Emit({0x59}); + } else if (access.Register == 1) { + code.Emit({0x58}); + code.Emit({0x48, 0x8d, 0x64, 0x24, 0x08}); + } else { + code.Emit({0x58}); + code.Emit({0x59}); + } + } else if (access.AluOpcode != 0 && access.Register == 0) { code.Emit({0x51}); code.Emit({0x52}); code.Emit({0x50}); @@ -207,6 +287,18 @@ PeDirectory WindowsTlsBuilder::Build(const std::vector& source, co if (preserveCounter) code.Emit({0x59}); } code.Emit({0x48, 0x8d, 0xa4, 0x24, 0x80, 0, 0, 0}); + for (const auto& instruction : access.Moved) { + auto bytes = instruction.Bytes; + if (instruction.RipDisplacement) { + const auto target = static_cast(instruction.Rva) + static_cast(bytes.size()) + std::bit_cast(Io::ReadU32(bytes, *instruction.RipDisplacement)); + const auto displacement = target - (static_cast(code.GetRva()) + static_cast(bytes.size())); + if (displacement < std::numeric_limits::min() || displacement > std::numeric_limits::max()) + throw Domain::RelinkerException("Moved RIP-relative instruction exceeds rel32 range from its TLS stub", access.FileOffset); + Io::WriteU32(bytes, *instruction.RipDisplacement, static_cast(static_cast(displacement))); + } + for (const auto byte : bytes) + code.Emit({byte}); + } code.Rip({0xe9}, CheckedRva(access.Rva + access.Length)); } diff --git a/core/relinker/relinker/tests/test_tls_function_coverage.py b/core/relinker/relinker/tests/test_tls_function_coverage.py index 3a8cae4dd..7f52d1e8b 100644 --- a/core/relinker/relinker/tests/test_tls_function_coverage.py +++ b/core/relinker/relinker/tests/test_tls_function_coverage.py @@ -213,6 +213,113 @@ def displacement_bounds_cases(): yield f"displacement-bounds-{register}-{displacement}", image, error +REGISTER_VALUES = {-8: 0x8877665544332211, 0x10: 0x0123456789abcdef, 0x28: 0xfedcba9876543210} +REGISTER_LOADS = ( + ("rax-rbx", bytes.fromhex("64 48 8b 03"), 0, True, {3: -8}, -8), + ("rcx-rax", bytes.fromhex("64 48 8b 08"), 1, True, {0: 0x10}, 0x10), + ("rax-rax", bytes.fromhex("64 48 8b 00"), 0, True, {0: 0x28}, 0x28), + ("r13-rbx-rcx-disp8", bytes.fromhex("64 4c 8b 6c 0b f0"), 13, True, {3: 0x18, 1: -0x10}, -8), + ("edx-rbx", bytes.fromhex("64 8b 13"), 2, False, {3: 0x10}, 0x10), + ("r9d-r13-disp8", bytes.fromhex("64 45 8b 4d 00"), 9, False, {13: 0x28}, 0x28), + ("rax-r12-index-disp32", bytes.fromhex("64 4a 8b 04 25 28 00 00 00"), 0, True, {12: -0x30}, -8), + ("rax-rcx-scaled-disp32", bytes.fromhex("64 48 8b 04 cd 10 00 00 00"), 0, True, {1: -3}, -8), + ("rax-r12", bytes.fromhex("64 49 8b 04 24"), 0, True, {12: 0x10}, 0x10), + ("rdx-rbp-disp32", bytes.fromhex("64 48 8b 95 f8 ff ff ff"), 2, True, {5: 0x30}, 0x28), + ("r15-r14", bytes.fromhex("64 4d 8b 3e"), 15, True, {14: -8}, -8), +) +REGISTER_LOAD_FOLLOWERS = ( + ("rax-rbx-rip-follower", bytes.fromhex("64 48 8b 03"), 0, True, {3: -8}, -8, b"", 0x0fedcba987654321), + ("edx-rbx-nop-follower", bytes.fromhex("64 8b 13"), 2, False, {3: 0x10}, 0x10, b"\x90", None), +) + + +def register_load_body(instruction, register, wide, address, offset, flags, follower=b"", rip_constant=None): + saved = (3, 5, 6, 7, 12, 13, 14, 15) + mask = (1 << 64) - 1 + code = bytearray() + failures = [] + + def emit(data): + code.extend(data) + + def immediate(target, value): + emit(bytes([0x48 | (target >> 3), 0xb8 | (target & 7)]) + struct.pack("= 8 else b"") + bytes([0x50 | (target & 7)])) + emit(bytes.fromhex("48 8d a4 24 00 ff ff ff")) + emit(fs_load(0, 0)) + for displacement, value in REGISTER_VALUES.items(): + immediate(1, value) + emit(bytes([0x48, 0x89, 0x48, displacement & 255])) + markers = [0x1020304050607000 + target * 0x101 for target in range(16)] + expected = list(markers) + for target in range(16): + if target != 4: + immediate(target, markers[target]) + for target, value in address.items(): + immediate(target, value) + expected[target] = value & mask + value = REGISTER_VALUES[offset] + expected[register] = value if wide else value & 0xffffffff + emit(b"\x68" + struct.pack("> 3) << 2, 0x89, 0x84 | (target & 7) << 3, 0x24]) + struct.pack("= 8 else b"") + bytes([0x58 | (target & 7)])) + emit(b"\xc3") + if rip_offset is not None: + struct.pack_into("> 3) << 2]) if wide or register >= 8 else b"") + bytes([0x8b, 0x04 | (register & 7) << 3, 0x08]) + restore = {0: bytes.fromhex("48 8d 64 24 08 59"), 1: bytes.fromhex("58 48 8d 64 24 08")}.get(register, bytes.fromhex("58 59")) + return bytes.fromhex("48 8d 64 24 80 51 50") + address + b"\x50", b"\x59" + move + restore + bytes.fromhex("48 8d a4 24 80 00 00 00") + + def make_image(transfer, metadata, extent=None, body=None): image = fixture() image.extend(b"\x90" * 0x1000) @@ -378,14 +485,32 @@ def main(): assert expected in stub, (case, expected.hex(), stub.hex()) for name, image in alu_execution_cases(): convert(name, image) + for name, image, address, instruction, register, wide, moved in register_load_cases(): + convert(name, image, tls_address=address) + pe = (work / (name + ".exe")).read_bytes() + patched = pe_bytes_at(pe, 0x10000 + address, 5) + stub = pe_bytes_at(pe, 0x10000 + address + 5 + struct.unpack_from("