### Find Process and Window IDs (C++) Source: https://context7.com/gamehackingbook/gamehackingcode/llms.txt Utilities for identifying target processes by window handle or executable name using Windows Toolhelp32 snapshot APIs. Essential for obtaining a handle to the target process before performing memory operations. Includes functions to get the process ID and base address. ```cpp #include #include // Get process ID from a window handle DWORD getPIDFromWindow(HWND window) { DWORD PID; GetWindowThreadProcessId(window, &PID); return PID; } // Get process ID by executable name DWORD getPIDByName(std::wstring name) { DWORD PID = -1; PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (Process32First(snapshot, &entry) == TRUE) { while (Process32Next(snapshot, &entry) == TRUE) { std::wstring binaryPath = entry.szExeFile; if (binaryPath.find(name) != std::wstring::npos) { PID = entry.th32ProcessID; break; } } } CloseHandle(snapshot); return PID; } // Get base address using multiple methods DWORD getMyBaseAddressGMH() { return (DWORD)GetModuleHandle(NULL); } DWORD getRemoteBaseAddress(HANDLE process) { DWORD newBase; HMODULE k32 = GetModuleHandleA("kernel32.dll"); LPVOID funcAdr = GetProcAddress(k32, "GetModuleHandleA"); HANDLE thread = CreateRemoteThread(process, NULL, NULL, (LPTHREAD_START_ROUTINE)funcAdr, NULL, NULL, NULL); WaitForSingleObject(thread, INFINITE); GetExitCodeThread(thread, &newBase); CloseHandle(thread); return newBase; } // Usage int main() { // Find explorer.exe process ID auto explorerPID = getPIDByName(L"explorer.exe"); printf("Explorer PID is %d\n", explorerPID); // Get PID from console window wchar_t myTitle[1024]; GetConsoleTitle(&myTitle[0], 1024); HWND myWindow = FindWindow(NULL, myTitle); auto myPID = getPIDFromWindow(myWindow); printf("My PID is %d\n", myPID); } ``` -------------------------------- ### C++ State Machine for Bot Automation Source: https://context7.com/gamehackingbook/gamehackingcode/llms.txt Implements a feedback-loop state machine in C++ for autonomous bot behavior. It utilizes lambda functions for defining conditions and actions, with adaptive thresholds that adjust based on gameplay feedback. This example includes simulated game sensors and actuators. ```cpp #include #include #include // For std::min #include // For Sleep // Simulated game state int32_t currentHealth = 10; int32_t maximumHealth = 10; class GameSensors { public: float getHealthPercent() { return ((float)currentHealth / maximumHealth) * 100.0f; } bool detectedStrongHeal() { /* check if heal occurred */ return false; } float getStrongHealIncrease() { /* return heal amount as % */ return 0; } bool getStrongHealMaxed() { /* was health maxed? */ return false; } void clearStrongHealInfo() { /* reset flags */ } }; class GameActuators { public: void strongHeal() { currentHealth = std::min(currentHealth + 4, maximumHealth); } void weakHeal() { currentHealth = std::min(currentHealth + 2, maximumHealth); } }; class StateDefinition { public: std::function condition; std::function reach; }; std::vector buildMachine() { std::vector stateMachine(2); auto curDef = stateMachine.begin(); // Adaptive strong heal - learns optimal threshold curDef->condition = [](GameSensors* sensors) -> bool { static float healAt = 50; if (sensors->detectedStrongHeal()) { if (sensors->getStrongHealMaxed()) healAt -= 1; // Lower threshold if over-healing else healAt = (healAt + (100 - sensors->getStrongHealIncrease())) / 2.0f; sensors->clearStrongHealInfo(); } return sensors->getHealthPercent() > healAt; }; curDef->reach = [](GameSensors* sensors, GameActuators* actuators) { actuators->strongHeal(); }; curDef++; // Weak heal state curDef->condition = [](GameSensors* sensors) -> bool { return sensors->getHealthPercent() > 70; }; curDef->reach = [](GameSensors* sensors, GameActuators* actuators) { actuators->weakHeal(); }; return stateMachine; } void doFeedbackLoop(std::vector stateMachine) { GameSensors sensors; GameActuators actuators; while (true) { for (auto& state : stateMachine) { if (!state.condition(&sensors)) { state.reach(&sensors, &actuators); break; } } Sleep(1000); } } // Usage int main() { doFeedbackLoop(buildMachine()); return 0; } ``` -------------------------------- ### IAT Hooking: Redirect Imported DLL Functions in C++ Source: https://context7.com/gamehackingbook/gamehackingcode/llms.txt This snippet demonstrates how to hook imported DLL functions by modifying the Import Address Table (IAT). It includes functions to scan the IAT, replace function addresses, and provides an example of hooking the `Sleep` function. Dependencies include the Windows API. It takes a function name and a new function address as input and returns the original function address. ```cpp #include template T* pointMemory(DWORD address) { return ((T*)address); } template DWORD protectMemory(DWORD address, DWORD prot) { DWORD oldProt; VirtualProtect((LPVOID)address, sizeof(T), prot, &oldProt); return oldProt; } // Scan IAT and replace function address DWORD hookIAT(const char* functionName, DWORD newFunctionAddress) { DWORD baseAddress = (DWORD)GetModuleHandle(NULL); auto dosHeader = pointMemory(baseAddress); if (dosHeader->e_magic != 0x5A4D) return 0; auto optHeader = pointMemory(baseAddress + dosHeader->e_lfanew + 24); if (optHeader->Magic != 0x10B) return 0; IMAGE_IMPORT_DESCRIPTOR* importDescriptor = pointMemory( baseAddress + optHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress); while (importDescriptor->FirstThunk) { int n = 0; IMAGE_THUNK_DATA* thunkData = pointMemory( baseAddress + importDescriptor->OriginalFirstThunk); while (thunkData->u1.Function) { char* importFunctionName = pointMemory( baseAddress + (DWORD)thunkData->u1.AddressOfData + 2); if (strcmp(importFunctionName, functionName) == 0) { auto vfTable = pointMemory(baseAddress + importDescriptor->FirstThunk); DWORD original = vfTable[n]; auto oldProtection = protectMemory((DWORD)&vfTable[n], PAGE_READWRITE); vfTable[n] = newFunctionAddress; protectMemory((DWORD)&vfTable[n], oldProtection); return original; } n++; thunkData++; } importDescriptor++; } return 0; } // Hook callback type and implementation typedef VOID (WINAPI _origSleep)(DWORD ms); _origSleep* originalSleep; VOID WINAPI newSleepFunction(DWORD ms) { if (ms > 100) printf("Sleep hook worked! Denied sleep for %d milliseconds.\n", ms); else originalSleep(ms); } // Usage int main() { originalSleep = (_origSleep*)hookIAT("Sleep", (DWORD)&newSleepFunction); Sleep(1234); // Output: Sleep hook worked! Denied sleep for 1234 milliseconds. Sleep(50); // Actually sleeps for 50ms } ``` -------------------------------- ### VFT Hooking: Intercept C++ Virtual Method Calls in C++ Source: https://context7.com/gamehackingbook/gamehackingcode/llms.txt This snippet illustrates Virtual Function Table (VFT) hooking, a technique used to intercept calls to virtual methods of C++ objects. It modifies the vtable pointer to redirect calls to a custom implementation. The code includes helper functions for memory access and protection, a sample class with a virtual function, and the hook installation logic. It requires a class instance, the function index within the vtable, and the new function address. ```cpp #include template T readMemory(DWORD address) { return *((T*)address); } template void writeMemory(DWORD address, T value) { *((T*)address) = value; } template DWORD protectMemory(DWORD address, DWORD prot) { DWORD oldProt; VirtualProtect((LPVOID)address, sizeof(T), prot, &oldProt); return oldProt; } // Target class with virtual function class someClass { public: virtual DWORD someFunction(DWORD arg1) { if (arg1 == 1) printf("VF Table hook worked! Parameters intercepted and changed!\n"); else printf("VF Table hook failed!\n"); return 0; } }; // Hook function DWORD originalVFFunction; DWORD __stdcall someNewVFFunction(DWORD arg1) { static DWORD _this, _ret; __asm MOV _this, ECX // Save 'this' pointer printf("VFHook pre\n"); __asm { PUSH 1 // Change argument from 0 to 1 MOV ECX, _this CALL [originalVFFunction] MOV _ret, EAX } printf("VFHook post\n"); __asm MOV ECX, _this return _ret; } // Install vtable hook DWORD hookVF(DWORD classInst, DWORD funcIndex, DWORD newFunc) { DWORD VFTable = readMemory(classInst); DWORD hookAddress = VFTable + funcIndex * sizeof(DWORD); auto oldProtection = protectMemory(hookAddress, PAGE_READWRITE); DWORD originalFunc = readMemory(hookAddress); writeMemory(hookAddress, newFunc); protectMemory(hookAddress, oldProtection); return originalFunc; } // Usage int main() { someClass* inst = new someClass(); originalVFFunction = hookVF((DWORD)inst, 0, (DWORD)&someNewVFFunction); inst->someFunction(0); // Argument changed from 0 to 1 by hook // Output: VFHook pre // VF Table hook worked! Parameters intercepted and changed! // VFHook post delete inst; } ``` -------------------------------- ### DLL Injection via CreateRemoteThread and LoadLibraryW (C++) Source: https://context7.com/gamehackingbook/gamehackingcode/llms.txt Demonstrates injecting a DLL into a target process by leveraging `CreateRemoteThread` to call the `LoadLibraryW` function. This is a common method for loading arbitrary code into a running process. Requires Windows API access and a target DLL. ```cpp #include void LoadDll(HANDLE process, const wchar_t* dllPath) { // Write the DLL path to target process memory int namelen = wcslen(dllPath) + 1; LPVOID remoteString = VirtualAllocEx(process, NULL, namelen * 2, MEM_COMMIT, PAGE_EXECUTE); WriteProcessMemory(process, remoteString, dllPath, namelen * 2, NULL); // Get LoadLibraryW address (same in all processes due to ASLR) HMODULE k32 = GetModuleHandleA("kernel32.dll"); LPVOID funcAdr = GetProcAddress(k32, "LoadLibraryW"); // Create thread to call LoadLibraryW with DLL path HANDLE thread = CreateRemoteThread(process, NULL, NULL, (LPTHREAD_START_ROUTINE)funcAdr, remoteString, NULL, NULL); WaitForSingleObject(thread, INFINITE); CloseHandle(thread); } // Usage int main() { HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId()); LoadDll(proc, L"MyHook.dll"); return 0; } ``` -------------------------------- ### Read/Write Process Memory (C++) Source: https://context7.com/gamehackingbook/gamehackingcode/llms.txt Template functions for reading and writing process memory using Windows API functions like ReadProcessMemory and WriteProcessMemory. Supports both external and internal memory manipulation. Includes functions for changing memory protection. ```cpp #include #include // Read memory from another process using Windows API template T readMemoryAPI(HANDLE process, LPVOID address) { T value; ReadProcessMemory(process, address, &value, sizeof(T), NULL); return value; } // Write memory to another process using Windows API template void writeMemoryAPI(HANDLE process, LPVOID address, T value) { WriteProcessMemory(process, address, &value, sizeof(T), NULL); } // Change memory protection flags template DWORD protectMemory(HANDLE process, LPVOID address, DWORD prot) { DWORD oldProt; VirtualProtectEx(process, address, sizeof(T), prot, &oldProt); return oldProt; } // Example usage: read, modify, and write back a value void readAndWriteMemoryAPI(HANDLE process, LPVOID address) { DWORD value = readMemoryAPI(process, address); printf("Current mem value is %d\n", value); value++; DWORD oldProt = protectMemory(process, address, PAGE_READWRITE); writeMemoryAPI(process, address, value); protectMemory(process, address, oldProt); value = readMemoryAPI(process, address); printf("New mem value is %d\n", value); } // Direct pointer-based memory access (for internal/injected code) template T readMemoryPointer(LPVOID address) { return *((T*)address); } template void writeMemoryPointer(LPVOID address, T value) { *((T*)address) = value; } // Usage int main() { HANDLE proc = OpenProcess( PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, GetCurrentProcessId()); DWORD someValue = 1234; readAndWriteMemoryAPI(proc, &someValue); // Output: Current mem value is 1234 // New mem value is 1235 } ``` -------------------------------- ### A* Pathfinding Algorithm in C++ Source: https://context7.com/gamehackingbook/gamehackingcode/llms.txt Implements the A* search algorithm for pathfinding on a grid. It uses a priority queue for managing nodes to explore and the Manhattan distance heuristic to estimate the cost to the goal. The function returns true if a path is found, and populates the 'path' array, otherwise returns false. ```cpp #include #include #include #define TILE_COST 1 class AStarNode; typedef std::shared_ptr AStarNodePtr; class AStarNode { public: int x, y; int g, score; // g = cost from start, score = g + heuristic AStarNodePtr parent; AStarNode(int x, int y, int cost, AStarNodePtr p, int score = 0) : x(x), y(y), g(cost), score(score), parent(p) {} static AStarNodePtr makePtr(int x, int y, int cost, AStarNodePtr p, int score = 0) { return AStarNodePtr(new AStarNode(x, y, cost, p, score)); } // Manhattan distance heuristic int heuristic(int destx, int desty) const { return abs(destx - x) + abs(desty - y); } void updateScore(int endx, int endy) { score = g + heuristic(endx, endy) * TILE_COST; } std::vector getChildren(int width, int height) { std::vector ret; auto copy = AStarNode::makePtr(x, y, g, parent, score); if (x > 0) ret.push_back(AStarNode::makePtr(x - 1, y, g + TILE_COST, copy)); if (y > 0) ret.push_back(AStarNode::makePtr(x, y - 1, g + TILE_COST, copy)); if (x < width - 1) ret.push_back(AStarNode::makePtr(x + 1, y, g + TILE_COST, copy)); if (y < height - 1) ret.push_back(AStarNode::makePtr(x, y + 1, g + TILE_COST, copy)); return ret; } }; bool operator<(const AStarNodePtr &a, const AStarNodePtr &b) { return a->score > b->score; } template bool doAStarSearch(int map[WIDTH][HEIGHT], int startx, int starty, int endx, int endy, int path[WIDTH][HEIGHT]) { std::priority_queue frontier; std::vector allNodes; auto node = AStarNode::makePtr(startx, starty, 0, nullptr); node->updateScore(endx, endy); allNodes.push_back(node); while (true) { if (node->x == endx && node->y == endy) { // Trace path back while (node.get() != nullptr) { path[node->x][node->y] = 1; node = node->parent; } return true; } auto children = node->getChildren(WIDTH, HEIGHT); for (auto& c : children) { if (map[c->x][c->y] == BLOCKING) continue; c->updateScore(endx, endy); frontier.push(c); allNodes.push_back(c); } if (frontier.empty()) return false; node = frontier.top(); frontier.pop(); } } // Usage: searchFunction = doAStarSearch<32, 24, 1>; ``` -------------------------------- ### Code Injection via Remote Thread using CreateRemoteThread (C++) Source: https://context7.com/gamehackingbook/gamehackingcode/llms.txt Demonstrates injecting and executing shellcode in a target process using the `CreateRemoteThread` function. It allocates memory, writes shellcode and parameters, and then launches the shellcode as a new thread. Requires Windows API access. ```cpp #include #include #include DWORD printStringManyTimes(int times, const char* string) { for (int i = 0; i < times; i++) printf(string); return 0; } void injectCodeUsingThreadInjection(HANDLE process, LPVOID func, int times, const char* string) { // Shellcode that pushes parameters and calls a function BYTE codeCave[20] = { 0xFF, 0x74, 0x24, 0x04, // PUSH DWORD PTR[ESP+0x4] 0x68, 0x00, 0x00, 0x00, 0x00, // PUSH times 0xB8, 0x00, 0x00, 0x00, 0x00, // MOV EAX, func 0xFF, 0xD0, // CALL EAX 0x83, 0xC4, 0x08, // ADD ESP, 0x08 0xC3 // RETN }; // Patch values into shellcode memcpy(&codeCave[5], ×, 4); memcpy(&codeCave[10], &func, 4); // Allocate memory for string + code int stringlen = strlen(string) + 1; int fulllen = stringlen + sizeof(codeCave); LPVOID remoteString = VirtualAllocEx(process, NULL, fulllen, MEM_COMMIT, PAGE_EXECUTE); LPVOID remoteCave = (LPVOID)((DWORD)remoteString + stringlen); // Write string and code WriteProcessMemory(process, remoteString, string, stringlen, NULL); WriteProcessMemory(process, remoteCave, codeCave, sizeof(codeCave), NULL); // Execute via remote thread HANDLE thread = CreateRemoteThread(process, NULL, NULL, (LPTHREAD_START_ROUTINE)remoteCave, remoteString, NULL, NULL); WaitForSingleObject(thread, INFINITE); CloseHandle(thread); } // Usage int main() { HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId()); injectCodeUsingThreadInjection(proc, &printStringManyTimes, 2, "injected\n"); // Output: injected // injected return 0; } ``` -------------------------------- ### Analyze C++ Vector Memory Layout Source: https://context7.com/gamehackingbook/gamehackingcode/llms.txt Reads and interprets the memory layout of an STL vector. It calculates the element count and capacity by examining the internal pointers (begin, end, tail). This is useful for understanding dynamic array structures in memory. ```cpp #include #include #include void readVector(DWORD vectorAddress) { struct _vector { DWORD* begin; DWORD* end; DWORD* tail; }; _vector* vec = (_vector*)vectorAddress; DWORD count = ((DWORD)vec->end - (DWORD)vec->begin) / sizeof(DWORD); DWORD capacity = ((DWORD)vec->tail - (DWORD)vec->begin) / sizeof(DWORD); printf("Vector has %d items and %d capacity\n", count, capacity); for (int i = 0; i < count; i++) printf("\tValue at %d is %d\n", i, vec->begin[i]); } // Usage int main() { std::vector vectorData; vectorData.reserve(20); vectorData.push_back(12345); vectorData.push_back(54321); readVector((DWORD)&vectorData); // Output: Vector has 2 items and 20 capacity // Value at 0 is 12345 // Value at 1 is 54321 return 0; } ``` -------------------------------- ### Analyze C++ List Memory Structure Source: https://context7.com/gamehackingbook/gamehackingcode/llms.txt Traverses and analyzes the memory structure of an STL list. It demonstrates forward and reverse iteration through the doubly-linked list nodes by accessing the 'next' and 'prev' pointers. This helps in understanding linked list implementations in memory. ```cpp #include #include #include void readList(DWORD listAddress) { struct listItem { listItem* next; listItem* prev; DWORD value; }; struct _list { listItem* root; DWORD size; }; _list* list = (_list*)listAddress; printf("List has %d items\n", list->size); // Forward iteration for (listItem* it = list->root->next; it != list->root; it = it->next) printf("\tForward value is %d\n", it->value); // Reverse iteration for (listItem* it = list->root->prev; it != list->root; it = it->prev) printf("\tReverse value is %d\n", it->value); } // Usage int main() { std::list listData; listData.push_back(123); listData.push_back(321); listData.push_back(121); readList((DWORD)&listData); // Output: List has 3 items // Forward value is 123 // Forward value is 321 // Forward value is 121 // Reverse value is 121 // Reverse value is 321 // Reverse value is 123 return 0; } ``` -------------------------------- ### Lua Scripts for Memory Analysis with Cheat Engine Source: https://context7.com/gamehackingbook/gamehackingcode/llms.txt Provides Lua helper functions for Cheat Engine to verify data structure integrity in memory. These scripts are designed to identify if a given memory address belongs to a circular linked list or a red-black tree (map) structure by analyzing memory patterns. ```lua -- Count nodes in a circular linked list function countLinkedListNodes(nodeAddress) local counter = 0 local next = readInteger(nodeAddress) while (next ~= nodeAddress) do counter = counter + 1 next = readInteger(next) end return counter end -- Verify if address is part of a linked list node function _verifyLinkedList(address) local nextItem = readInteger(address) or 0 local previousItem = readInteger(address + 4) or 0 local nextItemBack = readInteger(nextItem + 4) local previousItemForward = readInteger(previousItem) return (address == nextItemBack and address == previousItemForward) end function isValueInLinkedList(valueAddress) for address = valueAddress - 8, valueAddress - 48, -4 do if (_verifyLinkedList(address)) then return address end end return 0 end -- Verify if address is part of a map (red-black tree) node function _verifyMap(address) local parentItem = readInteger(address + 4) or 0 local parentLeftItem = readInteger(parentItem + 0) or 0 local parentRightItem = readInteger(parentItem + 8) or 0 local validParent = parentLeftItem == address or parentRightItem == address if (not validParent) then return false end -- Traverse up to root local tries = 0 local lastChecked = parentItem local parentsParent = readInteger(parentItem + 4) or 0 while (readInteger(parentsParent + 4) ~= lastChecked and tries < 200) do tries = tries + 1 lastChecked = parentsParent parentsParent = readInteger(parentsParent + 4) or 0 end return readInteger(parentsParent + 4) == lastChecked end -- Usage in Cheat Engine -- local node = isValueInLinkedList(addressOfSomeValue) -- if (node > 0) then -- print(string.format("Value in LL, node at 0x%x", node)) -- end ``` -------------------------------- ### Analyze C++ Map Memory Structure (Red-Black Tree) Source: https://context7.com/gamehackingbook/gamehackingcode/llms.txt Traverses and searches STL map structures, which are internally implemented as red-black trees. It requires recursive traversal to iterate through nodes and find specific keys. This code helps in understanding tree-based map implementations in memory. ```cpp #include #include #include typedef int keyInt; typedef int valInt; struct mapItem { mapItem* left; mapItem* parent; mapItem* right; keyInt key; valInt value; }; struct _map { DWORD irrelevant; mapItem* rootNode; int size; }; // Recursive search in binary tree mapItem* findItem(keyInt key, mapItem* node, mapItem* root) { if (node != root) { if (key == node->key) return node; else if (key < node->key) return findItem(key, node->left, root); else return findItem(key, node->right, root); } return root; } mapItem* searchMap(keyInt key, _map* map) { mapItem* ret = findItem(key, map->rootNode->parent, map->rootNode); if (ret == map->rootNode) return NULL; return ret; } // In-order traversal void iterateMap(mapItem* node, mapItem* root) { if (node == root) return; iterateMap(node->left, root); printf("\tKey %d has value 0x%04x\n", node->key, node->value); iterateMap(node->right, root); } void readMap(DWORD mapAddress) { _map* map = (_map*)mapAddress; printf("Nodes in map: %d\n", map->size); iterateMap(map->rootNode->parent, map->rootNode); } // Usage int main() { std::map mapData; mapData.insert(std::pair(1, 0x100)); mapData.insert(std::pair(2, 0x200)); mapData.insert(std::pair(5, 0x500)); readMap((DWORD)&mapData); // Output: Nodes in map: 3 // Key 1 has value 0x0100 // Key 2 has value 0x0200 // Key 5 has value 0x0500 printf("Search for key 2: 0x%04x\n", searchMap(2, (_map*)&mapData)->value); // Output: Search for key 2: 0x0200 return 0; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.