From 1379ec001b63e92d34741fc19317f6699bc8b806 Mon Sep 17 00:00:00 2001 From: boykopovar Date: Sat, 26 Sep 2026 15:10:21 +0300 Subject: [PATCH] feat(relinker): add native guest module loading with export priority --- core/relinker/CMakeLists.txt | 5 + .../domain/include/domain/GuestRuntime.hpp | 27 +++ core/relinker/domain/include/domain/Types.hpp | 2 + .../elfpatcher/general/GuestModuleWriter.hpp | 16 ++ .../windows/WindowsEntryStubBuilder.hpp | 2 +- .../windows/WindowsGuestStartup.hpp | 21 ++ .../elfpatcher/windows/WindowsPeFormat.hpp | 2 + .../elfpatcher/windows/WindowsTlsBuilder.hpp | 2 +- .../src/linux/LinuxGuestModuleWriter.cpp | 131 ++++++++++++ .../src/windows/WindowsEntryStubBuilder.cpp | 34 ++- .../src/windows/WindowsGuestModuleWriter.cpp | 160 +++++++++++++++ .../src/windows/WindowsGuestStartup.cpp | 43 ++++ .../src/windows/WindowsPePatcher.cpp | 11 +- .../src/windows/WindowsTlsBuilder.cpp | 3 +- core/relinker/main.cpp | 11 +- .../include/relinker/guest/GuestImage.hpp | 49 +++++ .../relinker/src/guest/GuestImageReader.cpp | 193 ++++++++++++++++++ .../relinker/src/guest/GuestModuleBuilder.cpp | 156 ++++++++++++++ 18 files changed, 856 insertions(+), 12 deletions(-) create mode 100644 core/relinker/domain/include/domain/GuestRuntime.hpp create mode 100644 core/relinker/elfpatcher/include/elfpatcher/general/GuestModuleWriter.hpp create mode 100644 core/relinker/elfpatcher/include/elfpatcher/windows/WindowsGuestStartup.hpp create mode 100644 core/relinker/elfpatcher/src/linux/LinuxGuestModuleWriter.cpp create mode 100644 core/relinker/elfpatcher/src/windows/WindowsGuestModuleWriter.cpp create mode 100644 core/relinker/elfpatcher/src/windows/WindowsGuestStartup.cpp create mode 100644 core/relinker/relinker/include/relinker/guest/GuestImage.hpp create mode 100644 core/relinker/relinker/src/guest/GuestImageReader.cpp create mode 100644 core/relinker/relinker/src/guest/GuestModuleBuilder.cpp diff --git a/core/relinker/CMakeLists.txt b/core/relinker/CMakeLists.txt index a48325819..66f3d02bd 100644 --- a/core/relinker/CMakeLists.txt +++ b/core/relinker/CMakeLists.txt @@ -3,6 +3,11 @@ add_executable(relinker ${CMAKE_CURRENT_SOURCE_DIR}/cli/src/CliArgs.cpp ${CMAKE_CURRENT_SOURCE_DIR}/cli/src/Autorun.cpp ${CMAKE_CURRENT_SOURCE_DIR}/elfpatcher/src/linux/LinuxElfPatcher.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/elfpatcher/src/linux/LinuxGuestModuleWriter.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/elfpatcher/src/windows/WindowsGuestModuleWriter.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/elfpatcher/src/windows/WindowsGuestStartup.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/relinker/src/guest/GuestImageReader.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/relinker/src/guest/GuestModuleBuilder.cpp ${CMAKE_CURRENT_SOURCE_DIR}/elfpatcher/src/windows/WindowsPePatcher.cpp ${CMAKE_CURRENT_SOURCE_DIR}/elfpatcher/src/windows/WindowsPeFormat.cpp ${CMAKE_CURRENT_SOURCE_DIR}/elfpatcher/src/windows/WindowsLoadImage.cpp diff --git a/core/relinker/domain/include/domain/GuestRuntime.hpp b/core/relinker/domain/include/domain/GuestRuntime.hpp new file mode 100644 index 000000000..43aae70b0 --- /dev/null +++ b/core/relinker/domain/include/domain/GuestRuntime.hpp @@ -0,0 +1,27 @@ +#ifndef DOMAIN_GUESTRUNTIME_HPP +#define DOMAIN_GUESTRUNTIME_HPP + +#include +#include +#include + +namespace Domain { + +struct GuestImport { + std::string Name; + std::uint32_t TargetRva; + std::uint64_t Addend; + std::uint32_t RelocationType = 1; +}; + +struct GuestRuntime { + std::string Path; + std::vector Imports; + std::uint32_t InitRva = 0; + std::uint32_t FiniRva = 0; + bool UsePlatformTlsResolver = true; +}; + +} + +#endif diff --git a/core/relinker/domain/include/domain/Types.hpp b/core/relinker/domain/include/domain/Types.hpp index f75570c5c..40bd960ce 100644 --- a/core/relinker/domain/include/domain/Types.hpp +++ b/core/relinker/domain/include/domain/Types.hpp @@ -7,6 +7,7 @@ #include #include #include +#include namespace Domain { @@ -92,6 +93,7 @@ struct SysVDynamicSection { std::vector DynStrData; std::vector RelaData; std::vector RelaPltData; + std::vector GuestModules; }; struct CallRegistryEntry { diff --git a/core/relinker/elfpatcher/include/elfpatcher/general/GuestModuleWriter.hpp b/core/relinker/elfpatcher/include/elfpatcher/general/GuestModuleWriter.hpp new file mode 100644 index 000000000..c820c3879 --- /dev/null +++ b/core/relinker/elfpatcher/include/elfpatcher/general/GuestModuleWriter.hpp @@ -0,0 +1,16 @@ +#ifndef ELFPATCHER_GUESTMODULEWRITER_HPP +#define ELFPATCHER_GUESTMODULEWRITER_HPP + +#include + +namespace Elfpatcher { + +class GuestModuleWriter { +public: + std::vector WriteLinux(const Relinker::GuestImage& image, const std::vector& dependencies, const std::string& runPath) const; + std::vector WriteWindows(const Relinker::GuestImage& image, Domain::GuestRuntime& runtime) const; +}; + +} + +#endif diff --git a/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsEntryStubBuilder.hpp b/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsEntryStubBuilder.hpp index 1ab27beca..a7a1225c1 100644 --- a/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsEntryStubBuilder.hpp +++ b/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsEntryStubBuilder.hpp @@ -19,7 +19,7 @@ struct WindowsEntryStub { class WindowsEntryStubBuilder { public: - WindowsEntryStub Build(std::uint32_t dataRva, std::uint32_t entryRva, const WindowsImports& nativeImports, const std::vector& libraries, const std::vector& imports, const std::string& runPath, bool lazyBinding, bool dependencyDiagnostics) const; + WindowsEntryStub Build(std::uint32_t dataRva, std::uint32_t entryRva, const WindowsImports& nativeImports, const std::vector& libraries, const std::vector& imports, const std::string& runPath, bool lazyBinding, bool dependencyDiagnostics, const std::vector& guestModules = {}) const; }; } diff --git a/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsGuestStartup.hpp b/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsGuestStartup.hpp new file mode 100644 index 000000000..209c8d00b --- /dev/null +++ b/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsGuestStartup.hpp @@ -0,0 +1,21 @@ +#ifndef ELFPATCHER_WINDOWSGUESTSTARTUP_HPP +#define ELFPATCHER_WINDOWSGUESTSTARTUP_HPP + +#include +#include + +namespace Elfpatcher::Windows { + +class WindowsGuestStartup { +public: + void WriteImport(WindowsStubEmitter& code, const PeImport& import, std::uint32_t handles) const; + void Initialize(WindowsStubEmitter& code, const std::vector& modules, std::uint32_t handles) const; + void Finalize(WindowsStubEmitter& code, const std::vector& modules, std::uint32_t handles, std::uint32_t finished) const; + std::uint32_t EmitTlsResolver(WindowsStubEmitter& code) const; +private: + void callLifecycle(WindowsStubEmitter& code, std::uint32_t handle, std::uint32_t rva) const; +}; + +} + +#endif diff --git a/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsPeFormat.hpp b/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsPeFormat.hpp index 9c2d5036d..bc1c0984d 100644 --- a/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsPeFormat.hpp +++ b/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsPeFormat.hpp @@ -32,6 +32,8 @@ struct PeImport { std::string Name; std::uint32_t TargetRva; std::uint64_t Addend; + std::int32_t TargetModule = -1; + std::uint32_t RelocationType = 1; }; struct PeRelocations { diff --git a/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsTlsBuilder.hpp b/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsTlsBuilder.hpp index 297ef5885..e7dc1ed7d 100644 --- a/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsTlsBuilder.hpp +++ b/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsTlsBuilder.hpp @@ -7,7 +7,7 @@ namespace Elfpatcher::Windows { class WindowsTlsBuilder { public: - PeDirectory Build(const std::vector& source, const std::vector& headers, const WindowsLoadImage& image, std::vector& sections, std::vector& relocations, std::uint32_t& nextRva) const; + PeDirectory Build(const std::vector& source, const std::vector& headers, const WindowsLoadImage& image, std::vector& sections, std::vector& relocations, std::uint32_t& nextRva, std::uint32_t* tlsIndexRva = nullptr) const; }; } diff --git a/core/relinker/elfpatcher/src/linux/LinuxGuestModuleWriter.cpp b/core/relinker/elfpatcher/src/linux/LinuxGuestModuleWriter.cpp new file mode 100644 index 000000000..31168ebd6 --- /dev/null +++ b/core/relinker/elfpatcher/src/linux/LinuxGuestModuleWriter.cpp @@ -0,0 +1,131 @@ +#include +#include +#include +#include + +namespace Elfpatcher { + +std::vector GuestModuleWriter::WriteLinux(const Relinker::GuestImage& image, const std::vector& dependencies, const std::string& runPath) const { + auto bytes = image.Bytes; + std::vector headers; + std::uint64_t end = 0; + for (auto header : image.Headers) { + if (header.Type != 1 && header.Type != 7 && header.Type != 0x6474e550 && header.Type != 0x6474e551) continue; + if (header.Type == 1) { + header.Flags |= 4; + end = std::max(end, header.MappedAddress + header.MemorySize); + } + headers.push_back(header); + } + if (end > std::numeric_limits::max() - 0x4000) throw Domain::RelinkerException("Guest virtual address overflow"); + Io::AlignBuffer(bytes, 0x4000); + const auto extraOffset = bytes.size(); + const auto extraAddress = Io::AlignUp64(end, 0x4000); + const auto address = [&] { return extraAddress + bytes.size() - extraOffset; }; + auto strings = image.Dynamic.DynStrData; + auto symbols = image.Dynamic.DynSymData; + const auto addString = [&](const std::string& value) { + if (strings.size() > std::numeric_limits::max()) throw Domain::RelinkerException("Guest string table too large"); + const auto offset = static_cast(strings.size()); + Io::AppendString(strings, value); + return offset; + }; + bool needsTlsResolver = false; + for (std::size_t index = 1; index < image.Symbols.size(); ++index) { + const auto& symbol = image.Symbols[index]; + if (image.UsePlatformTlsResolver && symbol.Section == 0 && symbol.Name == "vNe1w4diLCs") { + Io::WriteU32(symbols, index * 24, addString("__tls_get_addr")); + needsTlsResolver = true; + } + if (symbol.Section == 0 && (symbol.Info >> 4) == 2) symbols[index * 24 + 4] = static_cast(0x10 | (symbol.Info & 15)); + } + std::vector needed; + for (const auto& dependency : dependencies) needed.push_back(addString(dependency)); + if (needsTlsResolver) needed.push_back(addString("ld-linux-x86-64.so.2")); + const auto soname = addString(image.OutputName); + const auto search = addString(runPath); + const auto strAddress = address(); + bytes.insert(bytes.end(), strings.begin(), strings.end()); + Io::AlignBuffer(bytes, 8); + const auto symAddress = address(); + bytes.insert(bytes.end(), symbols.begin(), symbols.end()); + const auto hashAddress = address(); + const auto count = static_cast(image.Symbols.size()); + Io::AppendU32(bytes, 1); + Io::AppendU32(bytes, count); + Io::AppendU32(bytes, count > 1 ? 1 : 0); + for (std::uint32_t index = 0; index < count; ++index) Io::AppendU32(bytes, index != 0 && index + 1 < count ? index + 1 : 0); + Io::AlignBuffer(bytes, 8); + const auto relaAddress = address(); + bytes.insert(bytes.end(), image.Dynamic.RelaData.begin(), image.Dynamic.RelaData.end()); + const auto pltAddress = address(); + bytes.insert(bytes.end(), image.Dynamic.RelaPltData.begin(), image.Dynamic.RelaPltData.end()); + const auto lifecycle = [&](std::uint64_t target) { + if (target == 0) return std::uint64_t{}; + const auto start = address(); + bytes.insert(bytes.end(), {0x31, 0xff, 0x31, 0xf6, 0x31, 0xd2, 0xe9}); + const auto displacement = static_cast(target) - static_cast(address() + 4); + if (displacement < std::numeric_limits::min() || displacement > std::numeric_limits::max()) throw Domain::RelinkerException("Guest initializer exceeds relative branch range"); + Io::AppendU32(bytes, static_cast(displacement)); + return start; + }; + const auto init = lifecycle(image.Init); + const auto fini = lifecycle(image.Fini); + Io::AlignBuffer(bytes, 8); + const auto dynamicOffset = bytes.size(); + const auto dynamicAddress = address(); + const auto tag = [&](std::uint64_t key, std::uint64_t value) { Io::AppendU64(bytes, key); Io::AppendU64(bytes, value); }; + for (const auto offset : needed) tag(1, offset); + tag(14, soname); + tag(29, search); + tag(4, hashAddress); + tag(5, strAddress); + tag(10, strings.size()); + tag(6, symAddress); + tag(11, 24); + if (!image.Dynamic.RelaData.empty()) { + tag(7, relaAddress); + tag(8, image.Dynamic.RelaData.size()); + tag(9, 24); + } + if (!image.Dynamic.RelaPltData.empty()) { + tag(23, pltAddress); + tag(2, image.Dynamic.RelaPltData.size()); + tag(20, 7); + tag(3, image.Got); + } + if (init != 0) tag(12, init); + if (fini != 0) tag(13, fini); + tag(30, 8); + tag(0, 0); + const auto dynamicSize = bytes.size() - dynamicOffset; + const auto phOffset = bytes.size(); + const auto phCount = headers.size() + 2; + if (phCount > std::numeric_limits::max()) throw Domain::RelinkerException("Too many guest program headers"); + const auto extraSize = bytes.size() + phCount * 56 - extraOffset; + headers.push_back({1, 7, extraOffset, extraAddress, extraAddress, extraSize, extraSize, 0x4000}); + headers.push_back({2, 6, dynamicOffset, dynamicAddress, dynamicAddress, dynamicSize, dynamicSize, 8}); + for (const auto& header : headers) { + Io::AppendU32(bytes, header.Type); + Io::AppendU32(bytes, header.Flags); + Io::AppendU64(bytes, header.Offset); + Io::AppendU64(bytes, header.MappedAddress); + Io::AppendU64(bytes, header.PhysicalAddress); + Io::AppendU64(bytes, header.FileSize); + Io::AppendU64(bytes, header.MemorySize); + Io::AppendU64(bytes, header.Alignment); + } + bytes[7] = 0; + bytes[8] = 0; + Io::WriteU16(bytes, 16, 3); + Io::WriteU64(bytes, 24, 0); + Io::WriteU64(bytes, 32, phOffset); + Io::WriteU64(bytes, 40, 0); + Io::WriteU16(bytes, 56, static_cast(phCount)); + Io::WriteU16(bytes, 58, 0); + Io::WriteU16(bytes, 60, 0); + Io::WriteU16(bytes, 62, 0); + return bytes; +} + +} diff --git a/core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp b/core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp index 51f41f827..c0bde9668 100644 --- a/core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp +++ b/core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -29,7 +30,7 @@ std::string normalizeRunPath(std::string path) { } -WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, const std::uint32_t entryRva, const WindowsImports& nativeImports, const std::vector& libraries, const std::vector& imports, const std::string& runPath, const bool lazyBinding, const bool dependencyDiagnostics) const { +WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, const std::uint32_t entryRva, const WindowsImports& nativeImports, const std::vector& libraries, const std::vector& imports, const std::string& runPath, const bool lazyBinding, const bool dependencyDiagnostics, const std::vector& guestModules) const { if (!imports.empty() && libraries.empty()) throw Domain::RelinkerException("ELF imports have no DT_NEEDED libraries"); const auto path = normalizeRunPath(runPath); @@ -54,14 +55,17 @@ WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, con const auto programPath = reserve(PathCapacity); const auto modulePath = reserve(PathCapacity); const auto handles = reserve(libraries.size() * 8); + const auto guestFinished = reserve(4); + const WindowsGuestStartup guestStartup; const auto functionTable = reserve(12 * 32); const auto unwindRva = CheckedRva(dataRva + data.size()); data.insert(data.end(), {1, 10, 6, 0, 10, 0xb2, 6, 0xc0, 4, 0x70, 3, 0x60, 2, 0x50, 1, 0x30}); std::vector libraryPaths; std::vector libraryNames; - for (const auto& library : libraries) { - auto name = path + library; + for (std::size_t index = 0; index < libraries.size(); ++index) { + auto name = index < guestModules.size() ? libraries[index] : path + libraries[index]; + std::replace(name.begin(), name.end(), '/', '\\'); if (name.size() + 1 >= PathCapacity) throw Domain::RelinkerException("Windows library path exceeds the startup buffer: " + name); libraryPaths.push_back(addString(name)); @@ -218,7 +222,7 @@ WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, con code.Emit({0x49, 0xff, 0xc4}); for (std::size_t index = 0; index < libraries.size(); ++index) { - if (absolutePath) { + if (absolutePath && index >= guestModules.size()) { code.Rip({0x48, 0x8d, 0x0d}, libraryPaths[index]); } else { code.Emit({0x4c, 0x89, 0xe0, 0x48, 0x29, 0xd8, 0x48, 0x05}); @@ -270,7 +274,14 @@ WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, con std::vector unresolvedBranches; std::vector lazyUnresolvedImports; + std::vector tlsResolverAddresses; for (std::size_t index = 0; index < imports.size(); ++index) { + if (!guestModules.empty() && guestModules.front().UsePlatformTlsResolver && imports[index].Name == "vNe1w4diLCs") { + if (imports[index].Addend != 0) throw Domain::RelinkerException("TLS resolver import has an addend"); + tlsResolverAddresses.push_back(code.Branch({0x48, 0x8d, 0x05})); + guestStartup.WriteImport(code, imports[index], handles); + continue; + } code.Rip({0x48, 0x8d, 0x1d}, handles); code.Rip({0x48, 0x8d, 0x35}, symbolNames[index]); code.Emit({0xbd}); @@ -291,7 +302,7 @@ WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, con code.U64(imports[index].Addend); code.Emit({0x48, 0x01, 0xd0}); } - code.Rip({0x48, 0x89, 0x05}, imports[index].TargetRva); + guestStartup.WriteImport(code, imports[index], handles); code.PatchBranch(skipGotWrite, code.GetRva()); continue; } @@ -299,20 +310,26 @@ WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, con writeString(errorRvas.at(3 + index), true); unresolvedBranches.push_back(code.Branch({0xe9})); code.PatchBranch(resolved, code.GetRva()); + if (imports[index].RelocationType == 16) code.Emit({0x48, 0x8b, 0x00}); + if (imports[index].RelocationType == 17) code.Emit({0x48, 0x8b, 0x40, 8}); if (imports[index].Addend != 0) { code.Emit({0x48, 0xba}); code.U64(imports[index].Addend); code.Emit({0x48, 0x01, 0xd0}); } - code.Rip({0x48, 0x89, 0x05}, imports[index].TargetRva); + guestStartup.WriteImport(code, imports[index], handles); } + guestStartup.Initialize(code, guestModules, handles); writeString(enteringElf); code.Emit({0x48, 0xc7, 0x44, 0x24, 0x40, 1, 0, 0, 0}); code.Rip({0x48, 0x8d, 0x05}, programPath); code.Emit({0x48, 0x89, 0x44, 0x24, 0x48, 0x31, 0xc0, 0x48, 0x89, 0x44, 0x24, 0x50, 0x48, 0x89, 0x44, 0x24, 0x58, 0x48, 0x8d, 0x7c, 0x24, 0x40}); const auto exitCallback = code.Branch({0x48, 0x8d, 0x35}); code.Rip({0xe8}, entryRva); + code.Emit({0x89, 0x44, 0x24, 0x58}); + guestStartup.Finalize(code, guestModules, handles, guestFinished); + code.Emit({0x8b, 0x44, 0x24, 0x58}); code.Emit({0x89, 0xc1}); call("ExitProcess"); code.Emit({0x0f, 0x0b}); @@ -332,7 +349,12 @@ WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, con const auto functionEnd = code.GetRva(); code.PatchBranch(exitCallback, functionEnd); + code.Emit({0x48, 0x83, 0xec, 0x28}); + guestStartup.Finalize(code, guestModules, handles, guestFinished); + code.Emit({0x48, 0x83, 0xc4, 0x28}); code.Emit({0xc3}); + const auto tlsResolver = guestStartup.EmitTlsResolver(code); + for (const auto offset : tlsResolverAddresses) code.PatchBranch(offset, tlsResolver); for (const auto index : lazyUnresolvedImports) { const auto stubRva = code.GetRva(); diff --git a/core/relinker/elfpatcher/src/windows/WindowsGuestModuleWriter.cpp b/core/relinker/elfpatcher/src/windows/WindowsGuestModuleWriter.cpp new file mode 100644 index 000000000..3e7f5be80 --- /dev/null +++ b/core/relinker/elfpatcher/src/windows/WindowsGuestModuleWriter.cpp @@ -0,0 +1,160 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Elfpatcher { + +std::vector GuestModuleWriter::WriteWindows(const Relinker::GuestImage& guest, Domain::GuestRuntime& runtime) const { + using namespace Windows; + WindowsLoadImage image(guest.Bytes, guest.Headers); + std::vector relocations; + std::vector> tlsModules; + std::map targets; + const auto apply = [&](const std::vector& table) { + for (std::size_t offset = 0; offset < table.size(); offset += 24) { + const auto target = Io::ReadU64(table, offset); + const auto info = Io::ReadU64(table, offset + 8); + const auto addend = Io::ReadU64(table, offset + 16); + const auto type = static_cast(info); + const auto symbolIndex = info >> 32; + const auto& symbol = guest.Symbols.at(symbolIndex); + const auto rva = image.GetRva(target, 8); + for (const auto& header : guest.Headers) { + if (header.Type == 7 && target >= header.MappedAddress && target - header.MappedAddress < header.FileSize) throw Domain::RelinkerException("Windows guest TLS template relocations require explicit support", target); + } + const auto next = targets.lower_bound(target); + if ((next != targets.end() && next->first < target + 8) || (next != targets.begin() && std::prev(next)->second > target)) throw Domain::RelinkerException("Overlapping guest relocations", target); + targets.emplace(target, target + 8); + image.RequireWritable(target, 8); + if (type == 8) { + if (symbolIndex != 0) throw Domain::RelinkerException("RELATIVE guest relocation has a symbol", target); + image.WritePointer(target, image.GetRelocatedAddress(addend)); + relocations.push_back(rva); + } else if (type == 16) { + if (addend != 0 || (symbolIndex != 0 && (symbol.Info & 15) != 6)) throw Domain::RelinkerException("Invalid guest TLS module relocation", target); + if (symbolIndex != 0 && symbol.Section == 0) { + image.WritePointer(target, 0); + runtime.Imports.push_back({symbol.Name, rva, 0, 16}); + } else tlsModules.emplace_back(target, rva); + } else if (type == 17) { + if (symbolIndex != 0 && (symbol.Info & 15) != 6) throw Domain::RelinkerException("Invalid guest TLS offset relocation", target); + if (symbolIndex != 0 && symbol.Section == 0) { + image.WritePointer(target, 0); + runtime.Imports.push_back({symbol.Name, rva, addend, 17}); + } else image.WritePointer(target, symbol.Value + addend); + } else if (type == 18) { + const auto tls = std::find_if(guest.Headers.begin(), guest.Headers.end(), [](const auto& header) { return header.Type == 7; }); + if (tls == guest.Headers.end() || (symbolIndex != 0 && (symbol.Section == 0 || (symbol.Info & 15) != 6))) throw Domain::RelinkerException("Unsupported external static TLS relocation", target); + const auto size = Io::AlignUp64(tls->MemorySize, std::max(tls->Alignment, 16)); + image.WritePointer(target, symbol.Value + addend - size); + } else if (type == 1 || type == 6 || type == 7) { + if (symbolIndex == 0 || (type != 1 && addend != 0) || (symbol.Info & 15) == 6) throw Domain::RelinkerException("Invalid guest symbol relocation", target); + if (symbol.Section != 0) { + if (symbol.Section >= 0xff00) throw Domain::RelinkerException("Unsupported special guest symbol section", target); + image.WritePointer(target, image.GetRelocatedAddress(symbol.Value) + addend); + relocations.push_back(rva); + } else { + if (symbol.Name.empty()) throw Domain::RelinkerException("Empty guest import", target); + image.WritePointer(target, 0); + runtime.Imports.push_back({symbol.Name, rva, addend}); + } + } else throw Domain::RelinkerException("Unsupported Windows guest relocation " + std::to_string(type), target); + } + }; + apply(guest.Dynamic.RelaData); + apply(guest.Dynamic.RelaPltData); + auto sections = image.BuildSections(); + auto nextRva = image.GetEndRva(); + std::array directories{}; + std::uint32_t tlsIndex = 0; + directories[9] = WindowsTlsBuilder().Build(guest.Bytes, guest.Headers, image, sections, relocations, nextRva, &tlsIndex); + for (const auto& [target, rva] : tlsModules) { + if (tlsIndex == 0) throw Domain::RelinkerException("Guest TLS relocation has no TLS block", target); + bool written = false; + for (auto& section : sections) { + if (rva < section.Rva || rva - section.Rva > section.Data.size() || section.Data.size() - (rva - section.Rva) < 8) continue; + Io::WriteU64(section.Data, rva - section.Rva, ImageBase + tlsIndex); + written = true; + break; + } + if (!written) throw Domain::RelinkerException("Guest TLS target is unmapped", target); + relocations.push_back(rva); + } + for (const auto& header : guest.Headers) { + if (header.Type != 0x6474e550) continue; + std::vector metadata(4); + Io::WriteU32(metadata, 0, image.GetRva(header.MappedAddress, header.FileSize)); + sections.push_back({".ehmeta", nextRva, SectionRead | 0x40u, std::move(metadata)}); + nextRva = AlignRva(nextRva + sections.back().Data.size()); + } + std::map exports; + PeSection tlsExports{".tlsrefs", nextRva, SectionRead | 0x40u, {}}; + for (const auto& symbol : guest.Symbols) { + if (symbol.Section == 0 || (symbol.Info >> 4) == 0 || symbol.Visibility == 1 || symbol.Visibility == 2) continue; + if (symbol.Section >= 0xff00) throw Domain::RelinkerException("Unsupported guest export section: " + symbol.Name); + std::uint32_t rva = 0; + if ((symbol.Info & 15) == 6) { + if (tlsIndex == 0) throw Domain::RelinkerException("Guest TLS export has no TLS block: " + symbol.Name); + rva = CheckedRva(tlsExports.Rva + tlsExports.Data.size()); + Io::AppendU64(tlsExports.Data, ImageBase + tlsIndex); + Io::AppendU64(tlsExports.Data, symbol.Value); + relocations.push_back(rva); + } else rva = image.GetRva(symbol.Value, std::max(symbol.Size, 1)); + if (!exports.emplace(symbol.Name, rva).second) throw Domain::RelinkerException("Duplicate guest export: " + symbol.Name); + } + if (!tlsExports.Data.empty()) { + nextRva = AlignRva(nextRva + tlsExports.Data.size()); + sections.push_back(std::move(tlsExports)); + } + if (exports.size() > 65535) throw Domain::RelinkerException("Too many guest PE exports"); + PeSection exportSection{".edata", nextRva, SectionRead | 0x40u, std::vector(40)}; + auto& data = exportSection.Data; + const auto count = CheckedRva(exports.size()); + const auto functions = data.size(); + data.resize(data.size() + count * 4); + const auto names = data.size(); + data.resize(data.size() + count * 4); + const auto ordinals = data.size(); + data.resize(data.size() + count * 2); + Io::WriteU32(data, 12, CheckedRva(nextRva + data.size())); + Io::AppendString(data, guest.OutputName); + Io::WriteU32(data, 16, 1); + Io::WriteU32(data, 20, count); + Io::WriteU32(data, 24, count); + Io::WriteU32(data, 28, CheckedRva(nextRva + functions)); + Io::WriteU32(data, 32, CheckedRva(nextRva + names)); + Io::WriteU32(data, 36, CheckedRva(nextRva + ordinals)); + std::size_t index = 0; + for (const auto& [name, rva] : exports) { + Io::WriteU32(data, functions + index * 4, rva); + Io::WriteU32(data, names + index * 4, CheckedRva(nextRva + data.size())); + Io::WriteU16(data, ordinals + index * 2, static_cast(index)); + Io::AppendString(data, name); + ++index; + } + directories[0] = {nextRva, CheckedRva(data.size())}; + nextRva = AlignRva(nextRva + data.size()); + sections.push_back(std::move(exportSection)); + auto relocationData = WindowsRelocationBuilder().BuildBaseRelocations(relocations); + if (!relocationData.empty()) { + directories[5] = {nextRva, CheckedRva(relocationData.size())}; + sections.push_back({".reloc", nextRva, SectionRead | 0x02000040u, std::move(relocationData)}); + nextRva = AlignRva(nextRva + sections.back().Data.size()); + } + const auto entry = nextRva; + sections.push_back({".dllmain", entry, SectionRead | SectionExecute | 0x20u, {0xb8, 1, 0, 0, 0, 0xc3}}); + runtime.InitRva = guest.Init == 0 ? 0 : image.GetRva(guest.Init); + runtime.FiniRva = guest.Fini == 0 ? 0 : image.GetRva(guest.Fini); + auto result = WindowsPeWriter().Write(sections, entry, directories); + const auto characteristics = Io::ReadU16(result, 0x80 + 22); + Io::WriteU16(result, 0x80 + 22, static_cast((characteristics | 0x2000) & ~1u)); + return result; +} + +} diff --git a/core/relinker/elfpatcher/src/windows/WindowsGuestStartup.cpp b/core/relinker/elfpatcher/src/windows/WindowsGuestStartup.cpp new file mode 100644 index 000000000..b5e212bc9 --- /dev/null +++ b/core/relinker/elfpatcher/src/windows/WindowsGuestStartup.cpp @@ -0,0 +1,43 @@ +#include + +namespace Elfpatcher::Windows { + +void WindowsGuestStartup::WriteImport(WindowsStubEmitter& code, const PeImport& import, const std::uint32_t handles) const { + if (import.TargetModule < 0) { + code.Rip({0x48, 0x89, 0x05}, import.TargetRva); + return; + } + code.Rip({0x48, 0x8b, 0x15}, CheckedRva(handles + static_cast(import.TargetModule) * 8)); + code.Emit({0x41, 0xb8}); + code.U32(import.TargetRva); + code.Emit({0x4a, 0x89, 0x04, 0x02}); +} + +void WindowsGuestStartup::callLifecycle(WindowsStubEmitter& code, const std::uint32_t handle, const std::uint32_t rva) const { + if (rva == 0) return; + code.Rip({0x48, 0x8b, 0x05}, handle); + code.Emit({0xb9}); + code.U32(rva); + code.Emit({0x48, 0x01, 0xc8, 0x31, 0xff, 0x31, 0xf6, 0x31, 0xd2, 0xff, 0xd0}); +} + +void WindowsGuestStartup::Initialize(WindowsStubEmitter& code, const std::vector& modules, const std::uint32_t handles) const { + for (std::size_t index = 0; index < modules.size(); ++index) callLifecycle(code, CheckedRva(handles + index * 8), modules[index].InitRva); +} + +void WindowsGuestStartup::Finalize(WindowsStubEmitter& code, const std::vector& modules, const std::uint32_t handles, const std::uint32_t finished) const { + code.Emit({0xb8, 1, 0, 0, 0}); + code.Rip({0x87, 0x05}, finished); + code.Emit({0x85, 0xc0}); + const auto skip = code.Branch({0x0f, 0x85}); + for (std::size_t index = modules.size(); index > 0; --index) callLifecycle(code, CheckedRva(handles + (index - 1) * 8), modules[index - 1].FiniRva); + code.PatchBranch(skip, code.GetRva()); +} + +std::uint32_t WindowsGuestStartup::EmitTlsResolver(WindowsStubEmitter& code) const { + const auto entry = code.GetRva(); + code.Emit({0x48, 0x8b, 0x07, 0x8b, 0x08, 0x65, 0x48, 0x8b, 0x04, 0x25, 0x58, 0, 0, 0, 0x48, 0x8b, 0x04, 0xc8, 0x48, 0x03, 0x47, 8, 0xc3}); + return entry; +} + +} diff --git a/core/relinker/elfpatcher/src/windows/WindowsPePatcher.cpp b/core/relinker/elfpatcher/src/windows/WindowsPePatcher.cpp index 0910e7aad..a9e5e2a64 100644 --- a/core/relinker/elfpatcher/src/windows/WindowsPePatcher.cpp +++ b/core/relinker/elfpatcher/src/windows/WindowsPePatcher.cpp @@ -78,10 +78,17 @@ std::vector WindowsPePatcher::Patch(const std::vector guestPaths; + for (std::size_t index = 0; index < dynamicSection.GuestModules.size(); ++index) { + const auto& module = dynamicSection.GuestModules[index]; + guestPaths.push_back(module.Path); + for (const auto& import : module.Imports) relocations.Imports.push_back({import.Name, import.TargetRva, import.Addend, static_cast(index), import.RelocationType}); + } + libraries.insert(libraries.begin(), guestPaths.begin(), guestPaths.end()); if (dependencyDiagnostics) writeDiagnosticsImports(relocations.Imports); - auto entry = WindowsEntryStubBuilder().Build(nextRva, image.GetEntryRva(), nativeImports, libraries, relocations.Imports, runPath, lazyBinding, dependencyDiagnostics); + auto entry = WindowsEntryStubBuilder().Build(nextRva, image.GetEntryRva(), nativeImports, libraries, relocations.Imports, runPath, lazyBinding, dependencyDiagnostics, dynamicSection.GuestModules); directories[3] = entry.ExceptionDirectory; const auto entryRva = entry.Code.Rva; sections.push_back(std::move(nativeImports.Section)); diff --git a/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp b/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp index ea58d8138..5721381f8 100644 --- a/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp +++ b/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp @@ -35,7 +35,7 @@ void patchAccess(std::vector& sections, const TlsAccess& access, cons } -PeDirectory WindowsTlsBuilder::Build(const std::vector& source, const std::vector& headers, const WindowsLoadImage& image, std::vector& sections, std::vector& relocations, std::uint32_t& nextRva) const { +PeDirectory WindowsTlsBuilder::Build(const std::vector& source, const std::vector& headers, const WindowsLoadImage& image, std::vector& sections, std::vector& relocations, std::uint32_t& nextRva, std::uint32_t* tlsIndexRva) const { const Domain::ProgramHeader* tls = nullptr; const Codegen::X64InstructionDecoder decoder; @@ -92,6 +92,7 @@ PeDirectory WindowsTlsBuilder::Build(const std::vector& source, co PeSection data{".gtls", nextRva, SectionRead | SectionWrite | 0x40u, std::vector(templateOffset + blockSize + 16)}; const auto indexRva = nextRva + 40; + if (tlsIndexRva != nullptr) *tlsIndexRva = indexRva; const auto callbackTableRva = nextRva + 48; const auto templateRva = nextRva + templateOffset; const auto codeRva = AlignRva(nextRva + data.Data.size()); diff --git a/core/relinker/main.cpp b/core/relinker/main.cpp index 90f087e60..32b8c2b32 100644 --- a/core/relinker/main.cpp +++ b/core/relinker/main.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -72,6 +73,8 @@ int main(const int argc, char* argv[]) { for (std::size_t index = 0; index < patch.Bytes.size(); ++index) sourceBytes[patch.Offset + index] = patch.Bytes[index]; } + const auto guestArtifacts = Relinker::GuestModuleBuilder().Build(args.inputPath, absPath, result.DynamicSection, args.toWindows, args.toIntel, args.skipSyscallCheck, args.lazyBinding, args.runPath); + if (args.writeRegistry) { const std::filesystem::path outFsPath(absPath); const std::string registryPath = (outFsPath.parent_path() / (outFsPath.stem().string() + ".registry.json")).string(); @@ -95,7 +98,13 @@ int main(const int argc, char* argv[]) { ); } - fileWriter.Write(absPath, patcher->Patch(sourceBytes, result.OriginalHeaders, result.DynamicSection, result.OriginalPltGotVaddr, args.runPath, args.lazyBinding, args.windowsDiagnostics)); + const auto executableBytes = patcher->Patch(sourceBytes, result.OriginalHeaders, result.DynamicSection, result.OriginalPltGotVaddr, args.runPath, args.lazyBinding, args.windowsDiagnostics); + for (const auto& artifact : guestArtifacts) { + std::filesystem::create_directories(artifact.Path.parent_path()); + fileWriter.Write(artifact.Path.string(), artifact.Bytes); + std::cout << "Guest module: " << artifact.Path.string() << '\n'; + } + fileWriter.Write(absPath, executableBytes); std::cout << "External prx references: " << result.RegistryEntries.size() << "\nOutput file: " << absPath << '\n'; if (args.autorun) return Cli::Autorun(absPath, args.toWindows); diff --git a/core/relinker/relinker/include/relinker/guest/GuestImage.hpp b/core/relinker/relinker/include/relinker/guest/GuestImage.hpp new file mode 100644 index 000000000..e001c4357 --- /dev/null +++ b/core/relinker/relinker/include/relinker/guest/GuestImage.hpp @@ -0,0 +1,49 @@ +#ifndef RELINKER_GUESTIMAGE_HPP +#define RELINKER_GUESTIMAGE_HPP + +#include +#include + +namespace Relinker { + +struct GuestSymbol { + std::string Name; + std::uint8_t Info; + std::uint8_t Visibility; + std::uint16_t Section; + std::uint64_t Value; + std::uint64_t Size; +}; + +struct GuestImage { + std::filesystem::path SourcePath; + std::string OutputName; + std::vector Bytes; + std::vector Headers; + std::vector Symbols; + std::vector Dependencies; + Domain::SysVDynamicSection Dynamic; + std::uint64_t Init = 0; + std::uint64_t Fini = 0; + std::uint64_t Got = 0; + bool UsePlatformTlsResolver = true; +}; + +class GuestImageReader { +public: + GuestImage Read(const std::filesystem::path& path, std::vector bytes) const; +}; + +struct GuestArtifact { + std::filesystem::path Path; + std::vector Bytes; +}; + +class GuestModuleBuilder { +public: + std::vector Build(const std::filesystem::path& inputPath, const std::filesystem::path& outputPath, Domain::SysVDynamicSection& dynamic, bool windows, bool toIntel, bool skipSyscallCheck, bool lazyBinding, const std::string& runPath) const; +}; + +} + +#endif diff --git a/core/relinker/relinker/src/guest/GuestImageReader.cpp b/core/relinker/relinker/src/guest/GuestImageReader.cpp new file mode 100644 index 000000000..816196a26 --- /dev/null +++ b/core/relinker/relinker/src/guest/GuestImageReader.cpp @@ -0,0 +1,193 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Relinker { + +GuestImage GuestImageReader::Read(const std::filesystem::path& path, std::vector bytes) const { + const auto fail = [&](const std::string& message) { throw Domain::RelinkerException(path.string() + ": " + message); }; + const auto range = [&](std::uint64_t offset, std::uint64_t size) { + if (offset > bytes.size() || size > bytes.size() - offset) fail("ELF range exceeds file"); + }; + range(0, 64); + if (Io::ReadU32(bytes, 0) != 0x464c457f || bytes[4] != 2 || bytes[5] != 1 || bytes[6] != 1 || Io::ReadU16(bytes, 18) != 62 || Io::ReadU32(bytes, 20) != 1) fail("Expected little-endian ELF64 x86-64"); + const auto type = Io::ReadU16(bytes, 16); + if (type != 3 && type != 0xfe18) fail("ELF is not a shared module"); + if (Io::ReadU16(bytes, 52) != 64 || Io::ReadU16(bytes, 54) != 56 || Io::ReadU16(bytes, 56) == 0) fail("Invalid ELF program header table"); + range(Io::ReadU64(bytes, 32), static_cast(Io::ReadU16(bytes, 56)) * 56); + GuestImage image; + image.SourcePath = path; + image.OutputName = path.filename().string() + ".guest.prx"; + image.Headers = ElfReader(bytes).ReadProgramHeaders(); + const Domain::ProgramHeader* dynamic = nullptr; + const Domain::ProgramHeader* dynlib = nullptr; + const Domain::ProgramHeader* tls = nullptr; + std::map loads; + for (const auto& header : image.Headers) { + range(header.Offset, header.FileSize); + if (header.Type == 1) { + if (header.FileSize > header.MemorySize || header.MemorySize > std::numeric_limits::max() - header.MappedAddress || (header.Flags & ~7u) != 0) fail("Invalid load segment"); + if (header.Alignment > 1 && (!std::has_single_bit(header.Alignment) || header.Offset % header.Alignment != header.MappedAddress % header.Alignment)) fail("Invalid load segment alignment"); + const auto next = loads.lower_bound(header.MappedAddress); + if ((next != loads.end() && next->first < header.MappedAddress + header.MemorySize) || (next != loads.begin() && std::prev(next)->second > header.MappedAddress)) fail("Overlapping load segments"); + loads.emplace(header.MappedAddress, header.MappedAddress + header.MemorySize); + } + if (header.Type == 2) { + if (dynamic != nullptr) fail("Duplicate dynamic segment"); + dynamic = &header; + } + if (header.Type == 0x61000000) { + if (dynlib != nullptr) fail("Duplicate SCE dynamic data"); + dynlib = &header; + } + if (header.Type == 7) { + if (tls != nullptr || header.FileSize > header.MemorySize || !std::has_single_bit(header.Alignment)) fail("Invalid TLS segment"); + tls = &header; + } + } + if (loads.empty() || dynamic == nullptr || dynamic->FileSize % 16 != 0) fail("Missing or invalid ELF load/dynamic segments"); + std::map tags; + std::vector needed; + bool terminated = false; + for (std::uint64_t offset = dynamic->Offset; offset < dynamic->Offset + dynamic->FileSize; offset += 16) { + const auto tag = Io::ReadU64(bytes, offset); + const auto value = Io::ReadU64(bytes, offset + 8); + if (tag == 0) { terminated = true; break; } + if (tag == 1) needed.push_back(value); + else if (tag < 0x60000000 || tag == 0x6100003f || (tag >= 0x61000027 && tag <= 0x6100003b)) { + if (!tags.emplace(tag, value).second) fail("Duplicate dynamic tag " + std::to_string(tag)); + } + } + if (!terminated) fail("Unterminated dynamic segment"); + for (const auto unsupported : {15u, 16u, 17u, 18u, 19u, 22u, 35u, 36u, 37u}) { + if (tags.contains(unsupported)) fail("Unsupported dynamic tag " + std::to_string(unsupported)); + } + if (tags.contains(30) && (tags.at(30) & ~8ull) != 0) fail("Unsupported guest dynamic flags"); + const auto mapped = [&](std::uint64_t address, std::uint64_t size, std::uint32_t flags) { + for (const auto& header : image.Headers) { + if (header.Type == 1 && (header.Flags & flags) == flags && address >= header.MappedAddress && address - header.MappedAddress <= header.MemorySize && size <= header.MemorySize - (address - header.MappedAddress)) return; + } + fail("Unmapped or inaccessible guest address " + std::to_string(address)); + }; + const auto translate = [&](std::uint64_t address, std::uint64_t size) { + for (const auto& header : image.Headers) { + if (header.Type == 1 && address >= header.MappedAddress && address - header.MappedAddress <= header.FileSize && size <= header.FileSize - (address - header.MappedAddress)) return header.Offset + address - header.MappedAddress; + } + fail("Unmapped ELF address " + std::to_string(address)); + return std::uint64_t{}; + }; + const auto get = [&](std::uint64_t standard, std::uint64_t sce) { + if (tags.contains(standard) == tags.contains(sce)) fail("Missing or ambiguous dynamic tag " + std::to_string(standard)); + return tags.at(tags.contains(standard) ? standard : sce); + }; + const auto table = [&](std::uint64_t standard, std::uint64_t sce, std::uint64_t size) { + const auto value = get(standard, sce); + if (tags.contains(standard)) return translate(value, size); + if (dynlib == nullptr || value > dynlib->FileSize || size > dynlib->FileSize - value) fail("SCE table exceeds dynamic data segment"); + return dynlib->Offset + value; + }; + const auto strSize = get(10, 0x61000037); + const auto strOffset = table(5, 0x61000035, strSize); + const auto string = [&](std::uint64_t offset) { + if (offset >= strSize) fail("String offset out of bounds"); + const auto start = bytes.begin() + static_cast(strOffset + offset); + const auto end = bytes.begin() + static_cast(strOffset + strSize); + const auto zero = std::find(start, end, 0); + if (zero == end) fail("Unterminated ELF string"); + return std::string(start, zero); + }; + if (strSize == 0 || bytes[strOffset] != 0 || get(11, 0x6100003b) != 24) fail("Invalid string or symbol table"); + std::uint64_t symSize = 0; + if (tags.contains(0x6100003f)) symSize = tags.at(0x6100003f); + else if (tags.contains(4)) symSize = static_cast(Io::ReadU32(bytes, translate(tags.at(4), 8) + 4)) * 24; + else fail("Missing dynamic symbol count"); + if (symSize == 0 || symSize % 24 != 0 || symSize / 24 > std::numeric_limits::max()) fail("Invalid dynamic symbol count"); + const auto symOffset = table(6, 0x61000039, symSize); + image.Dynamic.DynSymData.assign(bytes.begin() + symOffset, bytes.begin() + symOffset + symSize); + image.Dynamic.DynStrData.push_back(0); + std::set exports; + for (std::uint64_t offset = 0; offset < symSize; offset += 24) { + auto name = string(Io::ReadU32(bytes, symOffset + offset)); + name = name.substr(0, name.find('#')); + const auto info = bytes[symOffset + offset + 4]; + const auto visibility = bytes[symOffset + offset + 5]; + const auto section = Io::ReadU16(bytes, symOffset + offset + 6); + const auto value = Io::ReadU64(bytes, symOffset + offset + 8); + const auto size = Io::ReadU64(bytes, symOffset + offset + 16); + if (offset == 0 && (info != 0 || visibility != 0 || section != 0 || value != 0 || size != 0 || !name.empty())) fail("Invalid null symbol"); + if (offset == 0) { + image.Symbols.push_back({{}, 0, 0, 0, 0, 0}); + continue; + } + if (offset != 0 && ((info >> 4) > 2 || (visibility & ~3u) != 0 || ((info & 15) != 0 && (info & 15) != 1 && (info & 15) != 2 && (info & 15) != 6))) fail("Unsupported symbol attributes: " + name); + if (section != 0 && (info >> 4) != 0 && visibility != 1 && visibility != 2) { + if (name.empty() || !exports.insert(name).second) fail("Duplicate or empty export after stripping #: " + name); + } + if ((info & 15) == 6 && section != 0 && (tls == nullptr || value > tls->MemorySize || size > tls->MemorySize - value)) fail("TLS symbol exceeds TLS segment: " + name); + if (section != 0 && (info & 15) != 6) { + if (section >= 0xff00) fail("Unsupported special symbol section: " + name); + mapped(value, std::max(size, 1), (info & 15) == 2 ? 1 : 0); + } + if (image.Dynamic.DynStrData.size() > std::numeric_limits::max()) fail("String table too large"); + Io::WriteU32(image.Dynamic.DynSymData, offset, static_cast(image.Dynamic.DynStrData.size())); + Io::AppendString(image.Dynamic.DynStrData, name); + image.Symbols.push_back({name, info, visibility, section, value, size}); + } + std::set dependencies; + for (const auto offset : needed) { + const auto name = string(offset); + if (name.empty() || name.find_first_of("/\\:$") != std::string::npos || !dependencies.insert(name).second) fail("Invalid or duplicate dependency: " + name); + image.Dependencies.push_back(name); + } + std::map relocationTargets; + const auto copyRelocations = [&](std::uint64_t addressTag, std::uint64_t sceAddressTag, std::uint64_t sizeTag, std::uint64_t sceSizeTag, std::vector& output, bool plt) { + if (!tags.contains(addressTag) && !tags.contains(sceAddressTag) && !tags.contains(sizeTag) && !tags.contains(sceSizeTag)) return; + const auto size = get(sizeTag, sceSizeTag); + if (size % 24 != 0) fail("Invalid relocation table size"); + const auto offset = table(addressTag, sceAddressTag, size); + output.assign(bytes.begin() + offset, bytes.begin() + offset + size); + for (std::uint64_t index = 0; index < size; index += 24) { + const auto info = Io::ReadU64(output, index + 8); + const auto relocation = static_cast(info); + if ((info >> 32) >= image.Symbols.size() || (plt && relocation != 7) || (relocation != 1 && relocation != 6 && relocation != 7 && relocation != 8 && relocation != 16 && relocation != 17 && relocation != 18)) fail("Unsupported relocation or symbol index"); + const auto target = Io::ReadU64(output, index); + const auto addend = Io::ReadU64(output, index + 16); + mapped(target, 8, 2); + const auto next = relocationTargets.lower_bound(target); + if ((next != relocationTargets.end() && next->first < target + 8) || (next != relocationTargets.begin() && std::prev(next)->second > target)) fail("Overlapping guest relocations"); + relocationTargets.emplace(target, target + 8); + if (relocation == 8) { + if ((info >> 32) != 0) fail("RELATIVE relocation has a symbol"); + mapped(addend, 0, 0); + } else if (relocation == 1 || relocation == 6 || relocation == 7) { + const auto& symbol = image.Symbols[info >> 32]; + if ((info >> 32) == 0 || (symbol.Info & 15) == 6 || (relocation != 1 && addend != 0) || (symbol.Section == 0 && symbol.Name.empty())) fail("Invalid guest symbol relocation"); + } else { + const auto& symbol = image.Symbols[info >> 32]; + if (((info >> 32) == 0 && tls == nullptr) || ((info >> 32) != 0 && (symbol.Info & 15) != 6) || (relocation == 16 && addend != 0)) fail("Invalid guest TLS relocation"); + } + } + }; + if (tags.contains(7) || tags.contains(0x6100002f)) { + if (get(9, 0x61000033) != 24) fail("Invalid RELA entry size"); + } + copyRelocations(7, 0x6100002f, 8, 0x61000031, image.Dynamic.RelaData, false); + copyRelocations(23, 0x61000029, 2, 0x6100002d, image.Dynamic.RelaPltData, true); + if (!image.Dynamic.RelaPltData.empty() && get(20, 0x6100002b) != 7) fail("Unsupported PLT relocation format"); + if (tags.contains(3) || tags.contains(0x61000027)) image.Got = get(3, 0x61000027); + if (tags.contains(12)) image.Init = tags.at(12); + if (tags.contains(13)) image.Fini = tags.at(13); + if (image.Init != 0) mapped(image.Init, 1, 1); + if (image.Fini != 0) mapped(image.Fini, 1, 1); + if ((tags.contains(27) && tags.at(27) != 0) || (tags.contains(28) && tags.at(28) != 0)) fail("Separate guest INIT_ARRAY/FINI_ARRAY is not supported"); + if (tags.contains(33) && tags.at(33) != 0 && image.Init == 0) fail("Guest PREINIT_ARRAY has no module initializer"); + image.Bytes = std::move(bytes); + return image; +} + +} diff --git a/core/relinker/relinker/src/guest/GuestModuleBuilder.cpp b/core/relinker/relinker/src/guest/GuestModuleBuilder.cpp new file mode 100644 index 000000000..df86edccc --- /dev/null +++ b/core/relinker/relinker/src/guest/GuestModuleBuilder.cpp @@ -0,0 +1,156 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Relinker { + +std::vector GuestModuleBuilder::Build(const std::filesystem::path& inputPath, const std::filesystem::path& outputPath, Domain::SysVDynamicSection& dynamic, const bool windows, const bool toIntel, const bool skipSyscallCheck, const bool lazyBinding, const std::string& runPath) const { + const auto root = std::filesystem::absolute(inputPath).parent_path(); + const auto singular = root / "sce_module"; + const auto plural = root / "sce_modules"; + const bool hasSingular = std::filesystem::exists(singular); + const bool hasPlural = std::filesystem::exists(plural); + if (hasSingular && hasPlural) throw Domain::RelinkerException("Both sce_module and sce_modules exist beside the input executable"); + if (!hasSingular && !hasPlural) { + std::cout << "WARNING: sce_module not found beside the input executable; it may be unnecessary or missing.\n"; + return {}; + } + const auto directory = hasSingular ? singular : plural; + if (!std::filesystem::is_directory(directory)) throw Domain::RelinkerException("Guest module path is not a directory: " + directory.string()); + std::vector paths; + for (const auto& entry : std::filesystem::directory_iterator(directory)) { + if (!entry.is_regular_file()) continue; + std::ifstream stream(entry.path(), std::ios::binary); + if (!stream) throw Domain::RelinkerException("Cannot read guest candidate: " + entry.path().string()); + char magic[4]{}; + stream.read(magic, 4); + if (stream.bad()) throw Domain::RelinkerException("Cannot read guest candidate magic: " + entry.path().string()); + if (stream.gcount() == 4 && static_cast(magic[0]) == 0x7f && magic[1] == 'E' && magic[2] == 'L' && magic[3] == 'F') paths.push_back(entry.path()); + } + std::sort(paths.begin(), paths.end()); + if (paths.empty()) return {}; + if (lazyBinding) throw Domain::RelinkerException("Guest modules require eager binding; --lazy-binding is incompatible"); + std::vector images; + std::map exports; + std::set outputNames; + Io::FileReader reader; + for (const auto& path : paths) { + auto image = GuestImageReader().Read(path, reader.Read(path.string())); + if (image.OutputName.find_first_of("$\r\n") != std::string::npos) throw Domain::RelinkerException("Unsupported guest filename: " + image.OutputName); + std::string folded = image.OutputName; + if (windows) { + for (auto& value : folded) { + if (static_cast(value) >= 128 || value == ':' || value == '$') throw Domain::RelinkerException("Unsupported Windows guest filename: " + image.OutputName); + if (value >= 'A' && value <= 'Z') value = static_cast(value + ('a' - 'A')); + } + } + if (!outputNames.insert(folded).second) throw Domain::RelinkerException("Conflicting guest output filename: " + image.OutputName); + for (const auto& symbol : image.Symbols) { + if (symbol.Section == 0 || (symbol.Info >> 4) == 0 || symbol.Visibility == 1 || symbol.Visibility == 2) continue; + const auto [existing, inserted] = exports.emplace(symbol.Name, images.size()); + if (!inserted) throw Domain::RelinkerException("Duplicate guest export after stripping #: " + symbol.Name + " in " + images.at(existing->second).SourcePath.string() + " and " + path.string()); + } + std::vector codeHeaders; + for (const auto& header : image.Headers) if (header.Type == 1 && (header.Flags & 1) != 0) codeHeaders.push_back(header); + if (toIntel) image.Bytes = Codegen::MakeAmd64OnlyConverter()->Convert(std::move(image.Bytes), codeHeaders).Bytes; + if (!skipSyscallCheck) { + const auto scanner = MakeSyscallScanner(); + for (const auto& header : codeHeaders) { + const std::vector code(image.Bytes.begin() + header.Offset, image.Bytes.begin() + header.Offset + header.FileSize); + scanner->ScanCodeSectionForSyscalls(code, header.MappedAddress, header.FileSize); + } + } + images.push_back(std::move(image)); + } + std::vector> dependencies(images.size()); + for (auto& image : images) image.UsePlatformTlsResolver = !exports.contains("vNe1w4diLCs"); + for (std::size_t index = 0; index < images.size(); ++index) { + for (const auto& symbol : images[index].Symbols) { + if (symbol.Section != 0 || symbol.Name.empty()) continue; + const auto found = exports.find(symbol.Name); + if (found != exports.end()) { + const auto& provider = images[found->second]; + const auto exported = std::find_if(provider.Symbols.begin(), provider.Symbols.end(), [&](const auto& candidate) { return candidate.Section != 0 && candidate.Name == symbol.Name && (candidate.Info >> 4) != 0 && candidate.Visibility != 1 && candidate.Visibility != 2; }); + if (exported == provider.Symbols.end() || ((symbol.Info & 15) != 0 && (symbol.Info & 15) != (exported->Info & 15))) throw Domain::RelinkerException("Guest import/export type mismatch: " + symbol.Name); + if (found->second != index) dependencies[index].insert(found->second); + } else if (windows && (symbol.Info & 15) == 6) throw Domain::RelinkerException("Windows guest TLS import requires a guest TLS export: " + symbol.Name); + } + } + std::vector order; + std::vector states(images.size()); + const std::function visit = [&](std::size_t index) { + if (states[index] == 1) throw Domain::RelinkerException("Cyclic guest initialization dependency: " + images[index].SourcePath.string()); + if (states[index] == 2) return; + states[index] = 1; + for (const auto dependency : dependencies[index]) visit(dependency); + states[index] = 2; + order.push_back(index); + }; + for (std::size_t index = 0; index < images.size(); ++index) visit(index); + std::vector hostLibraries; + std::set uniqueHosts; + const auto addHost = [&](const std::string& name) { + if (name.empty() || name.find_first_of("/\\:$") != std::string::npos) throw Domain::RelinkerException("Invalid host dependency: " + name); + if (uniqueHosts.insert(name).second) hostLibraries.push_back(name); + }; + if (dynamic.DynamicSegmentData.size() % 16 != 0) throw Domain::RelinkerException("Invalid executable dependency table"); + for (std::size_t offset = 0; offset < dynamic.DynamicSegmentData.size(); offset += 16) { + if (Io::ReadU64(dynamic.DynamicSegmentData, offset) != 1) throw Domain::RelinkerException("Unexpected executable dependency tag"); + const auto nameOffset = Io::ReadU64(dynamic.DynamicSegmentData, offset + 8); + if (nameOffset >= dynamic.DynStrData.size()) throw Domain::RelinkerException("Invalid dependency string offset"); + const auto start = dynamic.DynStrData.begin() + nameOffset; + const auto end = std::find(start, dynamic.DynStrData.end(), 0); + if (end == dynamic.DynStrData.end()) throw Domain::RelinkerException("Unterminated dependency string"); + addHost(std::string(start, end)); + } + for (const auto& image : images) for (const auto& dependency : image.Dependencies) addHost(dependency); + dynamic.DynamicSegmentData.clear(); + const auto addNeeded = [&](const std::string& name) { + Io::AppendU64(dynamic.DynamicSegmentData, 1); + Io::AppendU64(dynamic.DynamicSegmentData, dynamic.DynStrData.size()); + Io::AppendString(dynamic.DynStrData, name); + }; + const auto relativeDirectory = directory.filename().generic_string(); + for (const auto index : order) if (!windows) addNeeded("$ORIGIN/" + relativeDirectory + "/" + images[index].OutputName); + for (const auto& name : hostLibraries) addNeeded(name); + std::string guestRunPath = runPath; + if (!windows) { + if (guestRunPath == "$ORIGIN") guestRunPath = "$ORIGIN/.."; + else if (guestRunPath.starts_with("$ORIGIN/")) guestRunPath.insert(8, "../"); + else if (!std::filesystem::path(guestRunPath).is_absolute()) throw Domain::RelinkerException("Guest Linux run path must be absolute or begin with $ORIGIN"); + } + std::vector artifacts; + const auto destination = std::filesystem::absolute(outputPath).parent_path() / directory.filename(); + if (std::filesystem::exists(destination) && std::filesystem::equivalent(destination, directory)) throw Domain::RelinkerException("Guest output directory must differ from the source module directory"); + for (const auto index : order) { + const auto& image = images[index]; + const auto target = destination / image.OutputName; + if (target.lexically_normal() == std::filesystem::absolute(outputPath).lexically_normal()) throw Domain::RelinkerException("Guest output collides with the executable output"); + for (const auto& source : paths) if (std::filesystem::exists(target) && std::filesystem::equivalent(source, target)) throw Domain::RelinkerException("Guest output would overwrite an input module: " + target.string()); + if (std::filesystem::exists(target) && std::filesystem::equivalent(inputPath, target)) throw Domain::RelinkerException("Guest output would overwrite the input executable"); + Domain::GuestRuntime runtime; + runtime.UsePlatformTlsResolver = image.UsePlatformTlsResolver; + runtime.Path = relativeDirectory + "/" + image.OutputName; + std::vector output; + if (windows) output = Elfpatcher::GuestModuleWriter().WriteWindows(image, runtime); + else { + std::vector needed; + for (const auto dependency : dependencies[index]) needed.push_back("$ORIGIN/" + images[dependency].OutputName); + needed.insert(needed.end(), hostLibraries.begin(), hostLibraries.end()); + output = Elfpatcher::GuestModuleWriter().WriteLinux(image, needed, guestRunPath); + } + dynamic.GuestModules.push_back(std::move(runtime)); + artifacts.push_back({target, std::move(output)}); + } + return artifacts; +} + +}