#pragma once #include #include #include #include namespace sigscan { struct pattern { std::vector bytes; std::vector mask; // true = this byte must match }; // IDA-style: "48 8B ?? ?? 89 5C" inline bool parse(const char* ida, pattern& out) { out.bytes.clear(); out.mask.clear(); for (const char* p = ida; *p;) { if (*p == ' ') { ++p; continue; } if (*p == '?') { out.bytes.push_back(0); out.mask.push_back(false); ++p; if (*p == '?') ++p; } else { if (!p[1]) return false; const char buf[3] = { p[0], p[1], 0 }; char* end = nullptr; const unsigned long v = strtoul(buf, &end, 16); if (end != buf + 2) return false; out.bytes.push_back((uint8_t)v); out.mask.push_back(true); p += 2; } } return !out.bytes.empty(); } inline uint8_t* scan_range(uint8_t* begin, uint8_t* end, const pattern& pat) { const size_t n = pat.bytes.size(); if ((size_t)(end - begin) < n) return nullptr; uint8_t* last = end - n; for (uint8_t* p = begin; p <= last; ++p) { size_t i = 0; while (i < n && (!pat.mask[i] || p[i] == pat.bytes[i])) ++i; if (i == n) return p; } return nullptr; } inline size_t count_matches( uint8_t* begin, uint8_t* end, const pattern& pat) { size_t count = 0; const size_t n = pat.bytes.size(); if (n == 0 || end < begin || static_cast(end - begin) < n) return 0; for (uint8_t* p = begin; p <= end - n; ++p) { size_t i = 0; while (i < n && (!pat.mask[i] || p[i] == pat.bytes[i])) ++i; if (i == n) ++count; } return count; } // searches the executable sections of the game's main module inline uint8_t* find(const char* ida_pattern) { pattern pat; if (!parse(ida_pattern, pat)) return nullptr; auto* base = (uint8_t*)GetModuleHandleW(nullptr); auto* dos = (IMAGE_DOS_HEADER*)base; auto* nt = (IMAGE_NT_HEADERS*)(base + dos->e_lfanew); const IMAGE_SECTION_HEADER* sec = IMAGE_FIRST_SECTION(nt); for (WORD i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { if (!(sec->Characteristics & IMAGE_SCN_MEM_EXECUTE)) continue; uint8_t* start = base + sec->VirtualAddress; uint8_t* end = start + sec->Misc.VirtualSize; for (uint8_t* p = start; p < end;) { // walk readable regions only MEMORY_BASIC_INFORMATION mbi; if (!VirtualQuery(p, &mbi, sizeof(mbi))) break; uint8_t* region_end = (uint8_t*)mbi.BaseAddress + mbi.RegionSize; if (region_end > end) region_end = end; const bool readable = mbi.State == MEM_COMMIT && !(mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)); if (readable) { if (uint8_t* hit = scan_range(p, region_end, pat)) return hit; } p = region_end; } } return nullptr; } // for patterns that land on a RIP-relative instruction (e.g. a call or lea): // rel_offset = byte offset of the 4-byte displacement, instr_len = length of the instruction inline uint8_t* resolve_rip(uint8_t* instr, int rel_offset, int instr_len) { const int32_t rel = *(int32_t*)(instr + rel_offset); return instr + instr_len + rel; } } // namespace sigscan