Skip to content

feat(anchors): declarative self-healing anchor registry - #97

Merged
tkhquang merged 2 commits into
mainfrom
feat/self-healing-anchors
Jun 9, 2026
Merged

feat(anchors): declarative self-healing anchor registry#97
tkhquang merged 2 commits into
mainfrom
feat/self-healing-anchors

Conversation

@tkhquang

@tkhquang tkhquang commented Jun 9, 2026

Copy link
Copy Markdown
Owner

Summary

Adds a declarative Anchors registry that resolves a mod's patch-fragile constants from a module range in one pass, reporting a uniform {label, kind, status, value} per entry (the drift report). It unifies DMK's self-healing backends behind one table:

AnchorKind Resolves to
VtableIdentity a class vtable, keyed on its mangled name
RipGlobal an absolute address via a module-scoped AOB/RIP cascade
CodeOperand a live in-code immediate / displacement value
Manual a pinned literal, flagged at-risk
CallArgHome reserved (not yet resolvable)

Supporting work

  • Reverse RTTI resolvers: name -> vtable, with a cached identity handle.
  • Code-constant decode: re-derives a value instead of hard-coding it.
  • Module-scoped cascade resolver split into its own translation unit.

Summary by CodeRabbit

  • New Features

    • Anchor Registry: Declarative system for managing patch-fragile constants with runtime resolution and status reporting.
    • RTTI Reverse Lookup: Resolve vtables by mangled type names with caching support for efficient per-frame identity checks.
    • Code Constant Extraction: Decode immediate and displacement operands directly from machine code at runtime.
    • Drift Telemetry: Enhanced RTTI self-healing with detailed per-landmark offset drift reports.
    • Host Module Convenience APIs: Simplified resolver overloads scoped to the application's main executable.
  • Documentation

    • Comprehensive guides for Anchor Registry, code constant reading, and RTTI reverse lookup functionality.

Resolve every patch-fragile constant a mod depends on from a module range in one declarative pass, unifying the self-healing backends behind a uniform value+status report:

- VtableIdentity: reverse name-to-vtable RTTI resolvers (vtable_for_type, vtables_for_type, TypeIdentity)
- RipGlobal: module-scoped AOB/RIP cascade (resolve_cascade_in_module)
- CodeOperand: Zydis-backed in-code constant decode (read_code_constant)
- Manual: pinned literal, surfaced as at-risk in the report

Split the cascade resolver into scanner_cascade.cpp (shared with the scan engine via scanner_internal.hpp). Add test suites for each surface and document the registry.
@tkhquang tkhquang self-assigned this Jun 9, 2026
@coderabbitai

coderabbitai Bot commented Jun 9, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@tkhquang, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 21 minutes and 36 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1ff1dcb9-9d6f-41bd-af39-80d4af0453ab

📥 Commits

Reviewing files that changed from the base of the PR and between 8517237 and 87d7f94.

📒 Files selected for processing (2)
  • docs/misc/aob-signatures.md
  • src/scanner_cascade.cpp
📝 Walkthrough

Walkthrough

This PR introduces a declarative anchor registry system that consolidates patch-fragile constants into a single table-driven resolver, backed by four independent resolution backends: code-constant operand extraction (Zydis decoding), RTTI reverse vtable lookup by mangled type name, RIP/global cascade scanning, and manual literal pinning. Supporting infrastructure includes RTTI healing telemetry reporting, scanner cascade refactoring, and comprehensive test coverage.

Changes

Code-constant operand extraction and anchor consolidation

Layer / File(s) Summary
Code-constant operand extraction
include/DetourModKit/scanner.hpp, src/code_constant.cpp, tests/test_code_constant.cpp, docs/misc/aob-signatures.md
Adds Scanner::OperandKind, CodeConstant descriptor, and read_code_constant() to decode immediate/displacement operands from runtime machine code via Zydis, with RIP-relative address resolution and sign-extension handling; extends ResolveError with DecodeFailed, UnexpectedShape, OperandOutOfRange variants.
Scanner cascade refactoring and host-module APIs
src/scanner_cascade.cpp, src/scanner_internal.hpp, src/scanner.cpp, include/DetourModKit/scanner.hpp, tests/test_scanner.cpp
Extracts cascade resolution logic into dedicated scanner_cascade.cpp with separate implementations for whole-process, module-scoped, and prologue-fallback variants; adds host-module convenience overloads (resolve_cascade_in_host_module*); refactors scanner.cpp to use internal Scanner::detail::scan_module_executable/readable() functions.
RTTI reverse lookup by mangled type name
include/DetourModKit/rtti.hpp, src/rtti.cpp, tests/test_rtti_reverse.cpp, docs/misc/rtti-walker.md
Implements vtable_for_type(), vtables_for_type(), and TypeIdentity cached resolver class to find vtables by MSVC mangled name via module section scanning, PE header parsing, COL validation, and SEH-guarded name matching; includes atomic-based caching for repeated identity checks with fast-path matches() calls.
RTTI healing telemetry reporting
include/DetourModKit/rtti_dissect.hpp, src/rtti_dissect.cpp, tests/test_rtti_dissect.cpp, docs/misc/rtti-self-heal.md
Adds heal_report() function and DriftEntry struct to perform bulk landmark healing in a single pass and write per-landmark drift records including healed offset, delta, success status, and typed error information.
Declarative anchor registry system
include/DetourModKit/anchors.hpp, src/anchors.cpp, include/DetourModKit.hpp, tests/test_anchors.cpp, docs/misc/anchors.md, README.md
Introduces Anchors::resolve() dispatcher that routes resolution by AnchorKind to code-constant, RTTI, scanner, or manual backends; resolve_all() for batch resolution into output spans; uniform AnchorStatus mapping across all kinds; includes new DMKAnchors namespace alias and comprehensive registry documentation.
Documentation and project guidance
AGENTS.md, README.md, docs/misc/anchors.md
Updates project documentation with new module descriptions, test suite listings, code-style guidance (descriptive variable names), performance-critical-path notes (TypeIdentity::matches fast path), and guide entries for anchor registry, code-constant decoding, and reverse RTTI lookup.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • tkhquang/DetourModKit#69: Scanner prologue-fallback and cascade hardening (bounded hit counting, ambiguous-match rejection) directly affects the main PR's cascade resolver implementation.
  • tkhquang/DetourModKit#95: Introduces RTTI dissection self-healing foundation that the main PR extends with heal_report telemetry reporting.
  • tkhquang/DetourModKit#89: Extends AOB scanner to support readable/data region scanning (ScannerKind, scan_readable_regions) that aligns with the main PR's readable-module cascade paths.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat(anchors): declarative self-healing anchor registry' accurately describes the main change: a new declarative anchor registry system for resolving patch-fragile constants.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (2)
tests/test_code_constant.cpp (1)

35-41: ⚡ Quick win

Mark CodeRegion destructor as noexcept.

Please make the destructor signature explicit (~CodeRegion() noexcept) to match the project’s exception contract for teardown paths.

Suggested patch
-        ~CodeRegion()
+        ~CodeRegion() noexcept
         {
             if (m_base)
             {
                 VirtualFree(m_base, 0, MEM_RELEASE);
             }
         }

As per coding guidelines: "Do not omit noexcept on destructors, shutdown methods, and const accessors."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_code_constant.cpp` around lines 35 - 41, The destructor for
CodeRegion is missing noexcept; update its signature from ~CodeRegion() to
~CodeRegion() noexcept in the CodeRegion class/implementation so teardown cannot
throw (adjust both declaration and definition if they are separate), ensuring
the destructor matches the project's exception contract and coding guidelines.

Source: Coding guidelines

src/scanner_cascade.cpp (1)

66-77: ⚡ Quick win

Use the repo's constant naming here.

These new TU-scope constants introduce kCamelCase, but the project guideline for C++ constants is UPPER_SNAKE_CASE. Renaming them now avoids spreading a second style through the new scanner cascade code.

As per coding guidelines, "Use UPPER_SNAKE_CASE for constants and macros."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/scanner_cascade.cpp` around lines 66 - 77, Rename the TU-scope constants
to the repo's UPPER_SNAKE_CASE style and update all references: change
kPrologueFallbackMinTailLiterals to PROLOGUE_FALLBACK_MIN_TAIL_LITERALS and
kPrologueFallbackMaxHits to PROLOGUE_FALLBACK_MAX_HITS in
src/scanner_cascade.cpp (and any other translation units that reference them),
and ensure builds/tests still pass after updating usages in functions/methods
that rely on these constants (e.g., any logic that checks the minimum tail
literals or the fallback max hits).

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/misc/aob-signatures.md`:
- Around line 478-489: The Contents/TOC at the top of the document was not
updated after adding sections 6.6 ("Host-module convenience overloads") and 6.7
("Reading a code constant (read_code_constant)"); update the contents list to
add entries for these two headings (with matching anchor texts/section numbers),
and verify the anchor links match the exact heading text so navigation works
correctly.
- Around line 493-495: The example AOB in k_stride_site contains an invalid
token "..." which parse_aob will reject; update the entry in k_stride_site to
replace "..." with explicit byte tokens or wildcards (e.g., full hex byte pairs
or "??" for unknown bytes) so the pattern string conforms to parse_aob's allowed
tokens; locate the static constexpr sc::AddrCandidate k_stride_site[] definition
and fix the pattern for "equip-stride" to use concrete bytes/wildcards only (no
ellipses), ensuring the resulting pattern parses correctly by parse_aob.

In `@src/rtti.cpp`:
- Around line 495-497: The fixed-size buffer in scan_vtables_for_name is too
small: change ScanRange ranges[32] to accommodate the full capacity expected by
collect_rtti_scan_ranges (up to 96) — e.g., replace the 32 with 96 or allocate
dynamically based on the max accepted by collect_rtti_scan_ranges — so that
range_count = collect_rtti_scan_ranges(mod, ranges, 96) cannot overflow/clip
sections and miss RTTI; update any accompanying size constant/argument usages to
keep both the buffer and the call-site limit consistent (symbols: ScanRange
ranges, scan_vtables_for_name, collect_rtti_scan_ranges, range_count).

In `@src/scanner_cascade.cpp`:
- Around line 36-56: resolve_candidate_match currently returns 0 on an
unreadable displacement which scan_candidates still treats as a valid hit,
letting invalid matches produce a ResolveHit at address 0; change
resolve_candidate_match to return an optional (e.g.
std::optional<std::uintptr_t>) instead of raw uintptr_t and return std::nullopt
on failure (when DetourModKit::Memory::seh_read fails), then update
scan_candidates to check the optional before constructing a ResolveHit
(skip/continue when nullopt) so non-Direct AddrCandidate failures do not produce
a false hit; update all call sites (including the other occurrence referenced at
lines 273-286) to handle the optional result.
- Around line 238-247: The lambda scan_for currently always calls
Scanner::detail::scan_module_readable when range is set, which breaks
resolve_cascade_in_module's intent to keep module-scoped cascades
executable-only; change scan_for to respect the scanner kind: if range is set
and kind == DetourModKit::Scanner::ScannerKind::Readable call
Scanner::detail::scan_module_readable(*compiled, *range, occurrence), otherwise
call the module-executable counterpart (e.g.,
Scanner::detail::scan_module_executable or the appropriate detail function that
scans executable pages) so executable cascades remain limited to .text; make the
same conditional fix at the other occurrence noted (lines ~487-490).

In `@tests/test_anchors.cpp`:
- Around line 34-40: The Region class destructor is missing a noexcept
specification; update the destructor signature for ~Region() to be noexcept to
comply with the project's rule for destructors and RAII cleanup, keeping the
body that checks m_base and calls VirtualFree(m_base, 0, MEM_RELEASE) unchanged
so the cleanup behavior is preserved.

---

Nitpick comments:
In `@src/scanner_cascade.cpp`:
- Around line 66-77: Rename the TU-scope constants to the repo's
UPPER_SNAKE_CASE style and update all references: change
kPrologueFallbackMinTailLiterals to PROLOGUE_FALLBACK_MIN_TAIL_LITERALS and
kPrologueFallbackMaxHits to PROLOGUE_FALLBACK_MAX_HITS in
src/scanner_cascade.cpp (and any other translation units that reference them),
and ensure builds/tests still pass after updating usages in functions/methods
that rely on these constants (e.g., any logic that checks the minimum tail
literals or the fallback max hits).

In `@tests/test_code_constant.cpp`:
- Around line 35-41: The destructor for CodeRegion is missing noexcept; update
its signature from ~CodeRegion() to ~CodeRegion() noexcept in the CodeRegion
class/implementation so teardown cannot throw (adjust both declaration and
definition if they are separate), ensuring the destructor matches the project's
exception contract and coding guidelines.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 376d94ba-76a6-44b6-a2c8-9edd4307ad93

📥 Commits

Reviewing files that changed from the base of the PR and between 84ec4b8 and 8517237.

📒 Files selected for processing (23)
  • AGENTS.md
  • README.md
  • docs/misc/anchors.md
  • docs/misc/aob-signatures.md
  • docs/misc/rtti-self-heal.md
  • docs/misc/rtti-walker.md
  • include/DetourModKit.hpp
  • include/DetourModKit/anchors.hpp
  • include/DetourModKit/rtti.hpp
  • include/DetourModKit/rtti_dissect.hpp
  • include/DetourModKit/scanner.hpp
  • src/anchors.cpp
  • src/code_constant.cpp
  • src/rtti.cpp
  • src/rtti_dissect.cpp
  • src/scanner.cpp
  • src/scanner_cascade.cpp
  • src/scanner_internal.hpp
  • tests/test_anchors.cpp
  • tests/test_code_constant.cpp
  • tests/test_rtti_dissect.cpp
  • tests/test_rtti_reverse.cpp
  • tests/test_scanner.cpp

Comment thread docs/misc/aob-signatures.md
Comment thread docs/misc/aob-signatures.md
Comment thread src/rtti.cpp
Comment thread src/scanner_cascade.cpp Outdated
Comment thread src/scanner_cascade.cpp
Comment thread tests/test_anchors.cpp
resolve_candidate_match now returns std::optional; a faulted displacement read is a miss (nullopt) instead of address 0, which the whole-process cascade path would otherwise accept as a ResolveHit (the module-scoped path was already guarded by Memory::contains).

Also: rename the prologue-fallback constants to UPPER_SNAKE_CASE per AGENTS.md; add TOC entries for sections 6.6/6.7 and replace the invalid "..." token in the read_code_constant example with a wildcard in aob-signatures.md.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant