From a18e2c7e1cebb22de78de4244758a1a6eeb3701a Mon Sep 17 00:00:00 2001 From: AlenHay <82121826+AlenHay@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:47:59 +0200 Subject: [PATCH 1/3] Emit explicit interior function entries and index graph mutations Add validated body-owner configuration and entry-aware emission, preserve deferred graph entries, track address index changes across node replacement/removal/moves, and sweep gap-fill graphs efficiently. Ship actual generated-code execution and graph behavior fixtures with the feature. Run generated-code fixture at the SDK x86-64-v2 baseline. Rebuild codegen consumers before using body-owner configuration; older parsers silently ignore that field. --- include/rex/codegen/config.h | 3 + include/rex/codegen/function_graph.h | 8 +- include/rex/codegen/function_node.h | 7 +- src/codegen/codegen_writer.cpp | 121 +++++++- src/codegen/config.cpp | 14 +- src/codegen/function_graph.cpp | 125 +++++++- src/codegen/phase_gapfill.cpp | 69 +++-- tests/CMakeLists.txt | 41 +++ tests/regression/emit_interior_entries.cpp | 226 ++++++++++++++ tests/regression/test_gapfill_cleanup.py | 212 +++++++++++++ tests/regression/test_graph_registration.py | 311 ++++++++++++++++++++ tests/regression/test_interior_entries.py | 103 +++++++ 12 files changed, 1204 insertions(+), 36 deletions(-) create mode 100644 tests/regression/emit_interior_entries.cpp create mode 100644 tests/regression/test_gapfill_cleanup.py create mode 100644 tests/regression/test_graph_registration.py create mode 100644 tests/regression/test_interior_entries.py diff --git a/include/rex/codegen/config.h b/include/rex/codegen/config.h index 8200139..9e74744 100644 --- a/include/rex/codegen/config.h +++ b/include/rex/codegen/config.h @@ -47,6 +47,9 @@ struct FunctionConfig { uint32_t end = 0; // End address, exclusive (mutually exclusive with size) std::string name; // Custom symbol name (empty = auto-generate sub_XXXXXXXX) uint32_t parent = 0; // Parent function address (0 = standalone, non-zero = chunk) + // Keep this entry callable, but start at its exact address in the named + // owner's emitted body. Intended for explicit interior entry points. + uint32_t bodyOwner = 0; // Keep non-volatiles in ctx instead of localizing them. Marks an MSVC SEH // funclet, which reads the registers its owner left live and would see a zero diff --git a/include/rex/codegen/function_graph.h b/include/rex/codegen/function_graph.h index c64271b..6f1f461 100644 --- a/include/rex/codegen/function_graph.h +++ b/include/rex/codegen/function_graph.h @@ -54,7 +54,7 @@ class FunctionGraph { // Add a function to the graph. // Returns the new node, or existing node if already present (higher authority wins). - // Notifies all PENDING functions to try resolution against the new entry. + // Notifies PENDING functions with unresolved jumps against the new entry. // hasXrefs: true if this is a known call target (bl target, etc.) FunctionNode* addFunction(uint32_t base, uint32_t size, FunctionAuthority authority, bool hasXrefs = false); @@ -199,7 +199,11 @@ class FunctionGraph { std::vector> chunks_; // base, size pairs MemoryReader memoryReader_; - // Notify all PENDING functions that a new function was added + // Only these entries can benefit from registration notifications. Entry + // addresses remain valid across graph moves and never retain replaced nodes. + std::unordered_set unresolvedFunctionEntries_; + + // Notify indexed PENDING functions that a new function was added void notifyFunctionAdded(FunctionNode* newFunction); }; diff --git a/include/rex/codegen/function_node.h b/include/rex/codegen/function_node.h index 569acf2..f07472e 100644 --- a/include/rex/codegen/function_node.h +++ b/include/rex/codegen/function_node.h @@ -93,10 +93,12 @@ class FunctionNode { //========================================================================= /// Emit C++ code for this function - /// Requires: state() == kSealed + /// Requires discovered blocks; the writer validates deferred interior branches. /// For imports: emits REX_IMPORT macro /// For normal functions: emits REX_FUNC with blocks and instructions - std::string emitCpp(const EmitContext& ctx) const; + // An alternate entry retains its own symbol while using this node's body + // and call metadata, plus any additional blocks found from that entry. + std::string emitCpp(const EmitContext& ctx, const FunctionNode* entry = nullptr) const; //========================================================================= // Instruction access (valid after discover) @@ -175,6 +177,7 @@ class FunctionNode { // Internal helper void removeUnresolvedJump(uint32_t site); + std::string emitCppForEntry(const EmitContext& ctx, const FunctionNode& entry) const; //========================================================================= // State diff --git a/src/codegen/codegen_writer.cpp b/src/codegen/codegen_writer.cpp index a0484fb..c11f21e 100644 --- a/src/codegen/codegen_writer.cpp +++ b/src/codegen/codegen_writer.cpp @@ -35,6 +35,120 @@ namespace { +bool ValidateFunctionBodies(const rex::codegen::RecompilerConfig& config, + const rex::codegen::FunctionGraph& graph, + const rex::codegen::BinaryView& binary) { + for (const auto& [address, function] : config.functions) { + if (!function.bodyOwner) + continue; + auto reject = [&](std::string_view reason) { + REXCODEGEN_ERROR("Function 0x{:08X} body 0x{:08X}: {}", address, + function.bodyOwner, reason); + return false; + }; + if ((address & 3) || (function.bodyOwner & 3) || function.parent || + address == function.bodyOwner) + return reject("body requires a distinct aligned owner and cannot be a chunk"); + if (config.ctrAsLocalVariable || config.xerAsLocalVariable || + config.reservedRegisterAsLocalVariable || config.crRegistersAsLocalVariables || + config.nonArgumentRegistersAsLocalVariables || config.nonVolatileRegistersAsLocalVariables) + return reject("interior body entries require all register localization options disabled"); + auto ownerConfig = config.functions.find(function.bodyOwner); + if (ownerConfig != config.functions.end() && ownerConfig->second.bodyOwner) + return reject("nested or cyclic body owners are unsupported"); + const auto* entry = graph.getFunction(address); + const auto* owner = graph.getFunction(function.bodyOwner); + if (!entry || !owner || entry->isRegistered() || owner->isRegistered() || + entry->isImport() || owner->isImport() || owner->blocks().empty() || + entry->blocks().empty()) { + REXCODEGEN_ERROR("Body node states: entry present={} state={} import={} unresolved={}; owner present={} state={} import={} unresolved={}", + entry != nullptr, entry ? int(entry->state()) : -1, entry && entry->isImport(), + entry ? entry->unresolvedJumps().size() : 0, owner != nullptr, + owner ? int(owner->state()) : -1, owner && owner->isImport(), + owner ? owner->unresolvedJumps().size() : 0); + return reject("entry and owner must have discovered non-import instruction blocks"); + } + if (std::any_of(config.rexcrtFunctions.begin(), config.rexcrtFunctions.end(), + [&](const auto& crt) { + return crt.second == address || crt.second == function.bodyOwner; + })) + return reject("body entries cannot replace a rexcrt mapping"); + bool contained = std::any_of(owner->blocks().begin(), owner->blocks().end(), + [&](const rex::codegen::Block& block) { + return address >= block.base && uint64_t(address) + 4 <= uint64_t(block.base) + block.size; + }); + if (!contained || !binary.translate(address)) + return reject("entry instruction is missing from the owner's actual blocks"); + // The emission union must never wrap an address or import unmapped bytes. + for (const auto* node : {owner, entry}) { + for (const auto& block : node->blocks()) { + const auto* section = binary.findSection(block.base); + if (!block.size || (block.base & 3) || (block.size & 3) || + block.base < owner->base() || !section || !section->executable || + uint64_t(block.base) + block.size > UINT32_MAX || + uint64_t(block.base) + block.size > uint64_t(section->baseAddress) + section->size) + return reject("body has an invalid or unmapped instruction block"); + } + } + auto inBody = [&](uint32_t instruction) { + if (instruction & 3) return false; + for (const auto* node : {owner, entry}) { + for (const auto& block : node->blocks()) { + if (instruction >= block.base && + uint64_t(instruction) + 4 <= uint64_t(block.base) + block.size) + return true; + } + } + return false; + }; + auto resolvedAt = [&](uint32_t site) -> const rex::codegen::CallTarget* { + // Match the emission union's owner-first precedence exactly. + for (const auto* node : {owner, entry}) { + for (const auto* edges : {&node->calls(), &node->tailCalls()}) { + for (const auto& edge : *edges) + if (edge.site == site) return &edge.target; + } + } + return nullptr; + }; + for (const auto* node : {owner, entry}) { + for (const auto& jump : node->unresolvedJumps()) { + if (!inBody(jump.site)) return reject("pending branch site is outside the actual body"); + const auto* bytes = binary.translate(jump.site); + uint32_t instruction = (uint32_t(bytes[0]) << 24) | (uint32_t(bytes[1]) << 16) | + (uint32_t(bytes[2]) << 8) | bytes[3]; + uint32_t opcode = instruction >> 26; + if ((opcode != 16 && opcode != 18) || bool(instruction & 1) != jump.isCall || + (opcode == 16) != jump.isConditional) + return reject("pending branch metadata does not match its instruction"); + unsigned width = opcode == 16 ? 16 : 26; + uint32_t displacementBits = instruction & ((uint32_t(1) << width) - 4); + int64_t displacement = displacementBits; + if (displacementBits & (uint32_t(1) << (width - 1))) + displacement -= int64_t(1) << width; + uint32_t target = static_cast(displacement + + ((instruction & 2) ? 0 : int64_t(jump.site))); + if (target != jump.target) return reject("pending branch target does not match its instruction"); + const auto* call = resolvedAt(jump.site); + bool mapped = call && ((call->isFunction() && call->asFunction() && + call->asFunction()->base() == target) || + (call->isImport() && + std::get(call->value).address == target)); + if (mapped) continue; + if (jump.isCall || !inBody(target)) + return reject("pending branch has no actual local instruction or resolved call target"); + // Conditional local branches use owner labels. An unconditional jump + // to a graph entry still requires call metadata with the current builder. + auto kind = graph.classifyTarget(target, jump.site, false); + if (!jump.isConditional && (kind == rex::codegen::TargetKind::Function || + kind == rex::codegen::TargetKind::Import)) + return reject("pending unconditional branch conflicts with another graph entry"); + } + } + } + return true; +} + nlohmann::json buildTemplateData(const rex::codegen::CodegenContext& ctx, const std::vector& functions, const std::unordered_map& rexcrtByAddr) { @@ -173,6 +287,8 @@ bool CodegenWriter::write(bool force) { ctx_.errors.Count()); return false; } + if (!ValidateFunctionBodies(config(), graph(), binary())) + return false; // --- Output directory setup (from recompile.cpp) --- std::filesystem::path outputPath = ctx_.configDir() / config().outDirectoryPath; @@ -264,7 +380,10 @@ bool CodegenWriter::write(bool force) { emitCtx.referenced = &referenced; for (const auto* fn : functions) { referenced.clear(); - std::string code = fn->emitCpp(emitCtx); + const auto configured = config().functions.find(fn->base()); + const auto* body = configured != config().functions.end() && configured->second.bodyOwner + ? graph().getFunction(configured->second.bodyOwner) : fn; + std::string code = body->emitCpp(emitCtx, body == fn ? nullptr : fn); if (code.size() > maxFileBytes) { REXCODEGEN_WARN("Function 0x{:08X} is {} bytes, exceeds max_file_size_bytes ({})", fn->base(), code.size(), maxFileBytes); diff --git a/src/codegen/config.cpp b/src/codegen/config.cpp index 5da54a0..723fe8e 100644 --- a/src/codegen/config.cpp +++ b/src/codegen/config.cpp @@ -81,7 +81,7 @@ void MergeBool(bool& dst, bool src, bool present, const char* name) { // Apply a single parsed TOML table onto the config (merge semantics) // --------------------------------------------------------------------------- -void ApplyToml(const toml::table& toml, RecompilerConfig& cfg, const std::string& filePath) { +bool ApplyToml(const toml::table& toml, RecompilerConfig& cfg, const std::string& filePath) { // --- Scalars: last wins --- // String scalars (only override if present in this file) @@ -197,6 +197,14 @@ void ApplyToml(const toml::table& toml, RecompilerConfig& cfg, const std::string fcfg.end = (*table)["end"].value_or(0u); fcfg.name = (*table)["name"].value_or(std::string{}); fcfg.parent = (*table)["parent"].value_or(0u); + fcfg.bodyOwner = (*table)["body"].value_or(0u); + if ((*table)["body"] && + (!(*table)["body"].value() || !fcfg.bodyOwner || + (fcfg.bodyOwner & 3) != 0 || fcfg.bodyOwner == address || fcfg.parent)) { + REXCODEGEN_ERROR("Function 0x{:08X}: 'body' requires a different aligned owner address and cannot be combined with 'parent'", + address); + return false; + } fcfg.shareRegisters = (*table)["share_registers"].value_or(false); if (fcfg.size && fcfg.end) { @@ -381,6 +389,7 @@ void ApplyToml(const toml::table& toml, RecompilerConfig& cfg, const std::string } } } + return true; } bool ApplyTableWithIncludes(const toml::table& tbl, const std::filesystem::path& base_dir, @@ -440,8 +449,7 @@ bool ApplyTableWithIncludes(const toml::table& tbl, const std::filesystem::path& } } } - ApplyToml(tbl, cfg, description); - return true; + return ApplyToml(tbl, cfg, description); } } // namespace diff --git a/src/codegen/function_graph.cpp b/src/codegen/function_graph.cpp index fc918bb..dc3ff76 100644 --- a/src/codegen/function_graph.cpp +++ b/src/codegen/function_graph.cpp @@ -346,7 +346,81 @@ void emit_print(std::string& out, fmt::format_string fmt, Args&&... arg } // namespace -std::string FunctionNode::emitCpp(const EmitContext& ctx) const { +std::string FunctionNode::emitCpp(const EmitContext& ctx, const FunctionNode* entry) const { + if (!entry || entry == this) + return emitCppForEntry(ctx, *this); + + // Emission-only copy: preserve graph identities and ordinary owner output. + // An interior entry can discover an extra path the owner's CFG missed. + FunctionNode body = *this; + body.blocks_.insert(body.blocks_.end(), entry->blocks_.begin(), entry->blocks_.end()); + std::sort(body.blocks_.begin(), body.blocks_.end(), + [](const Block& a, const Block& b) { return a.base < b.base; }); + std::vector merged; + for (const auto& block : body.blocks_) { + if (!merged.empty() && block.base <= merged.back().end()) { + merged.back().size = std::max(merged.back().end(), block.end()) - merged.back().base; + } else { + merged.push_back(block); + } + } + body.blocks_ = std::move(merged); + for (const auto& block : body.blocks_) + body.size_ = std::max(body.size_, block.end() - body.base_); + body.labels_.insert(entry->labels_.begin(), entry->labels_.end()); + body.labels_.insert(entry->base()); + // Prefer owner metadata at shared sites. Copy only additional call sites + // so an entry's independently classified backward branch cannot replace it. + auto hasCallSite = [&](uint32_t site) { + auto matches = [site](const CallEdge& call) { return call.site == site; }; + return std::any_of(body.calls_.begin(), body.calls_.end(), matches) || + std::any_of(body.tailCalls_.begin(), body.tailCalls_.end(), matches); + }; + for (const auto& call : entry->calls_) { + if (!hasCallSite(call.site)) + body.calls_.push_back(call); + } + for (const auto& call : entry->tailCalls_) { + if (!hasCallSite(call.site)) + body.tailCalls_.push_back(call); + } + // The writer proves deferred local branches land on actual union bytes. + // CONFIG/PDATA containsAddress also trusts holes, so check block coverage + // directly. Preserve resolved external calls even if their address overlaps. + for (const auto* node : {this, entry}) { + for (const auto& jump : node->unresolvedJumps_) { + if (jump.isCall) continue; + const CallTarget* call = nullptr; + for (const auto* edges : {&body.calls_, &body.tailCalls_}) { + for (const auto& edge : *edges) { + if (edge.site == jump.site) { call = &edge.target; break; } + } + if (call) break; + } + if (call && ((call->isFunction() && call->asFunction() && + call->asFunction()->base() == jump.target) || + (call->isImport() && + std::get(call->value).address == jump.target))) + continue; + if (std::any_of(body.blocks_.begin(), body.blocks_.end(), [&](const Block& block) { + return jump.target >= block.base && + uint64_t(jump.target) + 4 <= uint64_t(block.base) + block.size; + })) + body.labels_.insert(jump.target); + } + } + for (const auto& table : entry->jumpTables_) { + if (std::none_of(body.jumpTables_.begin(), body.jumpTables_.end(), + [&](const JumpTable& existing) { + return existing.bctrAddress == table.bctrAddress; + })) + body.jumpTables_.push_back(table); + } + return body.emitCppForEntry(ctx, *entry); +} + +std::string FunctionNode::emitCppForEntry(const EmitContext& ctx, + const FunctionNode& entry) const { if (authority() == FunctionAuthority::IMPORT) { return ""; } @@ -385,6 +459,8 @@ std::string FunctionNode::emitCpp(const EmitContext& ctx) const { // --- First pass: collect labels from all blocks --- std::unordered_set labels; labels.reserve(64); + if (entry.base() != base()) + labels.insert(entry.base()); for (const auto& block : blocks()) { auto* blockData = reinterpret_cast(ctx.binary.translate(block.base)); @@ -470,12 +546,12 @@ std::string FunctionNode::emitCpp(const EmitContext& ctx) const { // --- Function name --- std::string name; - if (base() == ctx.entryPoint) { + if (entry.base() == ctx.entryPoint) { name = "xstart"; - } else if (!name_.empty()) { - name = name_; + } else if (!entry.name_.empty()) { + name = entry.name_; } else { - name = fmt::format("sub_{:08X}", base()); + name = fmt::format("sub_{:08X}", entry.base()); } // Function signature with weak/alias pattern @@ -493,6 +569,10 @@ std::string FunctionNode::emitCpp(const EmitContext& ctx) const { std::string body; body.reserve(4096); + // Local declarations are emitted before body below, so this jump skips + // guest prologue instructions without crossing C++ initialization. + if (entry.base() != base()) + emit_println(body, "\tgoto loc_{:X};", entry.base()); ppc_insn insn; std::unordered_set emittedLabels; @@ -756,13 +836,14 @@ FunctionNode* FunctionGraph::addFunction(uint32_t base, uint32_t size, FunctionA // Create new node auto node = std::make_unique(base, size, authority); FunctionNode* nodePtr = node.get(); + unresolvedFunctionEntries_.erase(base); functions_[base] = std::move(node); functionsByBase_[base] = nodePtr; // Track xrefs for merge eligibility functionHasXrefs_[base] = hasXrefs; - // Notify all PENDING functions + // Notify PENDING functions that still have unresolved jumps notifyFunctionAdded(nodePtr); return nodePtr; @@ -800,6 +881,7 @@ bool FunctionGraph::removeFunction(uint32_t entryPoint) { return false; } REXCODEGEN_TRACE("FunctionGraph: removing absorbed function 0x{:08X}", entryPoint); + unresolvedFunctionEntries_.erase(entryPoint); functionsByBase_.erase(entryPoint); functions_.erase(it); functionHasXrefs_.erase(entryPoint); // Clean up xref tracking @@ -962,6 +1044,11 @@ void FunctionGraph::addUnresolvedJumpToFunction(uint32_t entry, uint32_t site, u } // Not resolvable yet - add as unresolved + if (node->isPending()) { + // Index before appending: an allocation failure must not leave a live jump + // hidden from notifications. An empty indexed owner is pruned safely. + unresolvedFunctionEntries_.insert(entry); + } node->addUnresolvedJump(site, target, isCall, conditional); REXCODEGEN_TRACE("FunctionGraph: added unresolved {} 0x{:08X}->0x{:08X} to function 0x{:08X}", isCall ? "call" : "jump", site, target, entry); @@ -973,8 +1060,10 @@ void FunctionGraph::addUnresolvedJumpToFunction(uint32_t entry, uint32_t site, u size_t FunctionGraph::tryResolveFunction(uint32_t entry) { auto* node = getFunction(entry); - if (!node || node->isSealed()) + if (!node || node->isSealed()) { + unresolvedFunctionEntries_.erase(entry); return 0; + } size_t resolved = 0; @@ -1026,6 +1115,9 @@ size_t FunctionGraph::tryResolveFunction(uint32_t entry) { REXCODEGEN_TRACE(" 0x{:08X}->0x{:08X}: still unresolved", jump.site, jump.target); } + if (!node->hasUnresolvedJumps()) { + unresolvedFunctionEntries_.erase(entry); + } return resolved; } @@ -1043,6 +1135,7 @@ bool FunctionGraph::trySealFunction(uint32_t entry) { if (node->canSeal()) { node->seal(); + unresolvedFunctionEntries_.erase(entry); return true; } return false; @@ -1055,6 +1148,7 @@ size_t FunctionGraph::sealAllReady() { if (node->isPending()) { if (node->canSeal()) { node->seal(); + unresolvedFunctionEntries_.erase(base); sealed++; } else { couldNotSeal++; @@ -1094,6 +1188,7 @@ void FunctionGraph::sealAll() { } node->seal(); + unresolvedFunctionEntries_.erase(base); } if (!errors.empty()) { @@ -1284,10 +1379,22 @@ TargetKind FunctionGraph::classifyTarget(uint32_t target, uint32_t callerAddr, } void FunctionGraph::notifyFunctionAdded(FunctionNode* newFunction) { - for (auto& [base, node] : functions_) { - if (node.get() != newFunction && node->isPending()) { + for (auto it = unresolvedFunctionEntries_.begin(); it != unresolvedFunctionEntries_.end();) { + auto* node = getFunction(*it); + // Public node sealing can bypass the graph helpers (imports may seal even + // with unresolved jumps). Prune those entries before attempting resolution. + if (!node || !node->isPending() || !node->hasUnresolvedJumps()) { + it = unresolvedFunctionEntries_.erase(it); + continue; + } + if (node != newFunction) { node->tryResolveAgainst(newFunction); } + if (!node->hasUnresolvedJumps()) { + it = unresolvedFunctionEntries_.erase(it); + } else { + ++it; + } } } diff --git a/src/codegen/phase_gapfill.cpp b/src/codegen/phase_gapfill.cpp index f3da777..5c624eb 100644 --- a/src/codegen/phase_gapfill.cpp +++ b/src/codegen/phase_gapfill.cpp @@ -11,6 +11,10 @@ #include "ppc/instruction.h" +#include +#include +#include +#include #include #include @@ -178,29 +182,56 @@ void gapFillCodeRegions(CodegenContext& ctx) { void cleanupAbsorbedGapFills(CodegenContext& ctx) { auto& graph = ctx.graph; - std::vector toRemove; - + std::vector ordered; + ordered.reserve(graph.functions().size()); for (const auto& [addr, node] : graph.functions()) { - if (node->authority() != FunctionAuthority::GAP_FILL) - continue; - - for (const auto& [otherAddr, otherNode] : graph.functions()) { - if (otherAddr == addr) - continue; - if (!otherNode->containsAddress(addr)) - continue; + ordered.push_back(node.get()); + } + std::sort(ordered.begin(), ordered.end(), [](const auto* a, const auto* b) { + return a->base() < b->base(); + }); + + // containsAddress first rejects points outside [base, base + size). Only + // lower-base owners whose overall end remains above this entry can absorb it. + // Keep the real block/authority predicate for holes and declared-size owners. + using EndEntry = std::pair; + std::priority_queue, std::greater> endings; + std::map active; + std::unordered_set absorbed; + for (const auto* node : ordered) { + const uint32_t addr = node->base(); + while (!endings.empty() && endings.top().first <= addr) { + active.erase(endings.top().second); + endings.pop(); + } - // This GAP_FILL is inside another function's blocks - if (otherNode->authority() != FunctionAuthority::GAP_FILL) { - // Absorbed by higher authority - remove - toRemove.push_back(addr); - break; - } else if (otherAddr < addr) { - // Both GAP_FILL, other has lower address - it survives - toRemove.push_back(addr); - break; + if (node->authority() == FunctionAuthority::GAP_FILL) { + for (const auto& [otherAddr, otherNode] : active) { + if (!otherNode->containsAddress(addr)) + continue; + if (otherNode->authority() != FunctionAuthority::GAP_FILL || otherAddr < addr) { + absorbed.insert(addr); + break; + } } } + + // Match uint32_t wrap behavior: wrapped/empty bounds contain no address. + // Even an absorbed owner remains visible until the final batch removal. + const uint32_t end = node->end(); + if (end > addr) { + active.emplace(addr, node); + endings.emplace(end, addr); + } + } + + // Preserve the original removal order, independent of the sorted sweep. + std::vector toRemove; + toRemove.reserve(absorbed.size()); + for (const auto& [addr, node] : graph.functions()) { + if (absorbed.contains(addr)) { + toRemove.push_back(addr); + } } for (uint32_t addr : toRemove) { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 3e67044..aa516c8 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -6,3 +6,44 @@ add_subdirectory(unit) # PPC instruction tests (requires PPC toolchain) add_subdirectory(ppc) + +# Compile small production-body fixtures with fake guest threads and graphics +# objects. These tests do not require game assets or a graphics device. The +# cache-storage fixtures use POSIX stdio/file APIs, so register them on Linux +# with GNU-style compiler drivers only. +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" + AND NOT CMAKE_CROSSCOMPILING + AND CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "GNU") + find_package(Python3 COMPONENTS Interpreter QUIET) + if(Python3_Interpreter_FOUND) + set(REXGLUE_REGRESSION_CHECKS graph_registration gapfill_cleanup) + if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(AMD64|amd64|x86_64)$") + # This producer uses the real decoder and writer; its test compiles + # and executes unmodified generated C++ with the actual SDK headers. + add_executable(regression_interior_entries regression/emit_interior_entries.cpp) + target_link_libraries(regression_interior_entries PRIVATE rexcodegen) + add_test(NAME regression_interior_entries + COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/regression/test_interior_entries.py + ${CMAKE_CURRENT_BINARY_DIR}/regression/interior_entries + --compiler ${CMAKE_CXX_COMPILER} + --producer $) + set_tests_properties(regression_interior_entries PROPERTIES + TIMEOUT 60 LABELS "regression;asset_free") + endif() + foreach(check IN LISTS REXGLUE_REGRESSION_CHECKS) + add_test(NAME regression_${check} + COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/regression/test_${check}.py + ${CMAKE_CURRENT_BINARY_DIR}/regression/${check} + --compiler ${CMAKE_CXX_COMPILER}) + set_tests_properties(regression_${check} PROPERTIES + TIMEOUT 60 LABELS "regression;asset_free") + if(check STREQUAL "timer_wait") + set_tests_properties(regression_${check} PROPERTIES TIMEOUT 100) + endif() + endforeach() + else() + message(STATUS "Python3 unavailable: production-body regression fixtures are disabled") + endif() +endif() diff --git a/tests/regression/emit_interior_entries.cpp b/tests/regression/emit_interior_entries.cpp new file mode 100644 index 0000000..160c943 --- /dev/null +++ b/tests/regression/emit_interior_entries.cpp @@ -0,0 +1,226 @@ +// Synthetic executable PPC bytes pass through the real config loader, writer, +// decoder, and instruction builders. The companion test runs their C++ output. +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using namespace rex::codegen; +namespace fs = std::filesystem; +constexpr uint32_t kBase = 0x82000000; +constexpr uint32_t kEntry = kBase + 0x18; +constexpr uint32_t kExtraOwner = kBase + 0x40; +constexpr uint32_t kExtraEntry = kBase + 0x48; + +void Check(bool result, const char* message) { + if (!result) throw std::runtime_error(message); +} + +std::vector Bytes(bool externalHole = false) { + std::vector bytes(0x90); + auto put = [&](unsigned offset, uint32_t instruction) { + for (unsigned i = 0; i < 4; ++i) + bytes[offset + i] = static_cast(instruction >> (24 - i * 8)); + }; + // A real frame, conditional backward branch, live CTR loop, and owner-only + // call metadata. The interior entry skips all four prologue instructions. + put(0x00, 0x3821FFF0); // addi r1,r1,-16 + put(0x04, 0x38600000); // li r3,0 + put(0x08, 0x38800003); // li r4,3 + put(0x0C, 0x7C8903A6); // mtctr r4 + put(0x10, 0x38630001); // addi r3,r3,1 + put(0x14, 0x4800006D); // bl helper at +0x80 + put(0x18, 0x2C030001); // cmpwi r3,1 + put(0x1C, 0x4182FFF4); // beq +0x10 + put(0x20, 0x4200FFF0); // bdnz +0x10 + put(0x24, 0x38210010); // addi r1,r1,16 + put(0x28, 0x4E800020); // blr + if (externalHole) { + put(0x30, 0x38210010); // external tail callee restores existing frame + put(0x34, 0x38E70001); // addi r7,r7,1 + put(0x38, 0x4E800020); // blr + } + // Normal execution skips the interior-only path. Discovery from the + // interior entry found a second block and call absent from the owner CFG. + put(0x40, 0x3821FFF0); // addi r1,r1,-16 + put(0x44, 0x4800000C); // b +0x50 + put(0x48, 0x60000000); // nop (actual entry instruction in owner block) + put(0x4C, 0x48000014); // b +0x60 (entry-only discovered instruction) + put(0x50, 0x38210010); // addi r1,r1,16 + put(0x54, 0x4E800020); // blr + put(0x60, 0x48000029); // bl helper at +0x88 + put(0x64, 0x48000000 | (static_cast(-0x14) & 0x03FFFFFC)); // b +0x50 + put(0x80, 0x38A50001); // addi r5,r5,1 + put(0x84, 0x4E800020); + put(0x88, 0x38C60001); // addi r6,r6,1 + put(0x8C, 0x4E800020); + return bytes; +} + +CodegenContext Context(const fs::path& root, RecompilerConfig config, + bool missingEntry = false, uint32_t pendingTarget = 0, + bool externalHole = false) { + auto bytes = Bytes(externalHole); + if (pendingTarget) { + uint32_t instruction = 0x41820000 | ((pendingTarget - (kBase + 0x1C)) & 0xFFFC); + for (unsigned i = 0; i < 4; ++i) + bytes[0x1C + i] = static_cast(instruction >> (24 - i * 8)); + } + TestModule module; + module.Load(kBase, bytes.data(), bytes.size()); + auto ctx = CodegenContext::Create(BinaryView::fromModule(module), std::move(config)); + ctx.setConfigDir(root); + ctx.analysisState().format = "xex"; + ctx.analysisState().loadAddress = kBase; + ctx.analysisState().entryPoint = kBase + 0x80; + ctx.analysisState().imageSize = static_cast(bytes.size()); + auto add = [&](uint32_t address, uint32_t size, std::vector blocks) { + auto* node = ctx.graph.addFunction(address, size, FunctionAuthority::CONFIG, true); + Check(node != nullptr, "addFunction failed"); + node->discover(std::move(blocks), {}, {}); + return node; + }; + auto* helper = add(kBase + 0x80, 8, {{kBase + 0x80, 8}}); + ctx.graph.setFunctionName(kBase + 0x80, "xstart"); + auto* extraHelper = add(kBase + 0x88, 8, {{kBase + 0x88, 8}}); + auto* owner = add(kBase, externalHole ? 0x40 : 0x2C, missingEntry + ? std::vector{{kBase, 0x18}, {kBase + 0x1C, 0x10}} + : std::vector{{kBase, 0x2C}}); + auto* entry = add(kEntry, 0x14, {{kEntry, 0x14}}); + auto* extraOwner = add(kExtraOwner, 0x18, + {{kExtraOwner, 0xC}, {kBase + 0x50, 8}}); + auto* extraEntry = add(kExtraEntry, 0x20, + {{kExtraEntry, 8}, {kBase + 0x50, 8}, {kBase + 0x60, 8}}); + ctx.graph.addCallToFunction(kBase, kBase + 0x14, CallTarget::function(helper)); + ctx.graph.addLabelToFunction(kBase, kBase + 0x10); + ctx.graph.addCallToFunction(kEntry, kBase + 0x14, CallTarget::function(extraHelper)); + ctx.graph.addCallToFunction(kExtraEntry, kBase + 0x60, CallTarget::function(extraHelper)); + // A conflicting classification from isolated-entry analysis must not + // override the actual owner's backward-branch interpretation. + ctx.graph.addTailCallToFunction(kEntry, kBase + 0x1C, CallTarget::function(owner)); + if (pendingTarget) + ctx.graph.addUnresolvedJumpToFunction(kEntry, kBase + 0x1C, pendingTarget, false, true); + for (auto* node : {helper, extraHelper, owner, entry, extraOwner, extraEntry}) { + if (node != entry || !pendingTarget) node->seal(); + } + if (pendingTarget) + Check(entry->isDiscovered() && !entry->isSealed() && entry->unresolvedJumps().size() == 1, + "fixture must retain a genuinely unsealed deferred alias branch"); + return ctx; +} + +RecompilerConfig Config(const fs::path& root) { + fs::create_directories(root); + auto path = root / "fixture.toml"; + std::ofstream(path) << "project_name = 'interior'\nfile_path = 'synthetic.bin'\n" + "out_directory_path = 'generated'\n" + "[functions]\n0x82000018 = { body = 0x82000000 }\n" + "0x82000048 = { body = 0x82000040 }\n"; + RecompilerConfig config; + Check(config.Load(path.string()), "valid body config rejected"); + Check(config.functions.at(kEntry).bodyOwner == kBase, "body owner lost by parser"); + Check(config.outDirectoryPath == "generated", "output path lost by parser"); + return config; +} + +int main(int argc, char** argv) try { + Check(argc == 2, "expected output directory"); + fs::path root = fs::absolute(argv[1]); + auto config = Config(root); + auto ctx = Context(root, config); + CodegenWriter writer(ctx); + Check(writer.write(false), "valid body emission failed"); + + auto deferred = Context(root / "deferred", config, false, kBase + 0x10); + CodegenWriter deferredWriter(deferred); + Check(deferredWriter.write(false), "mapped unsealed interior branch rejected"); + + // Capture a pending node before graph notification resolves the external + // target. Test this stale snapshot directly with the production emitter: + // normal discovery usually resolves it immediately, but the wrapper must + // still honor owner metadata instead of inventing a label in a CONFIG hole. + auto external = Context(root / "external", config, false, kBase + 0x30, true); + FunctionNode snapshot = *external.graph.getFunction(kEntry); + snapshot.setName("pending_external_snapshot"); + auto* externalTarget = external.graph.addFunction(kBase + 0x30, 12, + FunctionAuthority::CONFIG, true); + externalTarget->discover({{kBase + 0x30, 12}}, {}, {}); + externalTarget->seal(); + external.graph.addCallToFunction(kBase, kBase + 0x1C, + CallTarget::function(externalTarget)); + const auto* externalOwner = external.graph.getFunction(kBase); + Check(externalOwner->containsAddress(kBase + 0x30), "fixture must exercise CONFIG hole fallback"); + Check(snapshot.unresolvedJumps().size() == 1, "snapshot lost its pending branch"); + EmitContext emission{external.binary(), external.Config(), external.graph, kBase + 0x80}; + auto code = externalOwner->emitCpp(emission, &snapshot); + Check(code.find("goto loc_82000030") == std::string::npos, + "resolved external call was promoted to an un-emitted local label"); + std::ofstream(root / "external_snapshot.cpp") + << "#include \"interior_pch.h\"\n" + "DECLARE_REX_FUNC(xstart);\nDECLARE_REX_FUNC(sub_82000030);\n" + << externalTarget->emitCpp(emission) << code; + + auto reject = [&](RecompilerConfig invalid, const char* name, bool missingEntry = false, + uint32_t pendingTarget = 0) { + auto out = root / name; + auto bad = Context(out, std::move(invalid), missingEntry, pendingTarget); + CodegenWriter rejected(bad); + Check(!rejected.write(true), "invalid body accepted even with force"); + Check(!fs::exists(out / "generated"), "invalid body created output"); + }; + auto invalid = config; + invalid.functions.at(kEntry).bodyOwner = kBase + 0x30; + reject(invalid, "missing-owner"); + reject(config, "missing-entry-in-owner", true); + reject(config, "pending-target-gap", false, kBase + 0x30); + reject(config, "pending-target-outside-image", false, kBase + 0x94); + invalid = config; + invalid.functions.at(kEntry).bodyOwner = kEntry; + reject(invalid, "self-owner"); + invalid = config; + invalid.functions[kBase].bodyOwner = kEntry; + reject(invalid, "cyclic-owner"); + invalid = config; + invalid.functions.at(kEntry).parent = kBase; + reject(invalid, "chunk-owner"); + invalid = config; + invalid.functions.at(kEntry).bodyOwner = kBase + 1; + reject(invalid, "unaligned-owner"); + invalid = config; + invalid.rexcrtFunctions["test"] = kEntry; + reject(invalid, "rexcrt-entry"); + constexpr std::array flags{ + &RecompilerConfig::ctrAsLocalVariable, &RecompilerConfig::xerAsLocalVariable, + &RecompilerConfig::reservedRegisterAsLocalVariable, + &RecompilerConfig::crRegistersAsLocalVariables, + &RecompilerConfig::nonArgumentRegistersAsLocalVariables, + &RecompilerConfig::nonVolatileRegistersAsLocalVariables}; + unsigned index = 0; + for (auto flag : flags) { + invalid = config; + invalid.*flag = true; + auto name = "localization-" + std::to_string(index++); + reject(invalid, name.c_str()); + } + // Invalid body values must fail config loading, rather than silently discard + // the override and emit the original lossy isolated function. + for (const char* value : {"'bad'", "0", "0x82000018", "0x82000001", "-1", + "0x100000000"}) { + auto path = root / "invalid.toml"; + std::ofstream(path) << "file_path = 'synthetic.bin'\n" + "[functions]\n0x82000018 = { body = " << value << " }\n"; + RecompilerConfig bad; + Check(!bad.Load(path.string()), "invalid TOML body accepted"); + } + std::cout << "Real sealed/deferred codegen body emission and 21 rejection cases passed\n"; + return 0; +} catch (const std::exception& e) { + std::cerr << e.what() << '\n'; + return 1; +} diff --git a/tests/regression/test_gapfill_cleanup.py b/tests/regression/test_gapfill_cleanup.py new file mode 100644 index 0000000..e63b36e --- /dev/null +++ b/tests/regression/test_gapfill_cleanup.py @@ -0,0 +1,212 @@ +"""Compare the production cleanup sweep with its former all-graph algorithm.""" +import argparse +from pathlib import Path +import subprocess + + +def function(source, signature): + start = source.index(signature) + opening = source.index('{', start) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('output', type=Path) +parser.add_argument('--compiler', default='clang++') +parser.add_argument('--sdk', type=Path) +args = parser.parse_args() +sdk = args.sdk or Path(__file__).resolve().parents[2] +cleanup = function((sdk / 'src/codegen/phase_gapfill.cpp').read_text(), + 'void cleanupAbsorbedGapFills(') +contains = function((sdk / 'src/codegen/function_graph.cpp').read_text(), + 'bool FunctionNode::containsAddress(') +opening = contains.index('{') + 1 +contains = contains[:opening] + '\n ++containsQueries;\n' + contains[opening:] +types = (sdk / 'include/rex/codegen/function_types.h').read_text() +block_start = types.index('struct Block {') +block = types[block_start:types.index('};', block_start) + 2] +node_header = (sdk / 'include/rex/codegen/function_node.h').read_text() +queries = '\n'.join(function(node_header, signature) for signature in ( + 'uint32_t base() const', 'uint32_t end() const', 'FunctionAuthority authority() const')) +# Preserve the exact former predicate and batch-removal order. Both algorithms +# execute the current production containsAddress/Block::contains implementations. +baseline = r''' +void cleanupAbsorbedGapFills(CodegenContext& ctx) { + auto& graph = ctx.graph; + std::vector toRemove; + for (const auto& [addr, node] : graph.functions()) { + if (node->authority() != FunctionAuthority::GAP_FILL) continue; + for (const auto& [otherAddr, otherNode] : graph.functions()) { + if (otherAddr == addr) continue; + if (!otherNode->containsAddress(addr)) continue; + if (otherNode->authority() != FunctionAuthority::GAP_FILL) { + toRemove.push_back(addr);break; + } else if (otherAddr < addr) { + toRemove.push_back(addr);break; + } + } + } + for (uint32_t addr : toRemove) graph.removeFunction(addr); +} +''' +harness = r''' +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define REXCODEGEN_TRACE(...) ((void)0) +enum class FunctionAuthority {GAP_FILL, DISCOVERED, VTABLE, HELPER, PDATA, CONFIG, IMPORT}; +''' + block + r''' +struct FunctionNode { + static inline uint64_t containsQueries=0; + uint32_t base_,size_;FunctionAuthority authority_;std::vector blocks_; + FunctionNode(uint32_t base,uint32_t size,FunctionAuthority authority,std::vector blocks) + :base_(base),size_(size),authority_(authority),blocks_(std::move(blocks)){} + bool containsAddress(uint32_t)const; +''' + queries + r''' +}; +struct FunctionGraph { + using Storage=std::unordered_map>; + Storage entries;mutable uint64_t iterations=0,scans=0;std::vector removed; + struct Range { + const FunctionGraph* graph; + struct Iterator { + Storage::const_iterator cursor;const FunctionGraph* graph; + auto& operator*()const{return *cursor;} + Iterator& operator++(){++graph->iterations;++cursor;return *this;} + bool operator!=(const Iterator& other)const{return cursor!=other.cursor;} + }; + auto begin()const{++graph->scans;return Iterator{graph->entries.begin(),graph};} + auto end()const{return Iterator{graph->entries.end(),graph};} + auto size()const{return graph->entries.size();} + }; + Range functions()const{return {this};} + bool removeFunction(uint32_t addr){removed.push_back(addr);return entries.erase(addr)==1;} +}; +struct CodegenContext {FunctionGraph graph;}; +''' + contains + '\nnamespace before {\n' + baseline + '\n}\nnamespace after {\n' + cleanup + '\n}\n' +tests = r''' +using Authority=FunctionAuthority; +struct Spec {uint32_t base,size;Authority authority;std::vector blocks;}; +CodegenContext Make(const std::vector& specs) { + CodegenContext ctx; + for(const auto& spec:specs) { + assert(!ctx.graph.entries.contains(spec.base)); + ctx.graph.entries.emplace(spec.base,std::make_unique(spec.base,spec.size,spec.authority,spec.blocks)); + } + return ctx; +} +struct Counts {uint64_t beforeQueries,afterQueries,beforeIterations,afterIterations;}; +Counts Compare(const std::vector& specs,const std::set* expected=nullptr) { + auto old=Make(specs),current=Make(specs); + FunctionNode::containsQueries=0;before::cleanupAbsorbedGapFills(old); + auto oldQueries=FunctionNode::containsQueries; + FunctionNode::containsQueries=0;after::cleanupAbsorbedGapFills(current); + auto newQueries=FunctionNode::containsQueries; + assert(old.graph.removed==current.graph.removed); // Includes original hash-map removal order. + assert(old.graph.entries.size()==current.graph.entries.size()); + for(const auto& [addr,node]:old.graph.entries)assert(current.graph.entries.contains(addr)); + if(expected)assert(std::set(current.graph.removed.begin(),current.graph.removed.end())==*expected); + return {oldQueries,newQueries,old.graph.iterations,current.graph.iterations}; +} +void Expect(std::vector specs,std::set expected) {Compare(specs,&expected);} +void Cases() { + Expect({},{});Expect({{0x1000,16,Authority::GAP_FILL,{}}},{}); + // Empty and wrapped owners never contain anything; zero-size targets may be absorbed. + Expect({{0x1000,0,Authority::CONFIG,{}},{0x1004,0,Authority::GAP_FILL,{}}},{}); + Expect({{0x1000,16,Authority::CONFIG,{}},{0x1004,0,Authority::GAP_FILL,{}}},{0x1004}); + Expect({{0xFFFFFFF0,0x20,Authority::CONFIG,{}}, + {0xFFFFFFF4,4,Authority::GAP_FILL,{}},{4,4,Authority::GAP_FILL,{}}},{}); + Expect({{0,0xFFFFFFFF,Authority::PDATA,{}}, + {0xFFFFFFF0,0x20,Authority::GAP_FILL,{}},{0xFFFFFFFF,0,Authority::GAP_FILL,{}}},{0xFFFFFFF0}); + // End is exclusive, base is inclusive, and owners with larger bases cannot absorb backwards. + Expect({{0x1000,16,Authority::HELPER,{}},{0x0FFC,4,Authority::GAP_FILL,{}}, + {0x1004,4,Authority::GAP_FILL,{}},{0x1010,4,Authority::GAP_FILL,{}}},{0x1004}); + // A nearer overlapping owner does not hide a containing owner with a lower base. + Expect({{0x1000,0x400,Authority::PDATA,{}},{0x1100,4,Authority::CONFIG,{}}, + {0x1200,4,Authority::GAP_FILL,{}}},{0x1200}); + for(auto authority:{Authority::GAP_FILL,Authority::DISCOVERED,Authority::VTABLE, + Authority::HELPER,Authority::IMPORT}) { + Expect({{0x1000,0x100,authority,{{0x1000,4},{0x1080,8}}}, + {0x1004,4,Authority::GAP_FILL,{}},{0x1080,4,Authority::GAP_FILL,{}}, + {0x1088,4,Authority::GAP_FILL,{}},{0x1100,4,Authority::GAP_FILL,{}}},{0x1080}); + } + for(auto authority:{Authority::PDATA,Authority::CONFIG}) { + Expect({{0x1000,0x100,authority,{{0x1000,4},{0x1080,8}}}, + {0x1004,4,Authority::GAP_FILL,{}},{0x1080,4,Authority::GAP_FILL,{}}, + {0x1088,4,Authority::GAP_FILL,{}},{0x1100,4,Authority::GAP_FILL,{}}}, + {0x1004,0x1080,0x1088}); + } + // Blocks outside overall bounds and wrapped blocks remain ineffective. + Expect({{0x1000,16,Authority::DISCOVERED,{{0x1050,32}}}, + {0x1050,4,Authority::GAP_FILL,{}}},{}); + Expect({{0,0x100,Authority::DISCOVERED,{{0xFFFFFFF0,0x30}}}, + {4,4,Authority::GAP_FILL,{}}},{}); + // B is absorbed by A, but must remain an owner while C is classified. + Expect({{0x1000,0x104,Authority::GAP_FILL,{{0x1000,4},{0x1100,4}}}, + {0x1100,0x104,Authority::GAP_FILL,{{0x1100,4},{0x1200,4}}}, + {0x1200,4,Authority::GAP_FILL,{}}},{0x1100,0x1200}); + // Multiple ends tie at a target point and must all expire before checking it. + Expect({{0x1000,0x100,Authority::HELPER,{}},{0x1080,0x80,Authority::GAP_FILL,{}}, + {0x1100,4,Authority::GAP_FILL,{}}},{0x1080}); +} +void RandomGraphs() { + std::mt19937 random(0xD1A3); + for(unsigned round=0;round<512;++round) { + std::vector specs; + for(unsigned i=0;i<48;++i) { + uint32_t base=(round%3==0?0xFFFFFC00u:0x1000u)+i*16; + uint32_t size=(random()%40)*4; + if(random()%17==0)size=0xFFFFFFFFu; + Spec spec{base,size,static_cast(random()%7),{}}; + if(random()%3!=0) { + for(unsigned j=0,count=1+random()%4;j(base+(random()%48)*4), + static_cast((random()%16)*4)}); + } + specs.push_back(std::move(spec)); + } + std::shuffle(specs.begin(),specs.end(),random);Compare(specs); + } +} +void Scaling() { + for(uint32_t count:{200u,1000u}) { + std::vector sparse; + for(uint32_t i=0;i %llu; graph iterations %llu -> %llu\n",count, + static_cast(counts.beforeQueries),static_cast(counts.afterQueries), + static_cast(counts.beforeIterations),static_cast(counts.afterIterations)); + } + std::vector nested; + for(uint32_t i=0;i<128;++i)nested.push_back({0x1000+i*4,0x10000-i*4,Authority::GAP_FILL,{}}); + auto counts=Compare(nested);assert(counts.afterQueries==127&&counts.afterIterations==256); +} +int main(){Cases();RandomGraphs();Scaling(); + std::puts("PASS: production gap cleanup equivalence, removal order, holes, overlap, wraps, chains and bounded scaling");} +''' +args.output.mkdir(parents=True, exist_ok=True) +cpp = args.output.resolve() / 'gapfill-cleanup.cpp' +exe = args.output.resolve() / 'gapfill-cleanup.exe' +cpp.write_text(harness + tests) +subprocess.run([args.compiler, '-std=c++20', '-UNDEBUG', str(cpp), '-o', str(exe)], + check=True, timeout=45) +subprocess.run([str(exe)], check=True, timeout=10) diff --git a/tests/regression/test_graph_registration.py b/tests/regression/test_graph_registration.py new file mode 100644 index 0000000..a8901f1 --- /dev/null +++ b/tests/regression/test_graph_registration.py @@ -0,0 +1,311 @@ +"""Count production graph notifications and preserve unresolved-owner lifecycle.""" +import argparse +from pathlib import Path +import re +import subprocess + + +def function(source, signature): + start = source.index(signature) + opening = source.index('{', start) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +p = argparse.ArgumentParser(description=__doc__) +p.add_argument('output', type=Path) +p.add_argument('--compiler', default='clang++') +p.add_argument('--sdk', type=Path) +a = p.parse_args() +sdk = a.sdk or Path(__file__).resolve().parents[2] +source = (sdk / 'src/codegen/function_graph.cpp').read_text() +header = (sdk / 'include/rex/codegen/function_graph.h').read_text() +node_header = (sdk / 'include/rex/codegen/function_node.h').read_text() +index = re.search(r' std::unordered_set unresolvedFunctionEntries_;', header).group(0) +# Node mutation is private: a new unresolved insertion path must update the index. +assert source.count('unresolvedJumps_.push_back(') == 1 +assert re.findall(r'(?:->|\.)addUnresolvedJump\(', source) == ['->addUnresolvedJump('] +assert node_header.index('void addUnresolvedJump(') > node_header.index(' private:') +notification = function(source, 'void FunctionGraph::notifyFunctionAdded(') +bodies = '\n'.join(function(source, signature) for signature in ( + 'FunctionNode::FunctionNode(', 'void FunctionNode::discover(', + 'void FunctionNode::discoverAsImport(', 'bool FunctionNode::canSeal(', + 'void FunctionNode::seal(', 'void FunctionNode::addBlock(', + 'bool FunctionNode::containsAddress(', 'void FunctionNode::addLabel(', + 'void FunctionNode::addCall(', 'void FunctionNode::addTailCall(', + 'void FunctionNode::addUnresolvedJump(', 'void FunctionNode::removeUnresolvedJump(', + 'bool FunctionNode::tryResolveAgainst(', 'bool FunctionNode::tryResolveAsInternalLabel(', + 'void FunctionNode::absorbRegion(', + 'FunctionNode* FunctionGraph::addFunction(uint32_t base, uint32_t size, FunctionAuthority authority,', + 'FunctionNode* FunctionGraph::getFunction(uint32_t entryPoint)', + 'bool FunctionGraph::removeFunction(', 'void FunctionGraph::addUnresolvedJumpToFunction(', + 'size_t FunctionGraph::tryResolveFunction(', 'void FunctionGraph::absorbRegionIntoFunction(', + 'bool FunctionGraph::trySealFunction(', 'size_t FunctionGraph::sealAllReady(', + 'void FunctionGraph::sealAll(', 'void FunctionGraph::notifyFunctionAdded(')) +# Count attempts inside the real node resolver. Do not depend on wall-clock timing. +resolver = 'bool FunctionNode::tryResolveAgainst(FunctionNode* newFunction) {' +assert bodies.count(resolver) == 1 +bodies = bodies.replace(resolver, resolver + '\n ++resolutionAttempts;') +node_queries = '\n'.join(function(node_header, signature) for signature in ( + 'bool isPending() const', 'bool isSealed() const', 'bool isRegistered() const', + 'bool canDiscover() const', 'bool isImport() const', 'bool hasUnresolvedJumps() const')) +# The immediately preceding algorithm uses a monotonic "ever unresolved" flag, +# then scans every pending graph entry on each registration. Keep all other +# production bodies identical for the behavioral comparison. +baseline_notification = ''' +void FunctionGraph::notifyFunctionAdded(FunctionNode* newFunction) { + if (!hasUnresolvedJumpsEver_) return; + for (auto& [base,node] : functions_) { + if(node.get()!=newFunction && node->isPending()) node->tryResolveAgainst(newFunction); + } +} +''' +baseline = bodies.replace(notification, baseline_notification) +append = 'node->addUnresolvedJump(site, target, isCall, conditional);' +assert baseline.count(append) == 1 +baseline = baseline.replace(append, append + '\n hasUnresolvedJumpsEver_=true;') +fixture = r''' +uint64_t resolutionAttempts=0; +enum class FunctionAuthority { GAP_FILL, DISCOVERED, VTABLE, HELPER, PDATA, CONFIG, IMPORT }; +enum class FunctionState { kRegistered, kDiscovered, kSealed }; +struct Block {uint32_t base,size;uint32_t end()const{return base+size;} + bool contains(uint32_t addr)const{return addr>=base&&addr blocks_;std::vector instructions_; + std::set labels_;std::optional analysis_; + std::vector unresolvedJumps_; + std::vector calls_,tailCalls_; + FunctionNode(uint32_t,uint32_t,FunctionAuthority); + uint32_t base() const{return base_;} + FunctionAuthority authority() const{return authority_;} + const std::string& name() const{return name_;} + const auto& blocks()const{return blocks_;} + const auto& unresolvedJumps()const{return unresolvedJumps_;} + void discover(std::vector,std::vector,std::set); + void discoverAsImport();bool canSeal()const;void seal(); + void addBlock(Block);bool containsAddress(uint32_t)const;void addLabel(uint32_t); + void addCall(uint32_t,CallTarget);void addTailCall(uint32_t,CallTarget); + void addUnresolvedJump(uint32_t,uint32_t,bool,bool);void removeUnresolvedJump(uint32_t); + bool tryResolveAgainst(FunctionNode*);bool tryResolveAsInternalLabel(uint32_t); + void absorbRegion(uint32_t,uint32_t); +''' + node_queries + r''' +}; +// Count full-map traversal, retaining real hash lookup/storage and normal moves. +struct CountedFunctions { + using Storage=std::unordered_map>; + Storage entries;uint64_t scans=0,iterations=0; + struct Iterator { + Storage::iterator cursor;CountedFunctions* owner; + auto& operator*() const{return *cursor;} + auto operator->() const{return cursor.operator->();} + Iterator& operator++(){++owner->iterations;++cursor;return *this;} + bool operator==(const Iterator& other) const{return cursor==other.cursor;} + bool operator!=(const Iterator& other) const{return !(*this==other);} + }; + Iterator begin(){++scans;return {entries.begin(),this};} + Iterator end(){return {entries.end(),this};} + Iterator find(uint32_t base){return {entries.find(base),this};} + auto& operator[](uint32_t base){return entries[base];} + void erase(Iterator it){entries.erase(it.cursor);} +}; +struct FunctionGraph { + CountedFunctions functions_; + std::map functionsByBase_; + std::unordered_map functionHasXrefs_; + bool hasUnresolvedJumpsEver_=false; // Used only by the reconstructed baseline. +''' + index + r''' + FunctionNode* addFunction(uint32_t,uint32_t,FunctionAuthority,bool=false); + FunctionNode* getFunction(uint32_t);bool removeFunction(uint32_t); + bool isImport(uint32_t base){auto* node=getFunction(base); + return node&&node->authority()==FunctionAuthority::IMPORT;} + void addUnresolvedJumpToFunction(uint32_t,uint32_t,uint32_t,bool,bool); + size_t tryResolveFunction(uint32_t);void absorbRegionIntoFunction(uint32_t,uint32_t,uint32_t); + bool trySealFunction(uint32_t);size_t sealAllReady();void sealAll(); + void notifyFunctionAdded(FunctionNode*); +}; +''' +tests = r''' +void TestRegistrationAndGapFill(bool baseline) { + FunctionGraph graph; + constexpr uint32_t count=1000,base=0x82000000,target=0x83000000; + for(uint32_t i=0;iisRegistered()&&!node->hasUnresolvedJumps()); + assert(graph.functionsByBase_.at(node->base())==node); + assert(graph.functionHasXrefs_.at(node->base())); + } + assert(graph.unresolvedFunctionEntries_.empty()&&graph.functions_.iterations==0); + auto* owner=graph.getFunction(base); + graph.addUnresolvedJumpToFunction(base,base+4,target,false,false); + assert(graph.unresolvedFunctionEntries_.size()==1); + resolutionAttempts=0; + for(uint32_t i=0;iunresolvedJumps().size()==1); + std::printf("%s: %u gap registrations, %llu full-graph iterations, %llu resolver attempts\n", + baseline?"before":"after",count, + static_cast(graph.functions_.iterations), + static_cast(resolutionAttempts)); + auto* targetNode=graph.addFunction(target,4,FunctionAuthority::PDATA); + assert(!owner->hasUnresolvedJumps()&&owner->tailCalls_.back().target.node==targetNode); + if(!baseline)assert(graph.unresolvedFunctionEntries_.empty()); + auto scans=graph.functions_.scans; + auto attempts=resolutionAttempts; + graph.addFunction(target+16,4,FunctionAuthority::GAP_FILL); + if(!baseline)assert(graph.functions_.scans==scans&&resolutionAttempts==attempts); +} +void TestResolutionAndIndexLifecycle(bool baseline) { + FunctionGraph graph; + constexpr uint32_t caller=0x82000000,known=0x82000100,target=0x82000200, + other=0x82000300,sealed=0x82000400; + auto* node=graph.addFunction(caller,32,FunctionAuthority::PDATA,true); + node->discover({{caller,32}}, {}, {}); + auto* knownNode=graph.addFunction(known,4,FunctionAuthority::IMPORT,true); + graph.addUnresolvedJumpToFunction(0,caller+4,target,false,false); + graph.addUnresolvedJumpToFunction(caller,caller+4,known,true,false); + graph.addUnresolvedJumpToFunction(caller,caller+8,known,false,false); + assert(graph.unresolvedFunctionEntries_.empty()&&!node->hasUnresolvedJumps()); + assert(node->calls_.size()==1&&node->calls_[0].target.node==knownNode); + assert(node->tailCalls_.size()==1&&node->tailCalls_[0].target.node==knownNode); + graph.addUnresolvedJumpToFunction(caller,caller+12,target,true,true); + graph.addUnresolvedJumpToFunction(caller,caller+16,target,false,false); + auto* sealedNode=graph.addFunction(sealed,4,FunctionAuthority::IMPORT,true); + graph.addUnresolvedJumpToFunction(sealed,sealed,target,false,false); + sealedNode->discoverAsImport();sealedNode->seal(); // Public sealing bypasses graph helpers. + graph.addFunction(other,4,FunctionAuthority::PDATA,true); + assert(node->unresolvedJumps().size()==2&&sealedNode->unresolvedJumps().size()==1); + if(!baseline)assert(!graph.unresolvedFunctionEntries_.contains(sealed)); + auto* targetNode=graph.addFunction(target,4,FunctionAuthority::PDATA,true); + assert(!node->hasUnresolvedJumps()&&node->tailCalls_.size()==3); + // Preserve the existing reactive resolver: even the isCall branch becomes a tail call. + assert(node->tailCalls_[1].site==caller+12&&node->tailCalls_[1].target.node==targetNode); + assert(node->tailCalls_[2].site==caller+16&&node->tailCalls_[2].target.node==targetNode); + assert(sealedNode->unresolvedJumps().size()==1&&sealedNode->tailCalls_.empty()); + if(!baseline)assert(graph.unresolvedFunctionEntries_.empty()); + assert(graph.removeFunction(caller)&&graph.removeFunction(sealed)); + assert(!graph.removeFunction(caller)); + + auto* low=graph.addFunction(caller,16,FunctionAuthority::DISCOVERED); + graph.addUnresolvedJumpToFunction(caller,caller+4,target+32,false,false); + assert(graph.addFunction(caller,4,FunctionAuthority::GAP_FILL)==low); + assert(graph.unresolvedFunctionEntries_.contains(caller)); + auto* replacement=graph.addFunction(caller,16,FunctionAuthority::CONFIG); + assert(replacement!=low&&!replacement->hasUnresolvedJumps()); + assert(!graph.unresolvedFunctionEntries_.contains(caller)); + graph.addUnresolvedJumpToFunction(caller,caller+4,target+48,false,false); + assert(graph.removeFunction(caller)&&graph.unresolvedFunctionEntries_.empty()); + graph.addFunction(target+32,4,FunctionAuthority::GAP_FILL); + graph.addFunction(target+48,4,FunctionAuthority::GAP_FILL); +} +void TestExplicitResolutionAndSealing() { + FunctionGraph graph; + constexpr uint32_t entry=0x82000000,target=0x82000080; + auto* node=graph.addFunction(entry,16,FunctionAuthority::PDATA); + graph.addUnresolvedJumpToFunction(entry,entry+4,target,false,false); + node->discover({{entry,16}}, {}, {}); // Discovery retains a registered owner's index entry. + assert(graph.unresolvedFunctionEntries_.contains(entry)); + assert(!graph.trySealFunction(entry)&&graph.tryResolveFunction(entry)==0); + graph.absorbRegionIntoFunction(entry,target,4); + assert(graph.tryResolveFunction(entry)==1&&node->labels_.contains(target)); + assert(graph.unresolvedFunctionEntries_.empty()&&graph.trySealFunction(entry)); + assert(!graph.trySealFunction(entry)&&graph.tryResolveFunction(entry)==0); + graph.addUnresolvedJumpToFunction(entry,entry+8,target+16,false,false); + assert(graph.unresolvedFunctionEntries_.empty()); // Sealed nodes remain ineligible. + graph.addFunction(target+16,4,FunctionAuthority::PDATA); + assert(node->unresolvedJumps().size()==1); + + for(int mode=0;mode<3;++mode){ + FunctionGraph imports; + auto* import=imports.addFunction(entry,4,FunctionAuthority::IMPORT); + imports.addUnresolvedJumpToFunction(entry,entry,target,false,false); + import->discoverAsImport(); + if(mode==0)assert(imports.trySealFunction(entry)); + if(mode==1)assert(imports.sealAllReady()==1); + if(mode==2)imports.sealAll(); + assert(import->isSealed()&&import->hasUnresolvedJumps()); + assert(imports.unresolvedFunctionEntries_.empty()); + } + FunctionGraph partial; + auto* import=partial.addFunction(entry,4,FunctionAuthority::IMPORT); + partial.addUnresolvedJumpToFunction(entry,entry,target,false,false);import->discoverAsImport(); + auto* pending=partial.addFunction(entry+32,4,FunctionAuthority::PDATA); + partial.addUnresolvedJumpToFunction(entry+32,entry+32,target+4,false,false); + bool threw=false;try{partial.sealAll();}catch(const std::runtime_error&){threw=true;} + assert(threw&&import->isSealed()&&pending->isRegistered()); + assert(!partial.unresolvedFunctionEntries_.contains(entry)); + assert(partial.unresolvedFunctionEntries_.contains(entry+32)); +} +void TestMoves() { + constexpr uint32_t entry=0x82000000,target=0x82001000; + FunctionGraph graph;auto* owner=graph.addFunction(entry,4,FunctionAuthority::PDATA); + graph.addUnresolvedJumpToFunction(entry,entry,target,false,false); + FunctionGraph moved(std::move(graph)); + assert(moved.getFunction(entry)==owner&&moved.unresolvedFunctionEntries_.contains(entry)); + auto* next=moved.addFunction(target,4,FunctionAuthority::PDATA); + assert(!owner->hasUnresolvedJumps()&&owner->tailCalls_.back().target.node==next); + assert(moved.unresolvedFunctionEntries_.empty()); + moved.addUnresolvedJumpToFunction(entry,entry,target+32,false,false); + FunctionGraph assigned; + assigned.addFunction(entry+16,4,FunctionAuthority::PDATA); + assigned.addUnresolvedJumpToFunction(entry+16,entry+16,target+64,false,false); + assigned=std::move(moved); + assert(!assigned.getFunction(entry+16)); + assert(assigned.unresolvedFunctionEntries_.size()==1); + assigned.addFunction(target+32,4,FunctionAuthority::PDATA); + assert(!owner->hasUnresolvedJumps()&&assigned.unresolvedFunctionEntries_.empty()); +} +''' +code = r''' +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define REXCODEGEN_TRACE(...) ((void)0) +#define REXCODEGEN_DEBUG(...) ((void)0) +namespace rex::codegen::ppc {struct Instruction;} +namespace fmt {templatestd::string format(const char* value,Args&&...){return value;}} +''' +code += '\nnamespace current {\n' + fixture + bodies + tests + '\n}\n' +code += '\nnamespace baseline {\n' + fixture + baseline + tests + '\n}\n' +code += r''' +int main(){ + baseline::TestRegistrationAndGapFill(true);current::TestRegistrationAndGapFill(false); + baseline::TestResolutionAndIndexLifecycle(true);current::TestResolutionAndIndexLifecycle(false); + current::TestExplicitResolutionAndSealing();current::TestMoves(); + std::puts("PASS: indexed gap registration; immediate/deferred/internal resolution, replacement/removal, sealing and graph moves"); +} +''' +a.output.mkdir(parents=True, exist_ok=True) +cpp = a.output.resolve() / 'graph-registration.cpp' +exe = a.output.resolve() / 'graph-registration.exe' +cpp.write_text(code) +subprocess.run([a.compiler, '-std=c++20', '-UNDEBUG', str(cpp), '-o', str(exe)], + check=True, timeout=45) +subprocess.run([str(exe)], check=True, timeout=10) diff --git a/tests/regression/test_interior_entries.py b/tests/regression/test_interior_entries.py new file mode 100644 index 0000000..b9ce985 --- /dev/null +++ b/tests/regression/test_interior_entries.py @@ -0,0 +1,103 @@ +"""Execute actual CodegenWriter output for explicit callable interior entries.""" +import argparse +from pathlib import Path +import subprocess + + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('output', type=Path) +parser.add_argument('--compiler', default='clang++') +parser.add_argument('--producer', type=Path, required=True) +parser.add_argument('--sdk', type=Path) +args = parser.parse_args() +sdk = args.sdk or Path(__file__).resolve().parents[2] +args.output.mkdir(parents=True, exist_ok=True) +subprocess.run([str(args.producer.resolve()), str(args.output.resolve())], + check=True, timeout=15) +sealed = args.output / 'generated' +generated = args.output / 'deferred/generated' +sources = sorted(generated.glob('interior_recomp.*.cpp')) +assert sources, 'producer emitted no real recompiled translation units' +for source in sources: + assert source.read_bytes() == (sealed / source.name).read_bytes(), \ + 'safely deferred alias changed the emitted instructions' +combined = '\n'.join(source.read_text() for source in sources) +assert 'goto loc_82000018;' in combined +assert 'goto loc_82000048;' in combined +assert 'REX_FATAL' not in combined, 'body preservation left an unresolved branch' +assert 'branch to 0x82000010 outside function' not in combined +# The isolated entry's conflicting classification must not tail-call its owner. +# Full generated sources and mapping table are compiled unchanged below. +main = args.output / 'execute.cpp' +main.write_text(r''' +#include "interior_init.h" +#include +DECLARE_REX_FUNC(pending_external_snapshot); + +PPCFunc* Find(size_t address) { + for (auto* mapping = PPCFuncMappings; mapping->host; ++mapping) + if (mapping->guest == address) return mapping->host; + return nullptr; +} + +int main() { + alignas(32) uint8_t memory[32]{}; + auto normal = Find(0x82000000); + auto interior = Find(0x82000018); + auto extraNormal = Find(0x82000040); + auto extraInterior = Find(0x82000048); + if (!normal || !interior || normal == interior || + !extraNormal || !extraInterior || extraNormal == extraInterior) return 1; + PPCContext ctx{}; + ctx.r1.u64 = 0x1000; + normal(ctx, memory); + if (ctx.r1.u64 != 0x1000 || ctx.r3.u64 != 4 || ctx.r5.u64 != 4 || ctx.ctr.u64 != 0) + return 2; + // The caller is already inside the guest frame. The interior entry must + // preserve r3/CTR, loop backwards, and run the single existing epilogue. + ctx = {}; + ctx.r1.u64 = 0xFF0; + ctx.r3.u64 = 0; + ctx.r4.u64 = 99; + ctx.ctr.u64 = 3; + interior(ctx, memory); + if (ctx.r1.u64 != 0x1000 || ctx.r3.u64 != 3 || ctx.r5.u64 != 3 || + ctx.r4.u64 != 99 || ctx.ctr.u64 != 0) return 3; + ctx = {}; + ctx.r1.u64 = 0xFF0; + ctx.r3.u64 = 7; + ctx.ctr.u64 = 2; + interior(ctx, memory); + if (ctx.r1.u64 != 0x1000 || ctx.r3.u64 != 8 || ctx.r5.u64 != 1 || ctx.ctr.u64 != 0) + return 4; + ctx = {}; + ctx.r1.u64 = 0x1000; + extraNormal(ctx, memory); + if (ctx.r1.u64 != 0x1000 || ctx.r6.u64 != 0) return 5; + ctx = {}; + ctx.r1.u64 = 0xFF0; + ctx.r6.u64 = 10; + extraInterior(ctx, memory); + if (ctx.r1.u64 != 0x1000 || ctx.r6.u64 != 11) return 6; + ctx = {}; + ctx.r1.u64 = 0xFF0; + ctx.r3.u64 = 1; + ctx.r7.u64 = 40; + pending_external_snapshot(ctx, memory); + if (ctx.r1.u64 != 0x1000 || ctx.r7.u64 != 41) return 7; + std::puts("Actual generated normal/interior mappings, backward branches, CTR, calls, extra blocks and epilogues passed"); +} +''') +binary = args.output / 'execute' +command = [args.compiler, '-std=c++23', '-O1', '-march=x86-64-v2', + '-DSPDLOG_FMT_EXTERNAL', + '-I' + str(generated), '-I' + str(sdk / 'include'), + '-I' + str(sdk / 'thirdparty/simde'), + '-I' + str(sdk / 'thirdparty/fmt/include'), + '-I' + str(sdk / 'thirdparty/spdlog/include'), + *map(str, sources), str(generated / 'interior_init.cpp'), + str(args.output / 'external_snapshot.cpp'), str(main), + '-o', str(binary)] +(args.output / 'compile-command.txt').write_text('\n'.join(command) + '\n') +subprocess.run(command, check=True, timeout=40) +subprocess.run([str(binary.resolve())], check=True, timeout=5) From 97e37e260f0bc6511a3b1d4aea0db8d156e601e0 Mon Sep 17 00:00:00 2001 From: AlenHay <82121826+AlenHay@users.noreply.github.com> Date: Wed, 7 Oct 2026 09:40:28 +0200 Subject: [PATCH 2/3] Emit compact function registration tables instead of oversized call blocks --- resources/templates/codegen/register_cpp.inja | 20 ++++- src/codegen/codegen_writer.cpp | 7 ++ tests/regression/emit_interior_entries.cpp | 42 +++++++++ tests/regression/test_interior_entries.py | 89 +++++++++++++++++++ tests/unit/codegen/codegen_writer_test.cpp | 37 ++++++++ 5 files changed, 193 insertions(+), 2 deletions(-) diff --git a/resources/templates/codegen/register_cpp.inja b/resources/templates/codegen/register_cpp.inja index 0be31c4..54b722f 100644 --- a/resources/templates/codegen/register_cpp.inja +++ b/resources/templates/codegen/register_cpp.inja @@ -4,6 +4,21 @@ #include "{{ project }}_init.h" #include +#include + +namespace { +struct FunctionRegistration { + uint32_t guest_address; + ::PPCFunc* host_function; +}; + +// Keep registrations as constant data. A game may contain hundreds of +// thousands of entries; emitting that many calls in one body overwhelms +// compiler optimization and instruction selection. +constexpr std::array kFunctionRegistrations = { +{% for fn in registrations %} FunctionRegistration{ {{ fn.address }}, {{ fn.name }} }, +{% endfor %}}; +} // namespace {% if is_dll %} #ifdef _WIN32 @@ -17,8 +32,9 @@ void ReXModule_Register(rex::runtime::IModuleRegistrar* registrar) { {% else %} void {{ project }}_RegisterFunctions(rex::runtime::IModuleRegistrar* registrar) { {% endif %} -{% for fn in functions %}{% if not fn.below_code_base or fn.is_import %} registrar->SetFunction({{ fn.address }}, {{ fn.name }}); -{% endif %}{% endfor %}} + for (const auto& entry : kFunctionRegistrations) + registrar->SetFunction(entry.guest_address, entry.host_function); +} {% if is_dll %} // The runtime uses this baked layout for the dispatch table. It must match the diff --git a/src/codegen/codegen_writer.cpp b/src/codegen/codegen_writer.cpp index c11f21e..80b1e3e 100644 --- a/src/codegen/codegen_writer.cpp +++ b/src/codegen/codegen_writer.cpp @@ -168,6 +168,7 @@ nlohmann::json buildTemplateData(const rex::codegen::CodegenContext& ctx, // Build functions JSON array nlohmann::json functionsJson = nlohmann::json::array(); + nlohmann::json registrationsJson = nlohmann::json::array(); for (const auto* fn : functions) { std::string funcName; bool isRexcrt = false; @@ -191,6 +192,11 @@ nlohmann::json buildTemplateData(const rex::codegen::CodegenContext& ctx, {"below_code_base", (fn->base() < codeMin)}, {"is_import", fn->authority() == rex::codegen::FunctionAuthority::IMPORT}, }); + // Preserve the registration order and filtering used by the mapping + // table, including import thunks below the executable code range. + if (fn->base() >= codeMin || fn->authority() == rex::codegen::FunctionAuthority::IMPORT) + registrationsJson.push_back({{"address", fmt::format("0x{:X}", fn->base())}, + {"name", funcName}}); } // Build config flags @@ -217,6 +223,7 @@ nlohmann::json buildTemplateData(const rex::codegen::CodegenContext& ctx, {"is_dll", ctx.isDllModule()}, {"config_flags", configFlags}, {"functions", functionsJson}, + {"registrations", registrationsJson}, {"recomp_files", nlohmann::json::array()}, }; } diff --git a/tests/regression/emit_interior_entries.cpp b/tests/regression/emit_interior_entries.cpp index 160c943..a3d0942 100644 --- a/tests/regression/emit_interior_entries.cpp +++ b/tests/regression/emit_interior_entries.cpp @@ -41,6 +41,7 @@ std::vector Bytes(bool externalHole = false) { put(0x20, 0x4200FFF0); // bdnz +0x10 put(0x24, 0x38210010); // addi r1,r1,16 put(0x28, 0x4E800020); // blr + put(0x30, 0x4E800020); // standalone hook target for registration tests if (externalHole) { put(0x30, 0x38210010); // external tail callee restores existing frame put(0x34, 0x38E70001); // addi r7,r7,1 @@ -141,6 +142,47 @@ int main(int argc, char** argv) try { CodegenWriter deferredWriter(deferred); Check(deferredWriter.write(false), "mapped unsealed interior branch rejected"); + // Exercise registration through the same actual writer as interior bodies. + // The below-code non-import is a rexcrt mapping so no out-of-image body is + // emitted. Its declaration must not become a registration. + auto registration = Context(root / "registration", config); + Check(registration.graph.addImportFunction(kBase - 8, "__imp__registration_import") != nullptr, + "registration import rejected"); + Check(registration.graph.addFunction(kBase - 4, 4, FunctionAuthority::CONFIG, true) != nullptr, + "below-code fixture node rejected"); + registration.Config().rexcrtFunctions["registration_suppressed"] = kBase - 4; + auto* hooked = registration.graph.addFunction(kBase + 0x30, 4, + FunctionAuthority::CONFIG, "registration_hooked", true); + Check(hooked != nullptr, "hook fixture node rejected"); + hooked->discover({{kBase + 0x30, 4}}, {}, {}); + hooked->seal(); + CodegenWriter registrationWriter(registration); + Check(registrationWriter.write(false), "registration fixture emission failed"); + + for (const char* project : {"empty", "single", "dll"}) { + const std::array bytes{0x4E, 0x80, 0x00, 0x20}; + TestModule module; + module.Load(kBase, bytes.data(), bytes.size()); + RecompilerConfig smallConfig; + smallConfig.projectName = project; + smallConfig.outDirectoryPath = "generated"; + auto small = CodegenContext::Create(BinaryView::fromModule(module), std::move(smallConfig)); + small.setConfigDir(root / project); + small.analysisState().format = "xex"; + small.analysisState().loadAddress = kBase; + small.analysisState().entryPoint = kBase; + small.analysisState().imageSize = bytes.size(); + small.setDllModule(std::string_view(project) == "dll"); + if (std::string_view(project) != "empty") { + auto* node = small.graph.addFunction(kBase, 4, FunctionAuthority::CONFIG, true); + Check(node != nullptr, "single registration node rejected"); + node->discover({{kBase, 4}}, {}, {}); + node->seal(); + } + CodegenWriter smallWriter(small); + Check(smallWriter.write(false), "small registration fixture emission failed"); + } + // Capture a pending node before graph notification resolves the external // target. Test this stale snapshot directly with the production emitter: // normal discovery usually resolves it immediately, but the wrapper must diff --git a/tests/regression/test_interior_entries.py b/tests/regression/test_interior_entries.py index b9ce985..5c04e66 100644 --- a/tests/regression/test_interior_entries.py +++ b/tests/regression/test_interior_entries.py @@ -1,5 +1,6 @@ """Execute actual CodegenWriter output for explicit callable interior entries.""" import argparse +import json from pathlib import Path import subprocess @@ -101,3 +102,91 @@ (args.output / 'compile-command.txt').write_text('\n'.join(command) + '\n') subprocess.run(command, check=True, timeout=40) subprocess.run([str(binary.resolve())], check=True, timeout=5) + +# Compile the actual registration source unchanged. Strong symbol hooks and +# imports must survive constant pointer relocations just as direct calls did. +registration = args.output / 'registration/generated' +registration_main = args.output / 'registration.cpp' +registration_main.write_text(r''' +#include "interior_init.h" +#include +#include +#include +#include + +void interior_RegisterFunctions(rex::runtime::IModuleRegistrar*); +REX_EXTERN(registration_hooked) { ctx.r9.u64 = 0xC0DE; } +REX_EXTERN(__imp__registration_import) { ctx.r8.u64 = 77; } + +struct Recorder : rex::runtime::IModuleRegistrar { + std::vector> calls; + bool SetFunction(uint32_t address, PPCFunc* function) override { + calls.emplace_back(address, function); + return false; // Every later entry must still be visited. + } +}; +int main() { + Recorder recorder; + interior_RegisterFunctions(&recorder); + const std::vector> expected{ + {0x81FFFFF8, __imp__registration_import}, + {0x82000000, sub_82000000}, {0x82000018, sub_82000018}, + {0x82000030, registration_hooked}, + {0x82000040, sub_82000040}, {0x82000048, sub_82000048}, + {0x82000080, xstart}, {0x82000088, sub_82000088} + }; + assert(recorder.calls == expected); // Below-code non-import omitted; equality included. + assert(recorder.calls[1].second != recorder.calls[2].second); + assert(recorder.calls[3].second != __imp__registration_hooked); + alignas(32) uint8_t memory[32]{}; + PPCContext ctx{}; + recorder.calls[0].second(ctx, memory); assert(ctx.r8.u64 == 77); + recorder.calls[3].second(ctx, memory); assert(ctx.r9.u64 == 0xC0DE); + __imp__registration_hooked(ctx, memory); assert(ctx.r9.u64 == 0xC0DE); + ctx = {}; ctx.r1.u64 = 0xFF0; ctx.ctr.u64 = 3; + recorder.calls[2].second(ctx, memory); + assert(ctx.r1.u64 == 0x1000 && ctx.r3.u64 == 3 && ctx.r5.u64 == 3); +} +''') + + +def execute_registration(directory, project, main): + sources = sorted(directory.glob(f'{project}_recomp.*.cpp')) + executable = main.with_suffix('.exe') + command = [args.compiler, '-std=c++23', '-O1', '-UNDEBUG', '-march=x86-64-v2', + '-DSPDLOG_FMT_EXTERNAL', '-I' + str(directory), + '-I' + str(sdk / 'include'), '-I' + str(sdk / 'thirdparty/simde'), + '-I' + str(sdk / 'thirdparty/fmt/include'), + '-I' + str(sdk / 'thirdparty/spdlog/include'), + *map(str, sources), str(directory / f'{project}_init.cpp'), + str(directory / f'{project}_register.cpp'), str(main), '-o', str(executable)] + main.with_suffix('.command.txt').write_text('\n'.join(command) + '\n') + subprocess.run(command, check=True, timeout=45) + subprocess.run([str(executable.resolve())], check=True, timeout=5) + + +execute_registration(registration, 'interior', registration_main) +for project, count, dll in [('empty', 0, False), ('single', 1, False), ('dll', 1, True)]: + small_main = args.output / f'{project}.cpp' + registration_declaration = ('extern "C" void ReXModule_Register(rex::runtime::IModuleRegistrar*);' + if dll else f'void {project}_RegisterFunctions(rex::runtime::IModuleRegistrar*);') + registration_call = 'ReXModule_Register' if dll else f'{project}_RegisterFunctions' + small_main.write_text(f'#include "{project}_init.h"\n' + '#include \n#include \n' + + registration_declaration + r''' +struct Recorder : rex::runtime::IModuleRegistrar { + unsigned calls = 0; + bool SetFunction(uint32_t address, PPCFunc* function) override { + ++calls;assert(address == 0x82000000 && function);return false; + } +}; +''' + f'int main(){{Recorder r;{registration_call}(&r);assert(r.calls=={count});}}\n') + execute_registration(args.output / project / 'generated', project, small_main) +(args.output / 'registration-verification.json').write_text(json.dumps({ + 'passed': True, 'actual_writer_and_registration_sources': True, + 'cases': ['sorted order', 'interior alias execution', 'strong hook relocation', + 'import below code base', 'suppressed non-import below code base', + 'code-base equality', 'false return continuation', 'empty', 'single', 'DLL'], + 'limits': 'Synthetic bytes and mocked registrar; no guest runtime or game execution' +}, indent=2) + '\n') +print('Actual registration tables: order, imports, hooks, aliases, empty/single/DLL passed') diff --git a/tests/unit/codegen/codegen_writer_test.cpp b/tests/unit/codegen/codegen_writer_test.cpp index 9b4b90c..ee1a4bb 100644 --- a/tests/unit/codegen/codegen_writer_test.cpp +++ b/tests/unit/codegen/codegen_writer_test.cpp @@ -252,3 +252,40 @@ TEST_CASE("Every name a recomp file calls is declared in its header", "[codegen_ } } } + +TEST_CASE("Registration is ordered constant data with the existing address filter", "[codegen_writer]") { + WriterFixture fx("registration_filter"); + // Imports below code_base remain callable; a non-import rexcrt below it + // remains declared but has no emitted body or registration. + REQUIRE(fx.ctx->graph.addImportFunction(kBaseAddress - 8, "__imp__test_import")); + REQUIRE(fx.ctx->graph.addFunction(kBaseAddress - 4, 4, FunctionAuthority::CONFIG, + "suppressed_below_code", true)); + fx.ctx->Config().rexcrtFunctions["suppressed_below_code"] = kBaseAddress - 4; + CodegenWriter writer(*fx.ctx); + REQUIRE(writer.write(false)); + const auto registration = ReadAll(fx.outputDir() / "testproj_register.cpp"); + CHECK(registration.find("std::array") != std::string::npos); + CHECK(registration.find("FunctionRegistration{ 0x81FFFFF8, __imp__test_import }") != std::string::npos); + CHECK(registration.find("0x81FFFFFC") == std::string::npos); + // Equality with code_base is included, and sorted imports precede it. + const auto first = registration.find("FunctionRegistration{ 0x82000000, xstart }"); + REQUIRE(first != std::string::npos); + CHECK(first > registration.find("FunctionRegistration{ 0x81FFFFF8")); + CHECK(registration.find("FunctionRegistration{ 0x82000004") > first); + CHECK(registration.find("registrar->SetFunction(entry.guest_address, entry.host_function)") != std::string::npos); +} + +TEST_CASE("Registration handles zero and one entries and DLL exports", "[codegen_writer]") { + WriterFixture fx("registration_small", 1); + for (bool empty : {false, true}) { + if (empty) REQUIRE(fx.ctx->graph.removeFunction(kBaseAddress)); + fx.ctx->setDllModule(empty); + CodegenWriter writer(*fx.ctx); + REQUIRE(writer.write(false)); + const auto registration = ReadAll(fx.outputDir() / "testproj_register.cpp"); + CHECK(registration.find(empty ? "std::array" + : "std::array") != std::string::npos); + CHECK(registration.find(empty ? "void ReXModule_Register(" : "void testproj_RegisterFunctions(") != std::string::npos); + if (empty) CHECK(registration.find("ReXModule_GetImageInfo()") != std::string::npos); + } +} From 061ece0cb34e7e13263e3828402ae5b4fd1e8e20 Mon Sep 17 00:00:00 2001 From: AlenHay <82121826+AlenHay@users.noreply.github.com> Date: Wed, 7 Oct 2026 09:55:14 +0200 Subject: [PATCH 3/3] Allow bounded time for all generated registration execution cases --- tests/CMakeLists.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index aa516c8..0122085 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -29,7 +29,8 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" --compiler ${CMAKE_CXX_COMPILER} --producer $) set_tests_properties(regression_interior_entries PROPERTIES - TIMEOUT 60 LABELS "regression;asset_free") + # Five isolated real-header compilation/link/execution cases. + TIMEOUT 180 LABELS "regression;asset_free") endif() foreach(check IN LISTS REXGLUE_REGRESSION_CHECKS) add_test(NAME regression_${check}