src/internal/scan_pages.hpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | #ifndef DETOURMODKIT_INTERNAL_SCAN_PAGES_HPP | ||
| 2 | #define DETOURMODKIT_INTERNAL_SCAN_PAGES_HPP | ||
| 3 | |||
| 4 | /** | ||
| 5 | * @file internal/scan_pages.hpp | ||
| 6 | * @brief Page-gated scan primitives: the VirtualQuery page walk, the TOCTOU-guarded region reads, the committed-window | ||
| 7 | * collector, and the executable-page predicates. | ||
| 8 | * @details Never installed. Wraps the raw scan_engine matcher in the OS page map so a scan over arbitrary process or | ||
| 9 | * module memory reads only committed pages of the requested protection class instead of faulting the host. | ||
| 10 | * The Windows page-protection masks stay private to scan_pages.cpp; callers select a class through the Pages | ||
| 11 | * mapping or the named module/process scans. | ||
| 12 | */ | ||
| 13 | |||
| 14 | #include "internal/memory_guarded.hpp" | ||
| 15 | #include "internal/scan_engine.hpp" | ||
| 16 | #include "internal/scan_exclusions.hpp" | ||
| 17 | |||
| 18 | #include "DetourModKit/region.hpp" | ||
| 19 | #include "DetourModKit/scan.hpp" | ||
| 20 | |||
| 21 | #include <array> | ||
| 22 | #include <cstddef> | ||
| 23 | #include <cstdint> | ||
| 24 | #include <span> | ||
| 25 | #include <vector> | ||
| 26 | |||
| 27 | namespace DetourModKit | ||
| 28 | { | ||
| 29 | namespace detail | ||
| 30 | { | ||
| 31 | /** | ||
| 32 | * @struct ScanQuery | ||
| 33 | * @brief What one page-gated sweep is asked to find and what it must not match. | ||
| 34 | * @details @ref count_beyond is what makes a uniqueness verdict sound: the sweep keeps traversing past the Nth | ||
| 35 | * match to look for an (N+1)th within the SAME pass, so the two counts come from one view of memory. | ||
| 36 | * Running two independent scans instead lets a concurrent write between them produce a count pair that | ||
| 37 | * never existed. | ||
| 38 | */ | ||
| 39 | struct ScanQuery | ||
| 40 | { | ||
| 41 | /// Which occurrence to report (1-based). Zero yields an empty result. | ||
| 42 | std::size_t occurrence = 1; | ||
| 43 | /// Keep counting one occurrence past @ref occurrence so the caller can tell unique from ambiguous. | ||
| 44 | bool count_beyond = false; | ||
| 45 | /// Spans a match may not intersect (query-owned storage); null excludes nothing. | ||
| 46 | const ScanExclusions *exclusions = nullptr; | ||
| 47 | /** | ||
| 48 | * @brief Capture the reported match's literal bytes into @ref MatchResult::evidence. | ||
| 49 | * @details Off by default, and deliberately not a free extra: the captured span is a verbatim copy of the | ||
| 50 | * needle-shaped bytes just matched, so it is itself matchable. A sweep whose window can reach the | ||
| 51 | * copy would count it as a further occurrence, which is why the live tally buffer joins the | ||
| 52 | * engine's exclusion floor while this is set. The window is the caller's resolve scope, not | ||
| 53 | * necessarily a module image, so the floor is what makes the guarantee rather than the scope; the | ||
| 54 | * stack residue an earlier by-value capture leaves behind stays outside it, exactly as | ||
| 55 | * @ref ScanExclusions cannot enumerate a caller's abandoned copies either. | ||
| 56 | */ | ||
| 57 | bool capture_evidence = false; | ||
| 58 | // Length of the instruction at the offset-applied match point to snapshot; zero captures none. | ||
| 59 | std::uint8_t instruction_snapshot_length = 0; | ||
| 60 | }; | ||
| 61 | |||
| 62 | /** | ||
| 63 | * @struct InstructionSnapshot | ||
| 64 | * @brief Private value copy of one matched x86-64 instruction, captured inside the guarded sweep. | ||
| 65 | */ | ||
| 66 | struct InstructionSnapshot | ||
| 67 | { | ||
| 68 | std::array<std::byte, scan::MAX_X86_INSTRUCTION_LENGTH> bytes{}; | ||
| 69 | std::uint8_t length = 0; | ||
| 70 | |||
| 71 | 333 | [[nodiscard]] constexpr std::span<const std::byte> span() const noexcept | |
| 72 | { | ||
| 73 | 333 | return std::span<const std::byte>{bytes.data(), length}; | |
| 74 | } | ||
| 75 | }; | ||
| 76 | |||
| 77 | /** | ||
| 78 | * @struct MatchResult | ||
| 79 | * @brief A page-gated scan result: the requested match, how many occurrences the pass counted, and why the | ||
| 80 | * count may be a lower bound. | ||
| 81 | * @details @ref count is capped at `occurrence + count_beyond`, so it distinguishes zero, exactly the requested | ||
| 82 | * occurrence, and at-least-one-more without traversing the whole scope after the answer is known. | ||
| 83 | * @ref incomplete (a region faulted under the TOCTOU guard and was skipped) and @ref budget_exhausted | ||
| 84 | * (a bounded-jump matcher spent its backtracking budget) are reported separately because they are | ||
| 85 | * different caller problems: one is a concurrent unmap, the other an over-broad pattern. | ||
| 86 | */ | ||
| 87 | struct MatchResult | ||
| 88 | { | ||
| 89 | /// The Nth match with pattern.offset applied, or nullptr when fewer than N occurrences were counted. | ||
| 90 | const std::byte *match = nullptr; | ||
| 91 | /// The Nth match's physical span before pattern.offset is applied; an address value, never dereferenced. | ||
| 92 | Region physical_span{}; | ||
| 93 | /** | ||
| 94 | * @brief The literal bytes of the Nth match's span, taken while the region was still guarded-readable. | ||
| 95 | * @details A value, not a view: the live match pointer is only valid inside the fault guard, so the caller | ||
| 96 | * cannot re-read the span after this returns. | ||
| 97 | */ | ||
| 98 | scan::WinningEvidence evidence{}; | ||
| 99 | /// Instruction bytes at @ref match, with the evidence-covered prefix copied from that same value. | ||
| 100 | InstructionSnapshot instruction{}; | ||
| 101 | /// Occurrences counted, capped by the query. | ||
| 102 | std::size_t count = 0; | ||
| 103 | /// A faulted region was skipped, so unscanned bytes may hide further matches. | ||
| 104 | bool incomplete = false; | ||
| 105 | /// Bounded-jump backtracking was truncated, so unvisited start positions may hide further matches. | ||
| 106 | bool budget_exhausted = false; | ||
| 107 | |||
| 108 | /// True when @ref count is only a lower bound, for either reason, so a uniqueness verdict must fail closed. | ||
| 109 |
4/4✓ Branch 2 → 3 taken 735 times.
✓ Branch 2 → 4 taken 371 times.
✓ Branch 3 → 4 taken 1 time.
✓ Branch 3 → 5 taken 734 times.
|
1106 | [[nodiscard]] constexpr bool truncated() const noexcept { return incomplete || budget_exhausted; } |
| 110 | }; | ||
| 111 | |||
| 112 | /// Module-scoped sweep over the image's execute-readable pages, so a match can only land on code. | ||
| 113 | [[nodiscard]] MatchResult | ||
| 114 | scan_module_executable(const EnginePattern &pattern, ModuleSpan range, const ScanQuery &query) noexcept; | ||
| 115 | |||
| 116 | /// Module-scoped sweep over every readable page, so one pass covers code and .rdata / .data candidates. | ||
| 117 | [[nodiscard]] MatchResult | ||
| 118 | scan_module_readable(const EnginePattern &pattern, ModuleSpan range, const ScanQuery &query) noexcept; | ||
| 119 | |||
| 120 | /** | ||
| 121 | * @brief Whole-process sweep over committed execute-readable pages. | ||
| 122 | * @details A pattern straddling two adjacent accepted regions is found via a max_match_length() - 1 carry. | ||
| 123 | */ | ||
| 124 | [[nodiscard]] MatchResult | ||
| 125 | scan_executable_regions(const EnginePattern &pattern, const ScanQuery &query) noexcept; | ||
| 126 | |||
| 127 | /// Whole-process sweep over committed readable pages; a strict superset of @ref scan_executable_regions. | ||
| 128 | [[nodiscard]] MatchResult scan_readable_regions(const EnginePattern &pattern, const ScanQuery &query) noexcept; | ||
| 129 | |||
| 130 | /// Maps a public scan::Pages class to the matching module-scoped sweep. | ||
| 131 | [[nodiscard]] MatchResult scan_module_pages( | ||
| 132 | const EnginePattern &pattern, | ||
| 133 | ModuleSpan range, | ||
| 134 | scan::Pages pages, | ||
| 135 | const ScanQuery &query | ||
| 136 | ) noexcept; | ||
| 137 | |||
| 138 | /** | ||
| 139 | * @brief True when a readable-page sweep of @p range can produce an authoritative result. | ||
| 140 | * @param range The scope the sweep will read. | ||
| 141 | * @param pages The page class the sweep accepts. | ||
| 142 | * @param exclusions Caller-declared copies of the query material; a non-empty span asserts completeness. | ||
| 143 | * @details A readable sweep reads every committed page of its scope, so a scope that spans arbitrary process | ||
| 144 | * memory also covers the allocator pages the caller's own copies of the query bytes live on. DMK | ||
| 145 | * excludes every query representation it owns, but it cannot discover a caller-retained copy, so such | ||
| 146 | * a scope can only report that the query found itself. A scope confined to one mapped image or to one | ||
| 147 | * memory allocation is fine: the caller named exactly what it wanted searched. An executable-page | ||
| 148 | * sweep is always authoritative, because no query representation is placed on an execute-readable | ||
| 149 | * page. | ||
| 150 | */ | ||
| 151 | [[nodiscard]] bool readable_scan_is_authoritative( | ||
| 152 | ModuleSpan range, | ||
| 153 | scan::Pages pages, | ||
| 154 | std::span<const Region> exclusions | ||
| 155 | ) noexcept; | ||
| 156 | |||
| 157 | /** | ||
| 158 | * @struct ExecutableWindow | ||
| 159 | * @brief One committed, execute-readable slice of a module image. | ||
| 160 | * @details The gate proves readability only at gate time, so a caller reading [base, base + span) should still | ||
| 161 | * wrap the read in a fault guard against a concurrent decommit / reprotect. | ||
| 162 | */ | ||
| 163 | struct ExecutableWindow | ||
| 164 | { | ||
| 165 | /// Absolute address of the first readable byte. | ||
| 166 | std::uintptr_t base = 0; | ||
| 167 | /// Window length in bytes. | ||
| 168 | std::size_t span = 0; | ||
| 169 | }; | ||
| 170 | |||
| 171 | /** | ||
| 172 | * @brief Collects the execute-readable windows of a module image in ascending address order. | ||
| 173 | * @return The windows; empty when @p range is invalid or exposes no readable code pages. | ||
| 174 | * @details Centralizes the executable-page gate so an out-of-TU caller (the string-xref backend) scans the | ||
| 175 | * image's code without re-deriving the Windows page masks. | ||
| 176 | */ | ||
| 177 | [[nodiscard]] std::vector<ExecutableWindow> collect_executable_windows(ModuleSpan range); | ||
| 178 | |||
| 179 | /** | ||
| 180 | * @brief True when @p address lies on a committed, execute-readable page. | ||
| 181 | * @details The destination is intentionally NOT module-constrained (a sibling mod's trampoline is allocated | ||
| 182 | * outside every loaded module), while this still rejects a jump into unmapped or data-only memory. | ||
| 183 | */ | ||
| 184 | [[nodiscard]] bool is_executable_address(std::uintptr_t address) noexcept; | ||
| 185 | |||
| 186 | /** | ||
| 187 | * @brief True when every byte in [@p address, @p address + @p size) is committed and execute-readable. | ||
| 188 | * @details Stricter than testing the first byte: a decoded x86 instruction can straddle a protection boundary, | ||
| 189 | * and a code-only decoder must not consume a readable data-page tail as instruction bytes. | ||
| 190 | */ | ||
| 191 | [[nodiscard]] bool is_executable_range(std::uintptr_t address, std::size_t size) noexcept; | ||
| 192 | } // namespace detail | ||
| 193 | } // namespace DetourModKit | ||
| 194 | |||
| 195 | #endif // DETOURMODKIT_INTERNAL_SCAN_PAGES_HPP | ||
| 196 |