fix(relinker): validate all executable segments and preserve live imports

This commit is contained in:
RomainROCH
2026-10-04 05:26:01 +02:00
parent 2cb95dab12
commit 328def4bab
4 changed files with 119 additions and 15 deletions
+2
View File
@@ -204,6 +204,8 @@ if(BUILD_TESTING)
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_elf_header.py $<TARGET_FILE:relinker>)
add_test(NAME input_magic COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_input_magic.py $<TARGET_FILE:relinker>)
add_test(NAME executable_segments COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_executable_segments.py $<TARGET_FILE:relinker>)
else()
message(STATUS "Python3 interpreter not found; skipping Python relinker tests")
endif()
@@ -69,14 +69,15 @@ public:
std::vector<FileByteOffset> ResolveCallSites(const std::vector<std::uint8_t>& textSection, FileByteOffset textSectionVAddr, VirtualAddress targetGotOrPltAddress, ByteCount targetGotOrPltSize) override;
private:
const std::vector<std::uint8_t>* _cachedTextPtr = nullptr;
std::map<VirtualAddress, FileByteOffset> _cachedTargetToInstr;
std::multimap<VirtualAddress, FileByteOffset> _cachedTargetToInstr;
FileByteOffset _cachedTextVAddr = 0;
};
std::vector<FileByteOffset> CallSiteResolver::ResolveCallSites(const std::vector<std::uint8_t>& textSection, const FileByteOffset textSectionVAddr, const VirtualAddress targetGotOrPltAddress, const ByteCount targetGotOrPltSize) {
if (textSection.empty()) return {};
if (_cachedTextPtr != &textSection) {
if (_cachedTextPtr != &textSection || _cachedTextVAddr != textSectionVAddr) {
auto scanner = Codegen::MakeInstructionScanner();
auto instructions = scanner->ScanCodeSection(textSection, textSectionVAddr, textSection.size());
auto instructions = scanner->ScanCodeSection(textSection, 0, textSection.size());
_cachedTargetToInstr.clear();
for (const auto& m : instructions) {
std::size_t dispOff = 0;
@@ -88,18 +89,19 @@ std::vector<FileByteOffset> CallSiteResolver::ResolveCallSites(const std::vector
continue;
if (dispOff + 4 > textSection.size()) continue;
std::int32_t disp = readDisp32(textSection, dispOff);
VirtualAddress instrEnd = m.Offset + static_cast<VirtualAddress>(m.Length);
VirtualAddress instrEnd = textSectionVAddr + m.Offset + static_cast<VirtualAddress>(m.Length);
VirtualAddress target = static_cast<VirtualAddress>(static_cast<std::int64_t>(instrEnd) + disp);
_cachedTargetToInstr.emplace(target, m.Offset);
}
_cachedTextPtr = &textSection;
_cachedTextVAddr = textSectionVAddr;
}
std::vector<FileByteOffset> sites;
auto lower = _cachedTargetToInstr.lower_bound(targetGotOrPltAddress);
auto upper = _cachedTargetToInstr.lower_bound(targetGotOrPltAddress + targetGotOrPltSize);
for (auto it = lower; it != upper; ++it)
sites.push_back(it->second);
sites.push_back(textSectionVAddr + it->second);
return sites;
}
@@ -38,14 +38,20 @@ RelinkResult RelinkerPipeline::Relink(const std::vector<std::uint8_t>& sourceElf
std::vector<std::uint8_t> textSection;
VirtualAddress textVAddr = 0;
std::vector<std::pair<std::vector<std::uint8_t>, VirtualAddress>> executableSegments;
VirtualAddress gotVAddr = 0;
ByteCount gotSize = 0;
for (const auto& ph : programHeaders) {
if (ph.Type == PT_LOAD && (ph.Flags & PF_X) != 0) {
textSection = _elfReader->ReadSegment(ph);
textVAddr = ph.MappedAddress;
break;
auto segment = _elfReader->ReadSegment(ph);
if (!segment.empty()) {
if (textSection.empty()) {
textSection = segment;
textVAddr = ph.MappedAddress;
}
executableSegments.emplace_back(std::move(segment), ph.MappedAddress);
}
}
}
@@ -199,8 +205,8 @@ RelinkResult RelinkerPipeline::Relink(const std::vector<std::uint8_t>& sourceElf
for (const auto& ref : nidRefs)
_validationPolicy->ValidateRelocationTypeSupported(ref.RelocationTypeValue, ref.RelocationTableOffset);
if (!textSection.empty())
_syscallScanner->ScanCodeSectionForSyscalls(textSection, textVAddr, textSection.size());
for (const auto& [segment, segmentVAddr] : executableSegments)
_syscallScanner->ScanCodeSectionForSyscalls(segment, segmentVAddr, segment.size());
_validationPolicy->ValidateSyscallAbsence();
@@ -211,6 +217,8 @@ RelinkResult RelinkerPipeline::Relink(const std::vector<std::uint8_t>& sourceElf
std::cout << "NID input: " << originalNidCount << " references\n";
if (unusedFilterLevel == 2) {
if (executableSegments.size() > 1)
throw RelinkerException("Strict NID filtering does not support multiple executable segments");
nidRefs = _unusedNidFilter->Filter(nidRefs, raw, textSection, textVAddr);
if (nidRefs.size() > originalNidCount) throw RelinkerException("Strict NID filter increased the reference count");
std::cout << "Strict filtering total: " << originalNidCount << " -> " << nidRefs.size() << "; filtered=" << originalNidCount - nidRefs.size() << "\n";
@@ -226,9 +234,14 @@ RelinkResult RelinkerPipeline::Relink(const std::vector<std::uint8_t>& sourceElf
std::cout << "PLT preservation: " << pltRefs.size() << " -> " << pltRefs.size() << "; filtered=0\n";
const std::size_t nonPltCount = nonPltRefs.size();
nonPltRefs = _unusedNidFilter->Filter(nonPltRefs, raw, textSection, textVAddr);
if (nonPltRefs.size() > nonPltCount) throw RelinkerException("Unused NID filter increased the reference count");
std::cout << "CFG/GOT filtering: " << nonPltCount << " -> " << nonPltRefs.size() << "; filtered=" << nonPltCount - nonPltRefs.size() << "\n";
if (executableSegments.size() > 1) {
std::cout << "CFG/GOT filtering skipped: multiple executable segments are not modeled; "
<< nonPltCount << " -> " << nonPltCount << "; filtered=0\n";
} else {
nonPltRefs = _unusedNidFilter->Filter(nonPltRefs, raw, textSection, textVAddr);
if (nonPltRefs.size() > nonPltCount) throw RelinkerException("Unused NID filter increased the reference count");
std::cout << "CFG/GOT filtering: " << nonPltCount << " -> " << nonPltRefs.size() << "; filtered=" << nonPltCount - nonPltRefs.size() << "\n";
}
nidRefs.clear();
nidRefs.reserve(pltRefs.size() + nonPltRefs.size());
@@ -285,8 +298,11 @@ RelinkResult RelinkerPipeline::Relink(const std::vector<std::uint8_t>& sourceElf
for (const auto& ref : nidRefs) {
std::vector<FileByteOffset> callSites;
bool callSitesResolved = false;
if (!textSection.empty() && gotSize > 0) {
callSites = _callSiteResolver->ResolveCallSites(textSection, textVAddr, ref.RelocationAddress, 8);
if (!executableSegments.empty()) {
for (const auto& [segment, segmentVAddr] : executableSegments) {
auto segmentSites = _callSiteResolver->ResolveCallSites(segment, segmentVAddr, ref.RelocationAddress, 8);
callSites.insert(callSites.end(), segmentSites.begin(), segmentSites.end());
}
callSitesResolved = !callSites.empty();
}
CallRegistryEntry entry;
@@ -0,0 +1,84 @@
from pathlib import Path
import os
import json
import struct
import subprocess
import sys
import tempfile
def fixture(second_code: bytes, with_import: bool = False) -> bytearray:
image = bytearray(0x1000)
image[:16] = b"\x7fELF\x02\x01\x01" + bytes(9)
struct.pack_into("<HHIQQQIHHHHHH", image, 16,
3, 62, 1, 0x1210, 64, 0, 0, 64, 56, 4, 64, 0, 0)
image[0x200:0x206] = b"\xff\x25\xfa\xf0\xff\xff"
image[0x210:0x215] = b"\xe9\xfb\x05\x00\x00"
image[0x800:0x800 + len(second_code)] = second_code
struct.pack_into("<QQq", image, 0x700, 0x310, 8, 0x1210)
tags = ([(1, 4), (5, 0x600), (10, 12), (6, 0x620), (11, 24)] if with_import else
[(5, 0x600), (10, 1), (6, 0x620), (11, 24)])
tags += [
(7, 0x700), (8, 48 if with_import else 24), (9, 24), (0, 0)]
if with_import:
tags.insert(-1, (0x6100003f, 48))
image[0x600:0x600 + len(b"foo\x00lib.so\x00")] = b"foo\x00lib.so\x00"
struct.pack_into("<QQq", image, 0x718, 0x300, (1 << 32) | 6, 0)
struct.pack_into("<IIQQQQQQ", image, 64,
1, 6, 0, 0, 0, 0x800, 0x800, 0x1000)
struct.pack_into("<IIQQQQQQ", image, 120,
2, 6, 0x400, 0x400, 0x400, len(tags) * 16, len(tags) * 16, 8)
struct.pack_into("<IIQQQQQQ", image, 176,
1, 5, 0x200, 0x1200, 0x1200, 0x20, 0x20, 0x1000)
struct.pack_into("<IIQQQQQQ", image, 232,
1, 5, 0x800, 0x1800, 0x1800, len(second_code), len(second_code), 0x1000)
for index, tag in enumerate(tags):
struct.pack_into("<qQ", image, 0x400 + index * 16, *tag)
return image
def run_case(relinker: Path, work: Path, name: str, args, code: bytes, with_import=False):
source = work / (name + ".elf")
output = work / (name + ".exe")
source.write_bytes(fixture(code, with_import))
result = subprocess.run([str(relinker), "--skip-sce-module", "--windows", *args,
str(source), str(output)], capture_output=True,
text=True, timeout=20)
return result, output
def main():
relinker = Path(sys.argv[1]).resolve()
with tempfile.TemporaryDirectory(prefix="anyps5-executable-segments-") as directory:
work = Path(directory)
result, output = run_case(relinker, work, "syscall", [], b"\x0f\x05\xc3")
assert result.returncode == 2 and "Forbidden syscall instruction" in result.stderr and not output.exists(), result
result, output = run_case(relinker, work, "syscall-filter", ["unused-filter=1"], b"\x0f\x05\xc3")
assert result.returncode == 2 and "Forbidden syscall instruction" in result.stderr and not output.exists(), result
result, output = run_case(relinker, work, "skip", ["--skip-syscall-check"], b"\x0f\x05\xc3")
assert result.returncode == 0 and output.exists(), (result.stdout, result.stderr)
second_code = b"\x90" * 16 + b"\xb8\x2a\x00\x00\x00\xc3"
result, output = run_case(relinker, work, "execute", ["--skip-syscall-check"], second_code)
assert result.returncode == 0 and output.exists(), (result.stdout, result.stderr)
if os.name == "nt":
executed = subprocess.run([str(output)], capture_output=True, timeout=20)
assert executed.returncode == 42, executed.returncode
second_code = b"\x48\x8b\x05\xf9\xea\xff\xff" + b"\x90" * 9 + b"\xb8\x2a\x00\x00\x00\xc3"
result, output = run_case(relinker, work, "preserve", ["unused-filter=1", "--registry"], second_code, True)
registry = output.with_name(output.stem + ".registry.json")
assert result.returncode == 0 and output.exists() and registry.exists(), (result.stdout, result.stderr)
entries = json.loads(registry.read_text())
assert len(entries) == 1 and entries[0]["nid"] == "foo", entries
assert entries[0]["callSites"] == ["0x1200", "0x1800"], entries
assert "CFG/GOT filtering skipped" in result.stdout and "filtered=0" in result.stdout
result, output = run_case(relinker, work, "strict", ["unused-filter=2"], b"\x90\xc3")
assert result.returncode == 2 and "multiple executable segments" in result.stderr and not output.exists(), result
print("Executable segment tests passed")
if __name__ == "__main__":
main()