Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

namespace Elfpatcher::Linux {

inline constexpr std::uint64_t DefaultFixedBase = 0x400000;

class LinuxElfPatcher : public IElfPatcher {
public:
LinuxElfPatcher(
Expand Down
5 changes: 3 additions & 2 deletions core/relinker/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ struct ConvertedExecutable {
std::vector<std::uint8_t> Bytes;
std::string Diagnostics;
std::vector<Relinker::GamePatch::AppliedPatch> AppliedPatches;
std::optional<std::uint64_t> LinuxBase;
};

ConvertedExecutable Convert(const Cli::Args& args, const std::string& inputPath, const std::string& absPath, const bool mainExecutable, const std::string& targetName, const std::vector<Relinker::GamePatch::PatchEntry>& patches, Cli::ConsoleProgress& progress) {
Expand Down Expand Up @@ -73,7 +74,7 @@ ConvertedExecutable Convert(const Cli::Args& args, const std::string& inputPath,
progress.IncludeFile(Io::Utf8Path(input.OutputPath));
for (const auto& module : input.Modules) progress.IncludeFile(Io::Utf8Path(module.Path));
auto converted = Relinker::Conversion(progress).Convert(std::move(input), options);
return {inputPath, absPath, std::move(converted.Analysis), std::move(converted.Modules), std::move(converted.Executable), std::move(converted.WindowsDiagnostics), std::move(converted.AppliedPatches)};
return {inputPath, absPath, std::move(converted.Analysis), std::move(converted.Modules), std::move(converted.Executable), std::move(converted.WindowsDiagnostics), std::move(converted.AppliedPatches), converted.LinuxBase};
}

class OutputIdentityDirectory {
Expand Down Expand Up @@ -332,7 +333,7 @@ int Run(const int argc, char* argv[]) {
std::filesystem::path manifestPath;
std::string manifestText;
if (!appliedPatches.empty()) manifestPath = Io::NativePath(absPath).parent_path() / Io::NativePath(Io::Utf8Path(Io::NativePath(absPath).stem()) + Relinker::GamePatch::ManifestSuffix);
if (!manifestPath.empty()) manifestText = Relinker::GamePatch::WriteManifest(appliedPatches, mainTarget, Io::Utf8Path(patchFile));
if (!manifestPath.empty()) manifestText = Relinker::GamePatch::WriteManifest(appliedPatches, mainTarget, Io::Utf8Path(patchFile), executables.front().LinuxBase);

const Elfpatcher::Linux::LinuxDesktopEntryWriter desktopEntryWriter;
const auto desktopEntry = args.toWindows || args.toMacos ? std::nullopt : desktopEntryWriter.Prepare(Io::NativePath(args.inputPath).parent_path() / "sce_sys", Io::NativePath(absPath));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ struct PatchEntry {
struct PatchFile {
std::vector<PatchEntry> Entries;
std::optional<std::string> MainTarget;
std::optional<std::uint64_t> LinuxBase;
};

struct PatchedRange {
Expand Down Expand Up @@ -114,7 +115,7 @@ void MatchTargets(const std::vector<PatchEntry>& entries, const std::vector<std:

std::vector<AppliedPatch> AggregateManifest(const std::vector<std::vector<AppliedPatch>>& records);

std::string WriteManifest(const std::vector<AppliedPatch>& patches, const std::string& mainTarget, const std::string& configPath);
std::string WriteManifest(const std::vector<AppliedPatch>& patches, const std::string& mainTarget, const std::string& configPath, std::optional<std::uint64_t> linuxBase = std::nullopt);

std::vector<VerifyResult> VerifyPatches(const PatchFile& file, const std::vector<VerifyTarget>& executables, const std::vector<VerifyTarget>& modules, bool outputMode);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ struct ConversionOutput {
RelinkResult Analysis;
std::string WindowsDiagnostics;
std::vector<GamePatch::AppliedPatch> AppliedPatches;
std::optional<std::uint64_t> LinuxBase;
};

class Conversion {
Expand Down
31 changes: 23 additions & 8 deletions core/relinker/relinker/src/patching/GamePatch.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ constexpr std::array<IntegerType, 8> kIntegerTypes{{
{"i8", 8, true}, {"i16", 16, true}, {"i32", 32, true}, {"i64", 64, true},
}};

constexpr std::array<std::string_view, 7> kIgnoredTopLevelKeys{"relinker_version", "relinker_commit", "config", "config_sha256", "main_target", "settings", "settings_sha256"};
constexpr std::array<std::string_view, 8> kReservedNames{"format", "relinker_version", "relinker_commit", "config", "config_sha256", "main_target", "settings", "settings_sha256"};
constexpr std::array<std::string_view, 8> kIgnoredTopLevelKeys{"relinker_version", "relinker_commit", "config", "config_sha256", "main_target", "linux_base", "settings", "settings_sha256"};
constexpr std::array<std::string_view, 9> kReservedNames{"format", "relinker_version", "relinker_commit", "config", "config_sha256", "main_target", "linux_base", "settings", "settings_sha256"};
constexpr std::array<std::string_view, 10> kEntryKeys{"name", "target", "va", "type", "expected", "value", "min", "max", "align", "description"};

std::string HexValue(const std::uint64_t value) {
Expand Down Expand Up @@ -300,8 +300,8 @@ void RejectEntryOverlaps(const std::vector<PatchEntry>& entries, const std::vect
}
}

bool IsElfDyn(const std::vector<std::uint8_t>& bytes) {
return bytes.size() >= 18 && bytes[0] == 0x7f && bytes[1] == 'E' && bytes[2] == 'L' && bytes[3] == 'F' && bytes[16] == Elfpatcher::ET_DYN && bytes[17] == 0;
bool IsElfOfType(const std::vector<std::uint8_t>& bytes, const std::uint16_t type) {
return bytes.size() >= 18 && bytes[0] == 0x7f && bytes[1] == 'E' && bytes[2] == 'L' && bytes[3] == 'F' && bytes[16] == (type & 0xff) && bytes[17] == (type >> 8);
}

VerifyResult VerifyOne(const PatchEntry& entry, const EntryRange& resolved, const std::vector<std::uint8_t>& bytes, const bool outputMode) {
Expand Down Expand Up @@ -410,6 +410,10 @@ PatchFile ParsePatchFile(const std::string_view text) {
if (!mainTarget->IsString || mainTarget->Text.empty()) FailLine(mainTarget->Line, "main_target must be a nonempty string", "main_target");
file.MainTarget = mainTarget->Text;
}
if (const auto* linuxBase = Find(top, "linux_base")) {
if (linuxBase->IsString || linuxBase->Number.Negative) FailLine(linuxBase->Line, "linux_base must be a non-negative integer", "linux_base");
file.LinuxBase = linuxBase->Number.Magnitude;
}
return file;
}

Expand Down Expand Up @@ -505,7 +509,7 @@ std::vector<AppliedPatch> AggregateManifest(const std::vector<std::vector<Applie
return merged;
}

std::string WriteManifest(const std::vector<AppliedPatch>& patches, const std::string& mainTarget, const std::string& configPath) {
std::string WriteManifest(const std::vector<AppliedPatch>& patches, const std::string& mainTarget, const std::string& configPath, const std::optional<std::uint64_t> linuxBase) {
const auto holdable = [](const std::string& text) {
return std::none_of(text.begin(), text.end(), [](const char character) {
return character == '"' || character == '\\' || (static_cast<unsigned char>(character) < 0x20 && character != '\t') || character == 0x7f;
Expand All @@ -519,6 +523,7 @@ std::string WriteManifest(const std::vector<AppliedPatch>& patches, const std::s
if (!config.empty() && !holdable(config)) config = std::filesystem::path(Io::NativePath(configPath)).filename().generic_string();
std::ostringstream manifest;
manifest << "format = 1\nmain_target = " << quoted(mainTarget, "main_target") << '\n';
if (linuxBase) manifest << "linux_base = " << HexValue(*linuxBase) << '\n';
if (!config.empty()) manifest << "config = " << quoted(config, "config") << '\n';
for (const auto& patch : patches) {
manifest << "\n[[patch]]\n";
Expand Down Expand Up @@ -553,8 +558,12 @@ std::vector<VerifyResult> VerifyPatches(const PatchFile& file, const std::vector
for (std::size_t index = 0; index < executables.size(); ++index)
for (std::size_t other = index + 1; other < executables.size(); ++other)
if (executables[index].Name == executables[other].Name) throw Domain::RelinkerException("ambiguous patch target: " + executables[index].Name);
for (const auto& executable : executables)
if (!IsElfDyn(executable.Bytes)) throw Domain::RelinkerException(executable.Name + " is not an ET_DYN Linux ELF output (ET_EXEC from --linux-fixed-base, PE and Mach-O outputs are not supported): verify the input instead");
for (const auto& executable : executables) {
const bool fixed = IsElfOfType(executable.Bytes, Elfpatcher::ET_EXEC);
if (!fixed && !IsElfOfType(executable.Bytes, Elfpatcher::ET_DYN)) throw Domain::RelinkerException(executable.Name + " is not a Linux ELF output (PE and Mach-O outputs are not supported): verify the input instead");
if (fixed && !file.LinuxBase) throw Domain::RelinkerException(executable.Name + " is an ET_EXEC Linux ELF output, but the patch file has no linux_base: verify the manifest written by its conversion");
if (!fixed && file.LinuxBase) throw Domain::RelinkerException(executable.Name + " is an ET_DYN Linux ELF output, but the patch file has linux_base = " + HexValue(*file.LinuxBase) + ": verify the output of the conversion that wrote it");
}
} else {
std::vector<std::string> names;
for (const auto& executable : executables) names.push_back(executable.Name);
Expand Down Expand Up @@ -583,13 +592,19 @@ std::vector<VerifyResult> VerifyPatches(const PatchFile& file, const std::vector
}
continue;
}
const std::uint64_t base = outputMode && IsElfOfType(target->Bytes, Elfpatcher::ET_EXEC) ? *file.LinuxBase : 0;
std::vector<PatchEntry> own;
for (const auto other : indices) own.push_back(file.Entries[other]);
for (const auto other : indices) {
own.push_back(file.Entries[other]);
if (own.back().VirtualAddress > std::numeric_limits<std::uint64_t>::max() - base) throw Domain::RelinkerException(Describe(own.back()) + " lies outside the address space at linux_base = " + HexValue(base));
own.back().VirtualAddress += base;
}
const ElfReader reader(target->Bytes);
const auto resolved = ResolveEach(reader, own);
RejectEntryOverlaps(own, resolved);
for (std::size_t position = 0; position < indices.size(); ++position) {
results[indices[position]] = VerifyOne(own[position], resolved[position], target->Bytes, outputMode);
results[indices[position]].VirtualAddress = file.Entries[indices[position]].VirtualAddress;
done[indices[position]] = true;
}
}
Expand Down
9 changes: 7 additions & 2 deletions core/relinker/relinker/src/pipeline/Conversion.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,11 @@ ConversionOutput Conversion::Convert(ConversionInput input, const ConversionOpti

auto byteWriter = std::make_shared<Io::ByteWriter>();

std::optional<std::uint64_t> linuxBase;
if (!windows && !macos)
linuxBase = options.LinuxFixedBase || options.LazyBinding ? options.LinuxFixedBase : std::optional<std::uint64_t>(Elfpatcher::Linux::DefaultFixedBase);
if (!windows && !macos && options.LazyBinding)
inputProgress.Message("Warning: with --lazy-binding the Linux executable stays position independent and is not placed at 0x400000; a title whose own sceLibcMspaceCreate checks the 40-bit address window stops at start-up\n");
std::shared_ptr<Elfpatcher::IElfPatcher> patcher;
if (macos) {
patcher = std::make_shared<Elfpatcher::MacOs::MacOsMachOPatcher>(options.MacosFixedBase, [&](std::string_view text) { inputProgress.Message(text); });
Expand All @@ -139,7 +144,7 @@ ConversionOutput Conversion::Convert(ConversionInput input, const ConversionOpti
),
std::make_shared<Elfpatcher::SectionHeaderTableBuilder>(byteWriter),
byteWriter,
options.LinuxFixedBase,
linuxBase,
options.TraceImports
);
}
Expand All @@ -157,7 +162,7 @@ ConversionOutput Conversion::Convert(ConversionInput input, const ConversionOpti
std::string diagnostics;
if (windows) diagnostics = std::static_pointer_cast<Elfpatcher::Windows::WindowsPePatcher>(patcher)->GetDiagnostics();
inputProgress.Report({Domain::ProgressStage::Executable, Io::Utf8Path(input.InputPath), 1, 1});
return {std::move(executableBytes), std::move(guestArtifacts), std::move(result), std::move(diagnostics), std::move(appliedPatches)};
return {std::move(executableBytes), std::move(guestArtifacts), std::move(result), std::move(diagnostics), std::move(appliedPatches), linuxBase};
} catch (Domain::RelinkerException& error) {
if (error.InputPath.empty()) error.InputPath = Io::Utf8Path(input.InputPath);
throw;
Expand Down
16 changes: 12 additions & 4 deletions core/relinker/relinker/tests/ConversionTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -132,14 +132,22 @@ void fixedBase() {
const Relinker::Conversion converter(progress);
auto source = input();
source.Modules.push_back({"virtual/title/sce_module/plugin.prx", fixture()});
const auto plain = converter.Convert(source, {});
const auto standard = converter.Convert(source, {});
Relinker::ConversionOptions lazy;
lazy.LazyBinding = true;
const auto independent = converter.Convert(input(), lazy);
Relinker::ConversionOptions options;
options.LinuxFixedBase = 0x400000000;
const auto fixed = converter.Convert(source, options);
require(Io::ReadU16(plain.Executable, 16) == 3 && Io::ReadU16(fixed.Executable, 16) == 2, "Fixed base did not select ET_EXEC");
require(Io::ReadU64(fixed.Executable, 24) == Io::ReadU64(plain.Executable, 24) + *options.LinuxFixedBase, "Fixed entry was not rebased above 4 GiB");
require(fixed.Modules.front().Bytes == plain.Modules.front().Bytes, "Executable fixed base changed a bundled module");
require(Io::ReadU16(standard.Executable, 16) == 2 && Io::ReadU16(fixed.Executable, 16) == 2, "Fixed base did not select ET_EXEC");
require(Io::ReadU16(independent.Executable, 16) == 3, "Lazy binding did not keep ET_DYN");
require(standard.LinuxBase == 0x400000 && fixed.LinuxBase == *options.LinuxFixedBase && !independent.LinuxBase, "Conversion reported the wrong Linux base");
require(Io::ReadU64(fixed.Executable, 24) == Io::ReadU64(standard.Executable, 24) + *options.LinuxFixedBase - 0x400000, "Fixed entry was not rebased above 4 GiB");
require(fixed.Modules.front().Bytes == standard.Modules.front().Bytes, "Executable fixed base changed a bundled module");
for (const auto target : {Relinker::TargetSystem::Windows, Relinker::TargetSystem::MacOs}) {
Relinker::ConversionOptions other;
other.Target = target;
require(!converter.Convert(source, other).LinuxBase, "A non-Linux conversion reported a Linux base");
options.Target = target;
reject([&] { converter.Convert(source, options); });
}
Expand Down
16 changes: 11 additions & 5 deletions core/relinker/relinker/tests/ElfFixture.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <limits>
#include <span>
#include <stdexcept>
#include <utility>
Expand Down Expand Up @@ -117,12 +118,17 @@ class MappedImage {
const auto phOffset = Read<std::uint64_t>(elf, 32);
const auto phSize = Read<std::uint16_t>(elf, 54);
const auto phCount = Read<std::uint16_t>(elf, 56);
const auto page = static_cast<std::uint64_t>(sysconf(_SC_PAGESIZE));
linkBase = std::numeric_limits<std::uint64_t>::max();
std::uint64_t last = 0;
for (std::uint16_t index = 0; index < phCount; ++index) {
const auto header = phOffset + index * phSize;
if (Read<std::uint32_t>(elf, header) != 1) continue;
size = std::max<std::size_t>(size, Read<std::uint64_t>(elf, header + 16) + Read<std::uint64_t>(elf, header + 40));
linkBase = std::min(linkBase, Read<std::uint64_t>(elf, header + 16) / page * page);
last = std::max(last, Read<std::uint64_t>(elf, header + 16) + Read<std::uint64_t>(elf, header + 40));
}
if (size == 0) throw std::runtime_error("ELF has no PT_LOAD segment");
if (last == 0) throw std::runtime_error("ELF has no PT_LOAD segment");
size = static_cast<std::size_t>(last - linkBase);
base = mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (base == MAP_FAILED) throw std::runtime_error("Cannot map executable memory for the ELF image");
for (std::uint16_t index = 0; index < phCount; ++index) {
Expand All @@ -131,15 +137,14 @@ class MappedImage {
const auto offset = Read<std::uint64_t>(elf, header + 8);
const auto fileSize = Read<std::uint64_t>(elf, header + 32);
if (offset > elf.size() || fileSize > elf.size() - offset) throw std::runtime_error("PT_LOAD exceeds the ELF file");
std::memcpy(static_cast<std::uint8_t*>(base) + Read<std::uint64_t>(elf, header + 16), elf.data() + offset, fileSize);
std::memcpy(static_cast<std::uint8_t*>(base) + (Read<std::uint64_t>(elf, header + 16) - linkBase), elf.data() + offset, fileSize);
}
if (mprotect(base, size, PROT_NONE) != 0) throw std::runtime_error("Cannot protect the ELF image");
const auto page = static_cast<std::uint64_t>(sysconf(_SC_PAGESIZE));
for (std::uint16_t index = 0; index < phCount; ++index) {
const auto header = phOffset + index * phSize;
if (Read<std::uint32_t>(elf, header) != 1) continue;
const auto flags = Read<std::uint32_t>(elf, header + 4);
const auto vaddr = Read<std::uint64_t>(elf, header + 16);
const auto vaddr = Read<std::uint64_t>(elf, header + 16) - linkBase;
const auto start = vaddr / page * page;
const auto end = (vaddr + Read<std::uint64_t>(elf, header + 40) + page - 1) / page * page;
const int protection = ((flags & 4) != 0 ? PROT_READ : 0) | ((flags & 2) != 0 ? PROT_WRITE : 0) | ((flags & 1) != 0 ? PROT_EXEC : 0);
Expand All @@ -163,6 +168,7 @@ class MappedImage {
private:
void* base = nullptr;
std::size_t size = 0;
std::uint64_t linkBase = 0;
};

} // namespace RelinkerTests
Loading
Loading