Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 84 additions & 29 deletions AOB.cpp
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@

#include "framework.h"
#include <psapi.h>
#include <vector>
#include <regex>
#include <string>
#include <iostream>
#include <algorithm>

#include "AOB.h"

Expand All @@ -19,7 +21,9 @@ namespace AOB {
}
DWORD FindPattern(DWORD dwAddress, DWORD dwLen, BYTE* bMask, char* szMask)
{
for (DWORD i = 0; i < (dwLen - strlen((char*)szMask)); i++)
const size_t length = strlen(szMask);
if (length == 0 || length > dwLen) return 0;
for (DWORD i = 0; i <= dwLen - length; i++)
{
if (bCompare((BYTE*)(dwAddress + i), bMask, szMask))
{
Expand All @@ -42,38 +46,30 @@ namespace AOB {
return bytes;
}

static bool Readable(const MEMORY_BASIC_INFORMATION& mbi)
{
return mbi.State == MEM_COMMIT && mbi.Type == MEM_IMAGE && (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) == 0;
}

// Searches [min, max], both inclusive. Adjacent readable regions are searched as one range.
DWORD Scan(char* content, char* mask, DWORD min, DWORD max)
{
SYSTEM_INFO si;
GetSystemInfo(&si);
_MEMORY_BASIC_INFORMATION32 mbi;
DWORD address = min;
int remainder = 0;

while (VirtualQuery((LPCVOID) address, ((MEMORY_BASIC_INFORMATION*)&mbi), sizeof(MEMORY_BASIC_INFORMATION)) != 0) {
if (mbi.State == MEM_COMMIT) {
if ((mbi.Type != MEM_MAPPED) && (mbi.Type != MEM_PRIVATE)) {
if ((mbi.Protect & PAGE_NOACCESS) == 0) {
// address = 0x401002
// mbi.BaseAddress = 0x401000
DWORD needle = FindPattern(address, mbi.RegionSize, (BYTE*)content, mask);
if (needle == 0) {
// address = 0x401000
address = mbi.BaseAddress;
}
else {
return needle;
}
}
const unsigned long long end = (unsigned long long) max + 1;
unsigned long long address = min, runStart = min;
MEMORY_BASIC_INFORMATION mbi;
while (address < end) {
const bool queried = VirtualQuery((LPCVOID) (DWORD) address, &mbi, sizeof(mbi)) != 0;
const unsigned long long next = queried ? (std::min)((unsigned long long) (DWORD) mbi.BaseAddress + mbi.RegionSize, end) : end;
if (!queried || !Readable(mbi)) {
if (address > runStart) {
DWORD needle = FindPattern((DWORD) runStart, (DWORD) (address - runStart), (BYTE*) content, mask);
if (needle != 0) return needle;
}
runStart = next;
}

// address = 0x59E000
address += mbi.RegionSize;
if (address > max) {
return 0;
}
address = next;
}
if (address > runStart) return FindPattern((DWORD) runStart, (DWORD) (address - runStart), (BYTE*) content, mask);
return 0;
}

Expand All @@ -100,7 +96,66 @@ namespace AOB {
haystack = sm.suffix();
}

return Scan((char*)(&AOB::HexToBytes(content)[0]), (char*)mask.c_str(), min, max);
std::vector<char> bytes = HexToBytes(content);
if (bytes.empty()) return 0;
return Scan(bytes.data(), (char*)mask.c_str(), min, max);
}

// Whether [offset, offset + size) lies inside an image of imageSize bytes.
static bool InImage(DWORD offset, DWORD size, DWORD imageSize)
{
return offset <= imageSize && size <= imageSize - offset;
}

// Whether every byte of [address, address + size) is readable image memory.
static bool AllReadable(DWORD address, DWORD size)
{
const unsigned long long end = (unsigned long long) address + size;
MEMORY_BASIC_INFORMATION mbi;
for (unsigned long long a = address; a < end; a = (unsigned long long) (DWORD) mbi.BaseAddress + mbi.RegionSize) {
if (VirtualQuery((LPCVOID) (DWORD) a, &mbi, sizeof(mbi)) == 0 || !Readable(mbi)) return false;
}
return true;
}

bool FindInMainModule(std::string ucp_aob_spec, DWORD& first, DWORD& second)
{
first = 0;
second = 0;
MODULEINFO info;
if (!GetModuleInformation(GetCurrentProcess(), GetModuleHandleW(NULL), &info, sizeof(info))) return false;
const DWORD base = (DWORD) info.lpBaseOfDll;
const DWORD size = info.SizeOfImage;

if (!InImage(0, sizeof(IMAGE_DOS_HEADER), size) || !AllReadable(base, sizeof(IMAGE_DOS_HEADER))) return false;
const IMAGE_DOS_HEADER* dos = (const IMAGE_DOS_HEADER*) base;
const DWORD ntOffset = (DWORD) dos->e_lfanew;
if (dos->e_magic != IMAGE_DOS_SIGNATURE || !InImage(ntOffset, sizeof(IMAGE_NT_HEADERS), size) || !AllReadable(base + ntOffset, sizeof(IMAGE_NT_HEADERS))) return false;
const IMAGE_NT_HEADERS* nt = (const IMAGE_NT_HEADERS*) (base + ntOffset);
const DWORD tableOffset = ntOffset + FIELD_OFFSET(IMAGE_NT_HEADERS, OptionalHeader) + nt->FileHeader.SizeOfOptionalHeader;
const DWORD tableSize = nt->FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER);
if (nt->Signature != IMAGE_NT_SIGNATURE || !InImage(tableOffset, tableSize, size) || !AllReadable(base + tableOffset, tableSize)) return false;

const IMAGE_SECTION_HEADER* section = (const IMAGE_SECTION_HEADER*) (base + tableOffset);
for (WORD i = 0; i < nt->FileHeader.NumberOfSections; i++, section++) {
const DWORD offset = section->VirtualAddress;
const DWORD length = section->Misc.VirtualSize;
if ((section->Characteristics & IMAGE_SCN_MEM_EXECUTE) == 0) continue;
if (length == 0 || !InImage(offset, length, size) || !AllReadable(base + offset, length)) return false;
const DWORD last = base + offset + length - 1;
for (DWORD start = base + offset; start <= last;) {
const DWORD found = FindInRange(ucp_aob_spec, start, last);
if (found == 0) break;
if (first != 0) {
second = found;
return true;
}
first = found;
if (found == last) break;
start = found + 1;
}
}
return true;
}

// TODO: find all?
Expand Down
3 changes: 3 additions & 0 deletions AOB.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,8 @@ namespace AOB {
//Consider: https://github.com/CvX/hadesmem
DWORD FindPattern(DWORD dwAddress, DWORD dwLen, BYTE* bMask, char* szMask);
DWORD Find(std::string ucp_aob);
// The first two matches in the executable sections of the main module (0 if none).
// Returns false when the headers or an executable section of the main module cannot be read.
bool FindInMainModule(std::string ucp_aob_spec, DWORD& first, DWORD& second);
DWORD FindInRange(std::string ucp_aob_spec, DWORD min, DWORD max);
}
27 changes: 27 additions & 0 deletions CodeFunctions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1115,3 +1115,30 @@ int luaScanForAOB(lua_State* L) {

return 1;
}

int luaScanForAOBsInMainModule(lua_State* L) {
const char* query = luaL_checkstring(L, 1);

if (strlen(query) < 2) {
return luaL_error(L, "first argument is too short, minimum length is 2");
}

if (!validateAOBQuery(query)) {
return luaL_error(L, "Invalid format, only spaces, 0-9, A-F, and ? are allowed");
}

DWORD first = 0;
DWORD second = 0;

if (!AOB::FindInMainModule(query, first, second)) {
lua_pushnil(L);
lua_pushnil(L);
lua_pushstring(L, "incomplete");
return 3;
}

if (first == 0) lua_pushnil(L); else lua_pushinteger(L, first);
if (second == 0) lua_pushnil(L); else lua_pushinteger(L, second);

return 2;
}
1 change: 1 addition & 0 deletions CodeFunctions.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ int luaAllocateRWE(lua_State* L);
int luaDeallocateRWE(lua_State* L);

int luaScanForAOB(lua_State* L);
int luaScanForAOBsInMainModule(lua_State* L);

int luaDetourCode(lua_State* L);

Expand Down
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project>
<PropertyGroup>
<PackageId>RPS</PackageId>
<Version>1.5.1</Version>
<Version>1.6.0</Version>
<Authors>gynt</Authors>
<Company>gynt</Company>
<Copyright>2023</Copyright>
Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,12 @@ detourCode(onDetour, 0xABCDEF, 7)
scanForAOB(searchPattern[, min, max])
searchPattern scans the memory for this pattern
min address to start searching
max address to stop searching
max last address of the search, a match has to end at or before it

scanForAOBsInMainModule(searchPattern)
returns the first and the second match in the executable sections of the main module, nil for each one not found.
returns nil, nil, "incomplete" when the headers or an executable section of the main module cannot be read.

searchPattern: hexadecimal array with question marks for wildcards.
example: "FF A1 E? B? ?? 00"
```
Expand Down
1 change: 1 addition & 0 deletions RuntimePatchingSystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ const struct luaL_Reg RPS_LIB[] = {
{"registerString", registerString},

{"scanForAOB", luaScanForAOB},
{"scanForAOBsInMainModule", luaScanForAOBsInMainModule},
{NULL, NULL} /* end of array */
};

Expand Down
2 changes: 1 addition & 1 deletion RuntimePatchingSystem.nuspec
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
<metadata>
<id>RPS</id>
<version>1.5.2</version>
<version>1.6.0</version>
<title>Runtime Patching System</title>
<authors>gynt</authors>
<readme>build\README.md</readme>
Expand Down
23 changes: 23 additions & 0 deletions tests/test-aob.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
local lunatest = require("tests.lunatest.lunatest")
local rps = require("RPS")

local test_aob = {}

function test_aob.test_scanForAOB_inclusive_max()
local first = rps.scanForAOBsInMainModule("? ? ?")
lunatest.assert_equal(first, rps.scanForAOB("? ? ?", first, first + 2))
lunatest.assert_nil(rps.scanForAOB("? ? ?", first, first + 1))
end

function test_aob.test_scanForAOBsInMainModule_second_match()
local first, second = rps.scanForAOBsInMainModule("? ? ?")
lunatest.assert_equal(first + 1, second)
end

function test_aob.test_scanForAOBsInMainModule_not_found()
local first, second = rps.scanForAOBsInMainModule(string.rep("37 9B E1 46 02 AF DC 85 ", 32))
lunatest.assert_nil(first)
lunatest.assert_nil(second)
end

return test_aob