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
2 changes: 2 additions & 0 deletions core/relinker/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ add_library(relinker_core STATIC
${CMAKE_CURRENT_SOURCE_DIR}/relinker/src/analysis/CallSiteResolver.cpp
${CMAKE_CURRENT_SOURCE_DIR}/relinker/src/analysis/CodeInstructionCollector.cpp
${CMAKE_CURRENT_SOURCE_DIR}/relinker/src/analysis/SceCodeExtent.cpp
${CMAKE_CURRENT_SOURCE_DIR}/relinker/src/analysis/RelativeJumpTables.cpp
${CMAKE_CURRENT_SOURCE_DIR}/relinker/src/analysis/UnusedNidFilter.cpp
${CMAKE_CURRENT_SOURCE_DIR}/relinker/src/analysis/UnusedNidFilter/StrictNidFilter.cpp
${CMAKE_CURRENT_SOURCE_DIR}/relinker/src/analysis/UnusedNidFilter/StrictReachability.cpp
Expand Down Expand Up @@ -657,6 +658,7 @@ if(BUILD_TESTING)

add_test_executable(control_flow_graph_tests
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/ControlFlowGraphTests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/relinker/src/analysis/RelativeJumpTables.cpp
${CMAKE_CURRENT_SOURCE_DIR}/relinker/src/analysis/UnusedNidFilter/ControlFlowGraph.cpp
${CMAKE_CURRENT_SOURCE_DIR}/relinker/src/analysis/UnusedNidFilter/StrictReachability.cpp
${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/X64InstructionDecoder.cpp
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#ifndef RELINKER_ANALYSIS_RELATIVEJUMPTABLES_HPP
#define RELINKER_ANALYSIS_RELATIVEJUMPTABLES_HPP

#include <relinker/analysis/UnusedNidFilter/StrictReachability.hpp>
#include <cstddef>
#include <cstdint>
#include <span>
#include <utility>
#include <vector>

namespace Relinker {

struct RelativeJumpTable {
VirtualAddress Function;
VirtualAddress Begin;
VirtualAddress End;
};

std::size_t FindTrailingRelativeJumpTable(std::span<const std::uint8_t> code);
std::vector<RelativeJumpTable> FindRelativeJumpTables(std::span<const std::uint8_t> segment, VirtualAddress segmentVAddr, const std::vector<std::pair<VirtualAddress, VirtualAddress>>& functions);

}

#endif
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ std::unique_ptr<IControlFlowGraph> BuildControlFlowGraph(
bool followCodeAddresses = false
);

std::unique_ptr<IControlFlowGraph> BuildControlFlowGraph(std::span<const std::uint8_t> text, VirtualAddress textVaddr, VirtualAddress entryVaddr, const std::vector<VirtualAddress>& extraEntries, const IRelativeRelocationIndex& relativeRelocations, bool followCodeAddresses, std::unordered_set<VirtualAddress>& reachable, const std::function<void(std::uint64_t)>& progress = {});
std::unique_ptr<IControlFlowGraph> BuildControlFlowGraph(std::span<const std::uint8_t> text, VirtualAddress textVaddr, VirtualAddress entryVaddr, const std::vector<VirtualAddress>& extraEntries, const IRelativeRelocationIndex& relativeRelocations, bool followCodeAddresses, std::unordered_set<VirtualAddress>& reachable, const std::function<void(std::uint64_t)>& progress = {}, const std::function<bool(VirtualAddress)>& isData = {});

std::unique_ptr<IControlFlowGraph> BuildControlFlowGraph(
const std::vector<std::uint8_t>& text,
Expand Down
20 changes: 18 additions & 2 deletions core/relinker/relinker/src/analysis/CodeInstructionCollector.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include <relinker/analysis/UnusedNidFilter/IControlFlowGraph.hpp>
#include <relinker/analysis/UnusedNidFilter/EhFrameReader.hpp>
#include <relinker/analysis/SceCodeExtent.hpp>
#include <relinker/analysis/RelativeJumpTables.hpp>
#include <codegen/x86/X64InstructionDecoder.hpp>
#include <codegen/CodegenException.hpp>
#include <io/BufferUtils.hpp>
Expand Down Expand Up @@ -110,7 +111,9 @@ std::set<Domain::VirtualAddress> CodeInstructionCollector::Collect(const std::ve
}
std::set<std::uint64_t> roots;
std::map<std::uint64_t, std::uint64_t> functions;
const auto addRoot = [&](std::uint64_t address) { if (isCode(address)) roots.insert(address); };
std::map<std::uint64_t, std::uint64_t> tables;
const auto inTable = [&](std::uint64_t address) { const auto after = tables.upper_bound(address); return after != tables.begin() && address < std::prev(after)->second; };
const auto addRoot = [&](std::uint64_t address) { if (isCode(address) && !inTable(address)) roots.insert(address); };
const auto addAddressTakenRoot = [&](std::uint64_t address, const std::uint8_t* code, const Codegen::DecodedInstructionInfo& info) {
if (!info.HasRipRelativeDisp || code[info.OpcodeOffset] != 0x8d || !(info.RexPrefix & 8)) return;
const auto displacement = std::bit_cast<std::int32_t>(Io::ReadU32(bytes, fileOffset(address, info.Length) + info.RipRelativeDispOffset));
Expand Down Expand Up @@ -241,6 +244,19 @@ std::set<Domain::VirtualAddress> CodeInstructionCollector::Collect(const std::ve
addFunction(function.Begin, function.End - function.Begin, false);
for (const auto target : function.ExtraTargets) addRoot(target);
}
if (sceBase) {
const std::vector<std::pair<std::uint64_t, std::uint64_t>> ranges(functions.begin(), functions.end());
for (const auto& header : codeHeaders) {
if (header.Type != 1 || (header.Flags & 1) == 0) continue;
const std::span<const std::uint8_t> segment(bytes.data() + header.Offset, header.FileSize);
for (const auto& table : FindRelativeJumpTables(segment, header.MappedAddress, ranges)) {
tables.emplace(table.Begin, table.End);
auto& end = functions.at(table.Function);
end = std::min(end, table.Begin);
}
}
std::erase_if(roots, inTable);
}
if (roots.empty()) throw Domain::RelinkerException("Code analysis: no code entry points");
std::set<std::uint64_t> instructions;
const Codegen::X64InstructionDecoder decoder;
Expand Down Expand Up @@ -372,7 +388,7 @@ std::set<Domain::VirtualAddress> CodeInstructionCollector::Collect(const std::ve
for (const auto root : roots) if (root >= header.MappedAddress && root - header.MappedAddress < header.FileSize) entries.push_back(root);
if (entries.empty()) continue;
const std::span<const std::uint8_t> text(bytes.data() + header.Offset, header.FileSize);
const auto graph = UnusedNidFilter::BuildControlFlowGraph(text, header.MappedAddress, entries.front(), entries, pointers, true, sectionReachable[i], [&](std::uint64_t count) { report(6000 + 2500 * count / std::max<std::uint64_t>(scanBytes, 1)); });
const auto graph = UnusedNidFilter::BuildControlFlowGraph(text, header.MappedAddress, entries.front(), entries, pointers, true, sectionReachable[i], [&](std::uint64_t count) { report(6000 + 2500 * count / std::max<std::uint64_t>(scanBytes, 1)); }, inTable);
for (const auto address : graph->ReachableVaddrs()) {
if (!decodedInstructions.insert(address).second) continue;
instructions.insert(address);
Expand Down
131 changes: 131 additions & 0 deletions core/relinker/relinker/src/analysis/RelativeJumpTables.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
#include <relinker/analysis/RelativeJumpTables.hpp>
#include <codegen/x86/X64InstructionDecoder.hpp>
#include <codegen/CodegenException.hpp>
#include <algorithm>
#include <cstring>

namespace Relinker {

namespace {

constexpr VirtualAddress MaxTableGapAfterFunction = 0x10000;

struct TableLoad {
std::size_t At;
std::size_t Target;
};

bool IsNop(std::span<const std::uint8_t> code, std::size_t at, std::size_t length) {
auto position = at;
const auto end = at + length;
while (position < end && (code[position] == 0x66 || code[position] == 0x2e || code[position] == 0x3e)) ++position;
if (position >= end) return false;
if (code[position] == 0x90) return position + 1 == end;
return code[position] == 0x0f && position + 1 < end && code[position + 1] == 0x1f;
}

bool OnlyPadding(std::span<const std::uint8_t> code, std::size_t from, const Codegen::X64InstructionDecoder& decoder) {
for (auto position = from; position < code.size();) {
if (code[position] == 0x00 || code[position] == 0xcc || code[position] == 0x90) {
++position;
continue;
}
try {
const auto length = decoder.DecodeInstruction(code.data() + position, code.size() - position).Length;
if (length == 0 || length > code.size() - position || !IsNop(code, position, length)) return false;
position += length;
} catch (const Codegen::CodegenException&) {
return false;
}
}
return true;
}

std::size_t TableEntries(std::span<const std::uint8_t> code, std::size_t table, std::size_t end, std::size_t firstTable, const std::vector<bool>& instructionStarts) {
std::size_t entries = 0;
while (table + (entries + 1) * 4 <= end) {
std::int32_t relative = 0;
std::memcpy(&relative, code.data() + table + entries * 4, sizeof(relative));
const auto destination = static_cast<std::int64_t>(table) + relative;
if (destination < 0 || destination >= static_cast<std::int64_t>(firstTable) || !instructionStarts[static_cast<std::size_t>(destination)]) break;
++entries;
}
return entries;
}

std::size_t TablesEnd(std::span<const std::uint8_t> code, std::size_t firstTable, const std::vector<TableLoad>& loads, const std::vector<bool>& instructionStarts) {
auto table = firstTable;
while (table < code.size()) {
auto end = code.size();
for (const auto& load : loads)
if (load.Target > table && load.Target < end) end = load.Target;
const auto entries = TableEntries(code, table, end, firstTable, instructionStarts);
if (entries == 0 || (table == firstTable && entries < 2)) return table == firstTable ? 0 : table;
table += entries * 4;
if (std::none_of(loads.begin(), loads.end(), [&](const auto& load) { return load.Target == table; })) return table;
}
return table;
}

}

std::size_t FindTrailingRelativeJumpTable(std::span<const std::uint8_t> code) {
const Codegen::X64InstructionDecoder decoder;
std::vector<TableLoad> loads;
std::vector<bool> instructionStarts(code.size() + 1, false);
bool flowEnded = false;
bool sawIndirectJump = false;
std::size_t lastIndirectJump = 0;
for (std::size_t position = 0; position < code.size();) {
instructionStarts[position] = true;
if (flowEnded && sawIndirectJump) {
for (const auto& load : loads) {
if (load.Target != position || load.At >= lastIndirectJump) continue;
const auto end = TablesEnd(code, position, loads, instructionStarts);
if (end != 0 && OnlyPadding(code, end, decoder)) return position;
}
}
Codegen::DecodedInstructionInfo info;
try {
info = decoder.DecodeInstruction(code.data() + position, code.size() - position);
} catch (const Codegen::CodegenException&) {
break;
}
if (info.Length == 0 || info.Length > code.size() - position) break;
const auto next = position + info.Length;
if (info.HasRipRelativeDisp && !info.IsTwoByteOpcode && info.OpcodeOffset < info.Length && info.Length >= 4 && code[position + info.OpcodeOffset] == 0x8d) {
std::int32_t displacement = 0;
std::memcpy(&displacement, code.data() + next - 4, sizeof(displacement));
const auto target = static_cast<std::int64_t>(next) + displacement;
if (target > static_cast<std::int64_t>(next) && target < static_cast<std::int64_t>(code.size())) loads.push_back({position, static_cast<std::size_t>(target)});
}
if (info.FlowKind == Codegen::ControlFlowKind::IndirectJump) {
sawIndirectJump = true;
lastIndirectJump = position;
}
if (!IsNop(code, position, info.Length)) {
const bool directJumpOrCall = (info.Length == 5 && (code[position] == 0xe8 || code[position] == 0xe9)) || (info.Length == 2 && code[position] == 0xeb);
flowEnded = directJumpOrCall || info.FlowKind == Codegen::ControlFlowKind::Return || info.FlowKind == Codegen::ControlFlowKind::IndirectJump || info.FlowKind == Codegen::ControlFlowKind::Trap;
}
position = next;
}
return code.size();
}

std::vector<RelativeJumpTable> FindRelativeJumpTables(std::span<const std::uint8_t> segment, VirtualAddress segmentVAddr, const std::vector<std::pair<VirtualAddress, VirtualAddress>>& functions) {
std::vector<RelativeJumpTable> tables;
const auto segmentEnd = segmentVAddr + segment.size();
for (std::size_t index = 0; index < functions.size(); ++index) {
const auto [begin, end] = functions[index];
if (begin < segmentVAddr || begin >= segmentEnd || end <= begin) continue;
auto inspectEnd = std::min(end, segmentEnd);
if (index + 1 < functions.size() && functions[index + 1].first > inspectEnd && functions[index + 1].first - inspectEnd <= MaxTableGapAfterFunction)
inspectEnd = std::min(functions[index + 1].first, segmentEnd);
const auto code = segment.subspan(begin - segmentVAddr, inspectEnd - begin);
if (const auto tail = FindTrailingRelativeJumpTable(code); tail != 0 && tail < code.size())
tables.push_back({begin, begin + tail, inspectEnd});
}
return tables;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class ControlFlowGraph : public IControlFlowGraph {

namespace {

void buildGraph(std::span<const std::uint8_t> text, VirtualAddress textVaddr, VirtualAddress entryVaddr, const std::vector<VirtualAddress>& extraEntries, const IRelativeRelocationIndex& relativeRelocations, const std::vector<StrictDataRegion>* data, bool followCodeAddresses, std::unordered_set<VirtualAddress>& reachable, const std::function<void(std::uint64_t)>& progress) {
void buildGraph(std::span<const std::uint8_t> text, VirtualAddress textVaddr, VirtualAddress entryVaddr, const std::vector<VirtualAddress>& extraEntries, const IRelativeRelocationIndex& relativeRelocations, const std::vector<StrictDataRegion>* data, bool followCodeAddresses, std::unordered_set<VirtualAddress>& reachable, const std::function<void(std::uint64_t)>& progress, const std::function<bool(VirtualAddress)>& isData) {
if (text.size() > std::numeric_limits<VirtualAddress>::max() - textVaddr)
throw RelinkerException("Text section range exceeds the address space");
const Codegen::X64InstructionDecoder decoder;
Expand All @@ -41,6 +41,7 @@ void buildGraph(std::span<const std::uint8_t> text, VirtualAddress textVaddr, Vi

auto enqueue = [&](VirtualAddress va) {
if (reachable.count(va) > 0) return;
if (isData && isData(va)) return;
if (va < textVaddr || va - textVaddr >= text.size()) return;
if (!visited.insert(va).second) return;
worklist.push(va);
Expand Down Expand Up @@ -68,7 +69,7 @@ void buildGraph(std::span<const std::uint8_t> text, VirtualAddress textVaddr, Vi
VirtualAddress va = worklist.front();
worklist.pop();

while (va >= textVaddr && va - textVaddr < text.size() && !reachable.contains(va)) {
while (va >= textVaddr && va - textVaddr < text.size() && !reachable.contains(va) && !(isData && isData(va))) {
std::size_t bufOff = static_cast<std::size_t>(va - textVaddr);
std::size_t available = text.size() - bufOff;
if (available == 0) throw RelinkerException("CFG: zero available bytes at target", va);
Expand Down Expand Up @@ -153,8 +154,8 @@ void buildGraph(std::span<const std::uint8_t> text, VirtualAddress textVaddr, Vi

}

std::unique_ptr<IControlFlowGraph> BuildControlFlowGraph(std::span<const std::uint8_t> text, VirtualAddress textVaddr, VirtualAddress entryVaddr, const std::vector<VirtualAddress>& extraEntries, const IRelativeRelocationIndex& relativeRelocations, bool followCodeAddresses, std::unordered_set<VirtualAddress>& reachable, const std::function<void(std::uint64_t)>& progress) {
buildGraph(text, textVaddr, entryVaddr, extraEntries, relativeRelocations, nullptr, followCodeAddresses, reachable, progress);
std::unique_ptr<IControlFlowGraph> BuildControlFlowGraph(std::span<const std::uint8_t> text, VirtualAddress textVaddr, VirtualAddress entryVaddr, const std::vector<VirtualAddress>& extraEntries, const IRelativeRelocationIndex& relativeRelocations, bool followCodeAddresses, std::unordered_set<VirtualAddress>& reachable, const std::function<void(std::uint64_t)>& progress, const std::function<bool(VirtualAddress)>& isData) {
buildGraph(text, textVaddr, entryVaddr, extraEntries, relativeRelocations, nullptr, followCodeAddresses, reachable, progress, isData);
return std::make_unique<ControlFlowGraph>(&reachable);
}

Expand Down Expand Up @@ -191,7 +192,7 @@ std::unique_ptr<IControlFlowGraph> BuildAddressTakenControlFlowGraph(
const std::vector<StrictDataRegion>& data
) {
std::unordered_set<VirtualAddress> reachable;
buildGraph(std::span<const std::uint8_t>(text.data(), text.size()), textVaddr, entryVaddr, extraEntries, relativeRelocations, &data, false, reachable, {});
buildGraph(std::span<const std::uint8_t>(text.data(), text.size()), textVaddr, entryVaddr, extraEntries, relativeRelocations, &data, false, reachable, {}, {});
return std::make_unique<ControlFlowGraph>(std::move(reachable));
}

Expand Down
Loading
Loading