fix(relinker): bind Windows imports to their declared modules

This commit is contained in:
Nicolas Abosch
2026-10-05 12:11:04 -03:00
parent fe98276fb0
commit bf0ee4019d
16 changed files with 249 additions and 29 deletions
+2
View File
@@ -224,6 +224,8 @@ if(BUILD_TESTING)
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_guest_host_libc.py $<TARGET_FILE:relinker>)
add_test(NAME guest_absolute_symbols COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_guest_absolute_symbols.py $<TARGET_FILE:relinker>)
add_test(NAME windows_import_modules COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_windows_import_modules.py $<TARGET_FILE:relinker>)
add_test(NAME elf_header COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_elf_header.py $<TARGET_FILE:relinker>)
add_test(NAME input_magic COMMAND ${Python3_EXECUTABLE}
@@ -12,6 +12,7 @@ struct GuestImport {
std::uint32_t TargetRva;
std::uint64_t Addend;
std::uint32_t RelocationType = 1;
std::string Library;
};
struct GuestRuntime {
@@ -22,6 +23,7 @@ struct GuestRuntime {
std::uint32_t InitRva = 0;
std::uint32_t FiniRva = 0;
bool UsePlatformTlsResolver = true;
std::vector<std::string> Names;
};
}
@@ -0,0 +1,35 @@
#ifndef DOMAIN_IMPORTMODULE_HPP
#define DOMAIN_IMPORTMODULE_HPP
#include <domain/Types.hpp>
#include <string_view>
namespace Domain {
inline std::string ImportModule(const std::string& symbol, const std::map<std::uint64_t, std::string>& modules) {
if (modules.empty()) return {};
const auto first = symbol.find('#');
if (first == std::string::npos) return {};
const auto second = symbol.find('#', first + 1);
if (second == std::string::npos || second + 1 == symbol.size())
throw RelinkerException("Invalid qualified import: " + symbol);
constexpr std::string_view alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-";
std::uint64_t id = 0;
for (const char character : std::string_view(symbol).substr(second + 1)) {
const auto digit = alphabet.find(character);
if (digit == std::string_view::npos || id > (65535u - digit) / 64u)
throw RelinkerException("Invalid import module ID: " + symbol);
id = id * 64u + digit;
}
const auto module = modules.find(id);
if (module == modules.end()) throw RelinkerException("Unknown import module ID: " + symbol);
auto name = module->second;
if (name.empty() || name.find_first_of("/\\:$\r\n") != std::string::npos)
throw RelinkerException("Invalid import module name: " + name);
if (!name.ends_with(".prx")) name += ".prx";
return name;
}
}
#endif
@@ -95,6 +95,7 @@ struct SysVDynamicSection {
std::vector<std::uint8_t> RelaData;
std::vector<std::uint8_t> RelaPltData;
std::vector<GuestRuntime> GuestModules;
std::map<VirtualAddress, std::string> ImportModules;
};
struct CallRegistryEntry {
@@ -34,6 +34,7 @@ struct PeImport {
std::uint64_t Addend;
std::int32_t TargetModule = -1;
std::uint32_t RelocationType = 1;
std::string Library;
};
struct PeRelocations {
@@ -5,6 +5,7 @@
#include <io/BufferUtils.hpp>
#include <algorithm>
#include <optional>
#include <filesystem>
namespace Elfpatcher::Windows {
@@ -85,6 +86,35 @@ WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, con
for (const auto& import : imports)
symbolNames.push_back(addString(import.Name));
std::vector<std::uint32_t> searchTables;
std::vector<std::uint32_t> searchCounts;
std::vector<bool> platformTlsResolvers;
for (const auto& import : imports) {
std::vector<std::uint32_t> order;
for (std::size_t index = 0; index < libraries.size(); ++index) {
auto name = std::filesystem::path(libraries[index]).filename().string();
if (name.ends_with(".guest.prx")) name.resize(name.size() - 10);
const bool guestName = index < guestModules.size() &&
std::find(guestModules[index].Names.begin(), guestModules[index].Names.end(), import.Library) != guestModules[index].Names.end();
if (import.Library.empty() || name == import.Library || guestName) order.push_back(CheckedRva(index));
}
if (order.empty()) throw Domain::RelinkerException("Import module is not a dependency: " + import.Library);
const bool hostModule = !import.Library.empty() &&
std::any_of(order.begin(), order.end(), [&](auto index) { return index >= guestModules.size(); });
if (hostModule) {
for (std::size_t index = guestModules.size(); index < libraries.size(); ++index) {
if (libraries[index] == "libc.prx" && import.Library != "libc.prx") order.push_back(CheckedRva(index));
}
}
Io::AlignBuffer(data, 4);
platformTlsResolvers.push_back(std::none_of(order.begin(), order.end(), [&](auto index) {
return index < guestModules.size() && !guestModules[index].UsePlatformTlsResolver;
}));
searchTables.push_back(CheckedRva(dataRva + data.size()));
searchCounts.push_back(CheckedRva(order.size()));
for (const auto index : order) Io::AppendU32(data, index);
}
const auto lastError = reserve(4);
const auto errorDigits = reserve(11);
const auto errorMessage = reserve(ErrorMessageCapacity);
@@ -105,7 +135,8 @@ WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, con
const auto diagnosticsOffset = data.size();
std::vector<std::string> errors = {"FAIL: cannot obtain executable path\n", "FAIL: executable or library path is too long\n", "FAIL: executable path has no directory\n"};
for (const auto& import : imports)
errors.push_back("FAIL: unresolved ELF import " + import.Name + "\n");
errors.push_back("FAIL: unresolved ELF import " + import.Name +
(import.Library.empty() ? std::string{} : " from " + import.Library) + "\n");
const auto argumentError = errors.size();
errors.push_back("FAIL: cannot prepare command-line arguments\n");
std::vector<std::uint32_t> errorRvas;
@@ -291,7 +322,7 @@ WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, con
std::vector<std::size_t> lazyUnresolvedImports;
std::vector<std::size_t> tlsResolverAddresses;
for (std::size_t index = 0; index < imports.size(); ++index) {
if (!guestModules.empty() && guestModules.front().UsePlatformTlsResolver && imports[index].Name == "vNe1w4diLCs") {
if (!guestModules.empty() && platformTlsResolvers[index] && 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);
@@ -299,14 +330,15 @@ WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, con
}
code.Rip({0x48, 0x8d, 0x1d}, handles);
code.Rip({0x48, 0x8d, 0x35}, symbolNames[index]);
code.Rip({0x48, 0x8d, 0x3d}, searchTables[index]);
code.Emit({0xbd});
code.U32(CheckedRva(libraries.size()));
code.U32(searchCounts[index]);
const auto search = code.GetRva();
code.Emit({0x48, 0x8b, 0x0b, 0x48, 0x89, 0xf2});
code.Emit({0x8b, 0x0f, 0x48, 0x8b, 0x0c, 0xcb, 0x48, 0x89, 0xf2});
call("GetProcAddress");
code.Emit({0x48, 0x85, 0xc0});
const auto resolved = code.Branch({0x0f, 0x85});
code.Emit({0x48, 0x83, 0xc3, 8, 0xff, 0xcd});
code.Emit({0x48, 0x83, 0xc7, 4, 0xff, 0xcd});
code.Rip({0x0f, 0x85}, search);
if (lazyBinding) {
lazyUnresolvedImports.push_back(index);
@@ -47,13 +47,13 @@ std::vector<std::uint8_t> GuestModuleWriter::WriteWindows(const Relinker::GuestI
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});
runtime.Imports.push_back({symbol.Name, rva, 0, 16, symbol.Library});
} 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});
runtime.Imports.push_back({symbol.Name, rva, addend, 17, symbol.Library});
} 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; });
@@ -70,7 +70,7 @@ std::vector<std::uint8_t> GuestModuleWriter::WriteWindows(const Relinker::GuestI
} else {
if (symbol.Name.empty()) throw Domain::RelinkerException("Empty guest import", target);
image.WritePointer(target, 0);
runtime.Imports.push_back({symbol.Name, rva, addend});
runtime.Imports.push_back({symbol.Name, rva, addend, 1, symbol.Library});
}
} else throw Domain::RelinkerException("Unsupported Windows guest relocation " + std::to_string(type), target);
}
@@ -83,7 +83,7 @@ std::vector<std::uint8_t> WindowsPePatcher::Patch(const std::vector<std::uint8_t
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<std::int32_t>(index), import.RelocationType});
for (const auto& import : module.Imports) relocations.Imports.push_back({import.Name, import.TargetRva, import.Addend, static_cast<std::int32_t>(index), import.RelocationType, import.Library});
}
libraries.insert(libraries.begin(), guestPaths.begin(), guestPaths.end());
if (dependencyDiagnostics)
@@ -45,6 +45,8 @@ PeRelocations WindowsRelocationBuilder::Apply(WindowsLoadImage& image, const Dom
image.RequireWritable(target, 8);
image.WritePointer(target, 0);
result.Imports.push_back({name, rva, addend});
if (const auto module = dynamicSection.ImportModules.find(target); module != dynamicSection.ImportModules.end())
result.Imports.back().Library = module->second;
}
};
applyTable(dynamicSection.RelaData, false);
@@ -21,6 +21,7 @@ struct GuestSymbol {
std::uint16_t Section;
std::uint64_t Value;
std::uint64_t Size;
std::string Library;
};
struct GuestImage {
@@ -7,6 +7,7 @@
#include <iterator>
#include <set>
#include <sstream>
#include <domain/ImportModule.hpp>
namespace Relinker {
@@ -61,12 +62,14 @@ GuestImage GuestImageReader::Read(const std::filesystem::path& path, std::vector
if (loads.empty() || dynamic == nullptr || dynamic->FileSize % 16 != 0) fail("Missing or invalid ELF load/dynamic segments");
std::map<std::uint64_t, std::uint64_t> tags;
std::vector<std::uint64_t> needed;
std::vector<std::uint64_t> moduleImports;
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 == 0x61000045) moduleImports.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));
}
@@ -118,9 +121,13 @@ GuestImage GuestImageReader::Read(const std::filesystem::path& path, std::vector
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::map<std::uint64_t, std::string> importModules;
for (const auto value : moduleImports)
if (!importModules.emplace(value >> 48, string(value & 0xffffffffu)).second) fail("Duplicate import module ID");
std::set<std::string> exports;
for (std::uint64_t offset = 0; offset < symSize; offset += 24) {
auto name = string(Io::ReadU32(bytes, symOffset + offset));
const auto library = Io::ReadU16(bytes, symOffset + offset + 6) == 0 ? Domain::ImportModule(name, importModules) : std::string{};
name = name.substr(0, name.find('#'));
const auto info = bytes[symOffset + offset + 4];
const auto visibility = bytes[symOffset + offset + 5];
@@ -144,7 +151,7 @@ GuestImage GuestImageReader::Read(const std::filesystem::path& path, std::vector
if (image.Dynamic.DynStrData.size() > std::numeric_limits<std::uint32_t>::max()) fail("String table too large");
Io::WriteU32(image.Dynamic.DynSymData, offset, static_cast<std::uint32_t>(image.Dynamic.DynStrData.size()));
Io::AppendString(image.Dynamic.DynStrData, name);
image.Symbols.push_back({name, info, visibility, section, value, size});
image.Symbols.push_back({name, info, visibility, section, value, size, library});
}
if (tags.contains(14)) {
image.Soname = string(tags.at(14));
@@ -49,7 +49,7 @@ std::vector<GuestArtifact> GuestModuleBuilder::Build(const std::filesystem::path
if (paths.empty()) return {};
if (lazyBinding) throw Domain::RelinkerException("Guest modules require eager binding; --lazy-binding is incompatible");
std::vector<GuestImage> images;
std::map<std::string, std::size_t> exports;
std::map<std::string, std::vector<std::size_t>> exports;
std::map<std::string, std::set<std::size_t>> sharedExports;
std::set<std::string> outputNames;
Io::FileReader reader;
@@ -66,12 +66,9 @@ std::vector<GuestArtifact> GuestModuleBuilder::Build(const std::filesystem::path
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.Section == AbsoluteSection || (symbol.Info >> 4) == 0 || symbol.Visibility == 1 || symbol.Visibility == 2) continue;
const auto [existing, inserted] = exports.emplace(symbol.Name, images.size());
if (inserted) continue;
if (windows || existing->second == images.size()) throw Domain::RelinkerException("Duplicate guest export after stripping #: " + symbol.Name + " in " + images.at(existing->second).SourcePath.string() + " and " + path.string());
auto& providers = sharedExports[symbol.Name];
providers.insert(existing->second);
providers.insert(images.size());
auto& providers = exports[symbol.Name];
if (std::find(providers.begin(), providers.end(), images.size()) == providers.end()) providers.push_back(images.size());
if (!windows && providers.size() > 1) sharedExports[symbol.Name].insert(providers.begin(), providers.end());
}
std::vector<Domain::ProgramHeader> codeHeaders;
for (const auto& header : image.Headers) if (header.Type == 1 && (header.Flags & 1) != 0) codeHeaders.push_back(header);
@@ -119,7 +116,11 @@ std::vector<GuestArtifact> GuestModuleBuilder::Build(const std::filesystem::path
if (!windows && exports.contains(name)) rename(dynamic.DynSymData, dynamic.DynStrData, offset / 24, name);
}
std::vector<std::set<std::size_t>> dependencies(images.size());
for (auto& image : images) image.UsePlatformTlsResolver = !exports.contains("vNe1w4diLCs");
for (auto& image : images) {
image.UsePlatformTlsResolver = std::none_of(image.Symbols.begin(), image.Symbols.end(), [](const auto& symbol) {
return symbol.Name == "vNe1w4diLCs" && symbol.Section != 0 && (symbol.Info >> 4) != 0 && symbol.Visibility != 1 && symbol.Visibility != 2;
});
}
for (std::size_t index = 0; index < images.size(); ++index) {
for (const auto& name : images[index].Dependencies) {
const auto found = guestNames.find(name);
@@ -129,11 +130,19 @@ std::vector<GuestArtifact> GuestModuleBuilder::Build(const std::filesystem::path
if (symbol.Section != 0 || symbol.Name.empty()) continue;
rejectSharedImport(symbol.Name, images[index].SourcePath.string());
const auto found = exports.find(symbol.Name);
std::vector<std::size_t> providers;
if (found != exports.end()) {
const auto& provider = images[found->second];
for (const auto provider : found->second) {
const auto& candidate = images[provider];
if (!windows || symbol.Library.empty() || symbol.Library == candidate.SourcePath.filename().string() || symbol.Library == candidate.Soname) providers.push_back(provider);
}
}
if (providers.size() > 1) throw Domain::RelinkerException("Ambiguous guest import after stripping #: " + symbol.Name);
if (!providers.empty()) {
const auto& provider = images[providers.front()];
const auto exported = std::find_if(provider.Symbols.begin(), provider.Symbols.end(), [&](const auto& candidate) { return candidate.Section != 0 && candidate.Section != AbsoluteSection && 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);
if (providers.front() != index) dependencies[index].insert(providers.front());
} else if (windows && (symbol.Info & 15) == 6) throw Domain::RelinkerException("Windows guest TLS import requires a guest TLS export: " + symbol.Name);
}
}
@@ -202,6 +211,7 @@ std::vector<GuestArtifact> GuestModuleBuilder::Build(const std::filesystem::path
Domain::GuestRuntime runtime;
runtime.UsePlatformTlsResolver = image.UsePlatformTlsResolver;
runtime.Path = relativeDirectory + "/" + image.OutputName;
runtime.Names = {image.SourcePath.filename().string(), image.Soname};
std::vector<std::uint8_t> output;
if (windows) output = Elfpatcher::GuestModuleWriter().WriteWindows(image, runtime);
else {
@@ -85,6 +85,7 @@ SysVDynamicSection SysVDynamicSectionBuilder::BuildDynamicSection(
std::vector<const NidReference*> nonPltRefs;
for (const auto& ref : nidReferences) {
if (!ref.Library.empty()) result.ImportModules.emplace(ref.RelocationAddress, ref.Library);
std::uint32_t relType = ref.RelocationTypeValue;
if (relType == 0) relType = R_X86_64_JUMP_SLOT;
@@ -4,6 +4,7 @@
#include <sstream>
#include <iostream>
#include <cstring>
#include <domain/ImportModule.hpp>
namespace Relinker {
@@ -175,6 +176,12 @@ RelinkResult RelinkerPipeline::Relink(const std::vector<std::uint8_t>& sourceElf
if (policy) policy->RegisterLibraryImport(snd);
}
std::map<std::uint64_t, std::string> importModules;
for (const auto& tag : dynTags) {
if (tag.Tag == 0x61000045 && !importModules.emplace(tag.Value >> 48, readCStr(tag.Value & 0xffffffffu)).second)
throw RelinkerException("Duplicate import module ID");
}
auto extractRela = [&](const FileByteOffset relaOff, const ByteCount relaSize) {
for (ByteCount off = 0; off + relaEntSize <= relaSize; off += relaEntSize) {
const FileByteOffset pos = relaOff + off;
@@ -203,7 +210,8 @@ RelinkResult RelinkerPipeline::Relink(const std::vector<std::uint8_t>& sourceElf
std::uint32_t nameOff = 0;
std::memcpy(&nameOff, raw.data() + symOff, 4);
nidRefs.push_back({readCStr(nameOff), {}, relType, pos, rOffset, rAddend});
const auto name = readCStr(nameOff);
nidRefs.push_back({name, Domain::ImportModule(name, importModules), relType, pos, rOffset, rAddend});
}
};
@@ -122,12 +122,8 @@ def main():
(case / name).mkdir(parents=True)
(case / name / f"{name}.prx").write_bytes(module_with_symbol(True))
result, output = convert(case, windows)
if windows:
assert result.returncode == 2 and "Duplicate guest export" in result.stderr, result.stderr
assert not output.exists() and not (case / "app0").exists(), output
else:
assert result.returncode == 0 and output.exists(), result.stderr
assert {path.name for path in (case / "app0").rglob("*.guest.prx")} == {"sce_module.prx.guest.prx", "prx.prx.guest.prx"}
assert result.returncode == 0 and output.exists(), result.stderr
assert {path.name for path in (case / "app0").rglob("*.guest.prx")} == {"sce_module.prx.guest.prx", "prx.prx.guest.prx"}
case = work / f"{windows}-ambiguous-import"
for name in ("sce_module", "prx"):
@@ -135,8 +131,7 @@ def main():
(case / name / f"{name}.prx").write_bytes(module_with_symbol(True))
(case / "prx" / "consumer.prx").write_bytes(module_with_symbol(False))
result, output = convert(case, windows)
expected = "Duplicate guest export" if windows else "Ambiguous guest import shared"
assert result.returncode == 2 and expected in result.stderr, result.stderr
assert result.returncode == 2 and "Ambiguous guest import shared" in result.stderr, result.stderr
assert not output.exists() and not (case / "app0").exists(), output
print("Guest module directory integration tests passed")
@@ -0,0 +1,123 @@
from pathlib import Path
import os
import struct
import subprocess
import sys
import tempfile
from test_guest_intel_trampolines import main_fixture
from test_guest_module_directories import module_with_symbol
def dynamic(image, offset, phoff, tags):
for index, tag in enumerate(tags + [(0, 0)]):
struct.pack_into('<qQ', image, offset + index * 16, *tag)
struct.pack_into('<QQ', image, phoff + 32, (len(tags) + 1) * 16, (len(tags) + 1) * 16)
def provider(value, soname=None):
image = module_with_symbol(True)
code = b'\xb8' + struct.pack('<I', value) + b'\xc3'
image[0x400:0x406] = code
struct.pack_into('<Q', image, 0x898 + 16, len(code))
if soname:
strings = b'\0shared#A#B\0' + soname.encode() + b'\0'
image[0x800:0x800 + len(strings)] = strings
tags = [(5, 0x2200), (10, len(strings)), (6, 0x2280), (11, 24),
(4, 0x2240), (7, 0x2300), (8, 0), (9, 24), (14, 12)]
dynamic(image, 0x600, 176, tags)
return image
def consumer(owner, symbol='shared#A#B', expected=22):
image = module_with_symbol(False)
strings = b'\0' + symbol.encode() + b'\0' + owner.encode() + b'\0'
owner_offset = len(symbol) + 2
image[0x800:0x800 + len(strings)] = strings
tags = [(5, 0x2200), (10, len(strings)), (6, 0x2280), (11, 24),
(4, 0x2240), (7, 0x2300), (8, 24), (9, 24), (12, 0x1010),
(1, owner_offset), (0x61000045, (1 << 48) | owner_offset)]
dynamic(image, 0x600, 176, tags)
code = b'\xff\x15' + struct.pack('<i', 0x2320 - 0x1016) + bytes([0x83, 0xf8, expected, 0x74, 2, 0x0f, 0x0b, 0xc3])
image[0x410:0x410 + len(code)] = code
return image
def executable(owner, symbol='shared#A#B'):
image = main_fixture()
struct.pack_into('<I', image, 68, 7)
strings = b'\0' + symbol.encode() + b'\0' + owner.encode() + b'\0'
owner_offset = len(symbol) + 2
image[0x4800:0x4800 + len(strings)] = strings
tags = [(5, 0x4800), (10, len(strings)), (6, 0x4880), (11, 24),
(4, 0x4840), (7, 0x4900), (8, 24), (9, 24),
(1, owner_offset), (0x61000045, (1 << 48) | owner_offset)]
dynamic(image, 0x4600, 120, tags)
struct.pack_into('<IIIII', image, 0x4840, 1, 2, 1, 0, 0)
struct.pack_into('<IBBHQQ', image, 0x4898, 1, 0x12, 0, 0, 0, 0)
struct.pack_into('<QQq', image, 0x4900, 0x4a20, (1 << 32) | 6, 0)
image[0x4000:0x4007] = b'\xff\x15' + struct.pack('<i', 0x4a20 - 0x4006) + b'\xc3'
return image
def main():
relinker = Path(sys.argv[1]).resolve()
with tempfile.TemporaryDirectory(prefix='anyps5-import-modules-') as directory:
work = Path(directory)
def convert(name, owner, symbol='shared#A#B', guest_owner=None):
case = work / name
modules = case / 'prx'
modules.mkdir(parents=True)
(modules / 'a.prx').write_bytes(provider(11))
(modules / 'b.prx').write_bytes(provider(22, 'alias.prx'))
other = provider(33)
other[0x800:0x80c] = b'\0other#A#B\0\0'
(modules / 'c.prx').write_bytes(other)
if guest_owner:
(modules / 'consumer.prx').write_bytes(consumer(guest_owner, symbol))
source = case / 'input.elf'
source.write_bytes(executable(owner, symbol))
output = case / 'output.exe'
result = subprocess.run([str(relinker), '--windows', str(source), str(output)], capture_output=True, text=True, timeout=30)
return result, output
for owner in ('a.prx', 'b.prx', 'alias.prx'):
result, output = convert(owner, owner, guest_owner='b.prx')
assert result.returncode == 0, (result.stdout, result.stderr)
if os.name == 'nt':
run = subprocess.run([str(output)], capture_output=True, text=True, timeout=30)
assert run.returncode == (11 if owner == 'a.prx' else 22), (run.returncode, run.stdout, run.stderr)
for symbol, message in [('shared#A#C', 'Unknown import module ID'),
('shared#A#', 'Invalid qualified import'),
('shared#A#?', 'Invalid import module ID'),
('shared#A#BBBBBBBB', 'Invalid import module ID')]:
result, output = convert(symbol.replace('?', 'invalid'), 'b.prx', symbol)
assert result.returncode == 2 and message in result.stderr, result.stderr
assert not output.exists()
result, output = convert('legacy', 'b.prx', 'shared', guest_owner='b.prx')
assert result.returncode == 2 and 'Ambiguous guest import' in result.stderr, result.stderr
assert not output.exists()
result, output = convert('missing-symbol', 'a.prx', 'absent#A#B')
assert result.returncode == 0, result.stderr
if os.name == 'nt':
run = subprocess.run([str(output)], capture_output=True, text=True, timeout=30)
assert run.returncode != 0 and 'unresolved ELF import absent' in run.stderr, (run.returncode, run.stderr)
result, output = convert('wrong-provider', 'c.prx')
assert result.returncode == 0, result.stderr
if os.name == 'nt':
run = subprocess.run([str(output)], capture_output=True, text=True, timeout=30)
assert run.returncode != 0 and 'unresolved ELF import shared' in run.stderr, (run.returncode, run.stderr)
result, output = convert('missing-dependency', 'missing.prx')
assert result.returncode == 0, result.stderr
if os.name == 'nt':
run = subprocess.run([str(output)], capture_output=True, text=True, timeout=30)
assert run.returncode != 0 and 'Failed to load module:' in run.stderr and 'missing.prx' in run.stderr, (run.returncode, run.stderr)
print('Windows module-scoped import tests passed')
if __name__ == '__main__':
main()