Merge pull request #1462 from abderahmane-ai/feat/module-registry

feat(relinker): write a registry for each converted bundled module
This commit is contained in:
Adrià
2026-10-09 23:06:18 +02:00
committed by GitHub
9 changed files with 125 additions and 7 deletions
+2
View File
@@ -235,6 +235,8 @@ if(BUILD_TESTING)
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_guest_module_directories.py $<TARGET_FILE:relinker>)
add_test(NAME guest_symbol_names COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_guest_symbol_names.py $<TARGET_FILE:relinker>)
add_test(NAME guest_registry COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_guest_registry.py $<TARGET_FILE:relinker>)
add_test(NAME guest_host_libc COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_guest_host_libc.py $<TARGET_FILE:relinker>)
add_test(NAME guest_absolute_symbols COMMAND ${Python3_EXECUTABLE}
+6 -1
View File
@@ -97,7 +97,12 @@ int main(const int argc, char* argv[]) {
if (args.writeRegistry) {
const std::filesystem::path outFsPath(absPath);
const std::string registryPath = (outFsPath.parent_path() / (outFsPath.stem().string() + ".registry.json")).string();
fileWriter.Write(registryPath, std::make_shared<Relinker::CallRegistryWriter>()->WriteCallRegistry(result.RegistryEntries));
const auto registryWriter = std::make_shared<Relinker::CallRegistryWriter>();
fileWriter.Write(registryPath, registryWriter->WriteCallRegistry(result.RegistryEntries));
for (const auto& artifact : guestArtifacts) {
const auto modulePath = outFsPath.parent_path() / (outFsPath.stem().string() + "." + artifact.Path.filename().string() + ".registry.json");
fileWriter.Write(modulePath.string(), registryWriter->WriteModuleImports(artifact.Imports));
}
}
auto byteWriter = std::make_shared<Io::ByteWriter>();
@@ -12,6 +12,7 @@ public:
virtual ~ICallRegistryWriter() = default;
virtual std::string WriteCallRegistry(const std::vector<CallRegistryEntry>& entries) = 0;
virtual std::string WriteModuleImports(const std::vector<CallRegistryEntry>& entries) = 0;
};
}
@@ -50,6 +50,7 @@ public:
struct GuestArtifact {
std::filesystem::path Path;
std::vector<std::uint8_t> Bytes;
std::vector<Domain::CallRegistryEntry> Imports;
};
class GuestModuleBuilder {
@@ -8,6 +8,7 @@ namespace Relinker {
class CallRegistryWriter : public ICallRegistryWriter {
public:
std::string WriteCallRegistry(const std::vector<CallRegistryEntry>& entries) override;
std::string WriteModuleImports(const std::vector<CallRegistryEntry>& entries) override;
};
}
@@ -171,6 +171,7 @@ 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());
std::vector<std::set<std::size_t>> systemImports(images.size());
for (auto& image : images) {
image.UsePlatformTlsResolver = !windows ? !exports.contains("vNe1w4diLCs") : std::none_of(image.Symbols.begin(), image.Symbols.end(), [](const auto& symbol) {
return symbol.Name == "vNe1w4diLCs" && symbol.Section != 0 && symbol.Section != AbsoluteSection && (symbol.Info >> 4) != 0 && symbol.Visibility != 1 && symbol.Visibility != 2;
@@ -181,7 +182,8 @@ std::vector<GuestArtifact> GuestModuleBuilder::Build(const std::filesystem::path
const auto found = findGuest(name);
if (found != guestNames.end() && found->second != index) dependencies[index].insert(found->second);
}
for (const auto& symbol : images[index].Symbols) {
for (std::size_t symbolIndex = 0; symbolIndex < images[index].Symbols.size(); ++symbolIndex) {
const auto& symbol = images[index].Symbols[symbolIndex];
if (symbol.Section != 0 || symbol.Name.empty()) continue;
rejectSharedImport(symbol.Name, images[index].SourcePath.string());
const auto found = exports.find(symbol.Name);
@@ -199,6 +201,7 @@ std::vector<GuestArtifact> GuestModuleBuilder::Build(const std::filesystem::path
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 (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);
if (providers.empty()) systemImports[index].insert(symbolIndex);
}
}
if (!windows) {
@@ -274,8 +277,17 @@ std::vector<GuestArtifact> GuestModuleBuilder::Build(const std::filesystem::path
if (provider == index && std::find(runtime.Names.begin(), runtime.Names.end(), name) == runtime.Names.end()) runtime.Names.push_back(name);
}
}
std::vector<Domain::CallRegistryEntry> imports;
for (const auto* table : {&image.Dynamic.RelaData, &image.Dynamic.RelaPltData}) {
for (std::size_t position = 0; position < table->size(); position += 24) {
const auto symbolIndex = static_cast<std::size_t>(Io::ReadU64(*table, position + 8) >> 32);
if (!systemImports[index].contains(symbolIndex)) continue;
const auto& symbol = image.Symbols[symbolIndex];
imports.push_back({symbol.Name, symbol.Library, {}, 0, {}, Io::ReadU64(*table, position), {}, false});
}
}
dynamic.GuestModules.push_back(std::move(runtime));
artifacts.push_back({target, std::move(output)});
artifacts.push_back({target, std::move(output), std::move(imports)});
}
return artifacts;
}
@@ -62,4 +62,23 @@ std::string CallRegistryWriter::WriteCallRegistry(const std::vector<CallRegistry
return out.str();
}
std::string CallRegistryWriter::WriteModuleImports(const std::vector<CallRegistryEntry>& entries) {
std::ostringstream out;
out << "[\n";
for (std::size_t i = 0; i < entries.size(); ++i) {
const auto& e = entries[i];
out << " {\n";
out << " \"nid\": " << _jsonString(e.Nid) << ",\n";
out << " \"library\": " << _jsonString(e.Library) << ",\n";
out << " \"targetOffset\": " << _hexOffset(e.TargetOffset) << "\n";
out << " }";
if (i + 1 < entries.size()) out << ",";
out << "\n";
}
out << "]\n";
return out.str();
}
}
@@ -0,0 +1,77 @@
import json
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
from test_guest_intel_trampolines import main_fixture
from test_guest_symbol_names import guest_module, importing_executable
RELA = 0x900
RELASZ = 0x668
PLT = 0x940
GLOB_DAT = 6
JUMP_SLOT = 7
def libc_module():
image = guest_module([("AAAAAAAAAAA#A#A", True), ("BBBBBBBBBBB#B#B", False), ("CCCCCCCCCCC#C#C", False), ("EEEEEEEEEEE", True)])
relocations = [(0x2380, 2, GLOB_DAT), (0x2388, 3, GLOB_DAT)]
for index, (target, symbol, kind) in enumerate(relocations):
struct.pack_into("<QQq", image, RELA + index * 24, target, (symbol << 32) | kind, 0)
struct.pack_into("<Q", image, RELASZ, len(relocations) * 24)
struct.pack_into("<QQq", image, PLT, 0x2390, (3 << 32) | JUMP_SLOT, 0)
for index, tag in enumerate([(23, 0x2340), (2, 24), (20, 7), (0, 0)], 8):
struct.pack_into("<qQ", image, 0x600 + index * 16, *tag)
struct.pack_into("<QQ", image, 208, 12 * 16, 12 * 16)
return image
def convert(relinker, case, options, sibling=True, registry=True):
(case / "sce_module").mkdir(parents=True)
source = case / "input.elf"
source.write_bytes(main_fixture() if "--windows" in options else importing_executable(["AAAAAAAAAAA#A#A", "DDDDDDDDDDD#D#D"]))
(case / "sce_module" / "libc.prx").write_bytes(libc_module())
if sibling:
(case / "sce_module" / "other.prx").write_bytes(guest_module([("BBBBBBBBBBB#B#B", True), ("EEEEEEEEEEE", True)]))
output = case / "output.elf"
result = subprocess.run([str(relinker), *(["--registry"] if registry else []), *options, str(source), str(output)], capture_output=True, text=True, timeout=30)
assert result.returncode == 0, (options, result.stdout, result.stderr)
return output
def read(path):
return json.loads(path.read_text(encoding="utf-8"))
def entry(nid, offset):
return {"nid": nid, "library": "", "targetOffset": offset}
def main():
relinker = Path(sys.argv[1]).resolve()
with tempfile.TemporaryDirectory(prefix="anyps5-guest-registry-") as directory:
work = Path(directory)
for name, options in (("linux", []), ("windows", ["--windows"])):
output = convert(relinker, work / name, options)
libc = read(output.parent / "output.libc.prx.guest.prx.registry.json")
assert libc == [entry("CCCCCCCCCCC", "0x2388"), entry("CCCCCCCCCCC", "0x2390")], (name, libc)
other = read(output.parent / "output.other.prx.guest.prx.registry.json")
assert other == [], (name, other)
main_nids = [item["nid"] for item in read(output.parent / "output.registry.json")]
expected = [] if options else ["AAAAAAAAAAA#A#A", "DDDDDDDDDDD#D#D"]
assert main_nids == expected, (name, main_nids)
alone = convert(relinker, work / (name + "-alone"), options, sibling=False)
libc = read(alone.parent / "output.libc.prx.guest.prx.registry.json")
assert libc == [entry("BBBBBBBBBBB", "0x2380"), entry("CCCCCCCCCCC", "0x2388"), entry("CCCCCCCCCCC", "0x2390")], (name, libc)
plain = convert(relinker, work / (name + "-plain"), options, registry=False)
written = sorted(path.name for path in plain.parent.glob("*.registry.json"))
assert written == [], (name, written)
print("Guest module registry tests passed")
if __name__ == "__main__":
main()
+4 -4
View File
@@ -42,7 +42,7 @@ All switches are disabled by default. `unused-filter` defaults to `0`; `--rpath`
| `unused-filter=0` | Keep all imported NID references. |
| `unused-filter=1` | Filter unused non-PLT imports using control-flow and GOT access analysis; preserve PLT imports. |
| `unused-filter=2` | Apply strict unused-import analysis and compact the PLT. Unsupported analysis cases cause an error. |
| `--registry` | Write `<output-stem>.registry.json` beside the output executable. |
| `--registry` | Write `<output-stem>.registry.json` beside the output executable, and `<output-stem>.<module>.registry.json` for each converted bundled module. |
| `--rpath <path>` | Set the system library search path. Quote `$ORIGIN` to prevent shell expansion, for example `--rpath '$ORIGIN/libs'` in Bash or PowerShell. Linux guest modules require an absolute path or a path beginning with `$ORIGIN`. Windows requires a nonempty ASCII path and supports `$ORIGIN` as the executable directory. |
| `--autorun` | Run the output after conversion, print its exit code, and wait for Enter. Adds executable permissions for Linux output. Requires the target OS and prepared runtime layout. |
| `--skip-sce-module` | Deprecated. Skip all bundled module processing. |
@@ -105,10 +105,10 @@ The game runs on the first Vulkan 1.1 device with graphics and compute queues an
```sh
relinker --registry source/input.elf app.elf
python3 tools/import_audit.py app.registry.json --libs build/core/libs/libs --modules source/sce_module
python3 tools/import_audit.py app.registry.json app.libc.prx.guest.prx.registry.json --libs build/core/libs/libs --modules source/sce_module
```
`--registry` writes `app.registry.json` beside the output. `--libs` is the directory the `libs` target fills ([build instructions](../dev/BUILD.md)); the exports are read from the built `.prx` files, so the result matches what the loader finds. Imports are counted once per NID and library, and every reference lands in exactly one class:
`--registry` writes `app.registry.json` for the executable and one `app.<module>.registry.json` for each converted bundled module; pass all of them. `--libs` is the directory the `libs` target fills ([build instructions](../dev/BUILD.md)); the exports are read from the built `.prx` files, so the result matches what the loader finds. Imports are counted once per NID and library, and every reference lands in exactly one class:
| Class | Meaning |
|-------|---------|
@@ -129,4 +129,4 @@ The report also lists needed libraries that have no file in `--libs` or `--modul
Exit codes: `0` nothing blocks loading, `1` there are `absent` imports or needed libraries without a file, `2` an input could not be read; the message names the file and the value.
The registry lists the imports of the executable, not of its bundled modules.
A module registry lists `nid`, `library` and `targetOffset` for each relocation against a function that no other bundled module exports, without the `#` suffix of the executable's NIDs.