While digging in my old code repositories I stumbled upon a memory pattern search algorithm I once used in a cheat I made. Maybe i’ts useful for someone at some time. It may be used like this:

1
2
3
4
constexpr unsigned char patD3Device[] = { 0xA1, '?', '?', '?', '?', 0x50, 0x8B, 0x08, 0xFF, 0x51, 0x0C };

// search for the patD3Device ('?' characters are non static values) from memory address 0x400000 to 0x408192
auto patternAddress = SearchPattern(patD3Device, sizeof(patD3Device), 0x400000, 0x8192);
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/// <summary>
/// Search a memory pattern. Placeholder is the '?' char.
/// </summary>
/// <param name="pattern">Pattern to search as char array</param>
/// <param name="patternSize">Size of the pattern array</param>
/// <param name="memory">Start of the search area</param>
/// <param name="memorySize">Size of the search are</param>
/// <returns>Address if found, 0 if not</returns>
__forceinline intptr_t SearchPattern(const unsigned char* pattern, const size_t patternSize, const void* memory, const size_t memorySize) noexcept
{
    size_t patternPosition = 0;
    intptr_t possibleAddress = 0;
    const auto c = reinterpret_cast<const unsigned char*>(memory);

    for (size_t i = 0; i < memorySize; ++i)
    {
        if (c[i] == pattern[patternPosition] || pattern[patternPosition] == '?')
        {
            if (patternPosition == 0)
            {
                possibleAddress = i;
            }
            else if (patternPosition == patternSize - 1)
            {
                return reinterpret_cast<intptr_t>(memory) + possibleAddress;
            }

            ++patternPosition;
        }
        else
        {
            if (patternPosition > 0)
            {
                i = possibleAddress;
            }

            patternPosition = 0;
        }
    }

    return 0;
}