Reading and writing with a DLL injection C++

Tom Wright picture Tom Wright · May 9, 2014 · Viewed 8k times · Source

I've run into a bit of a problem and I'm not sure how to do what I am trying to do.

I am using C++ to inject a DLL into an application and I want to alter an address. The problem is that I'm not quite sure how to target it - let me explain...

I know how to use pointers:

int x;
int *myPointer;
myPointer = &x;
*myPointer = 5;
std::cout << x << endl; // 5

And I know that you can point to pointers:

int x;
int *myPointer;
int **myPointer2;
myPointer = &x;
myPointer2 = &myPointer;
**myPointer = 5;
std::cout << x << endl; // 5

I am trying to make a basic game hack by injecting a DLL into a game, and then setting the ammo to a fixed value on a keypress. The injection is working, the keypress is working, but I get a crash whenever I try and access the memory.

I have used Cheat Engine to get the static address for the variable I want to change, along with 3 offsets.

The address info in Cheat Engine looks like this:

Address: 0288A520 = 19
Type: 4 bytes
0   [0288A520 + 0]   -> 0288A520
14  [0288A520 + 14]  -> 0288A520
384 [0288A3D0 + 384] -> 02881A30
ac_client.exe+109B74 -> 0288A3D0

The value 19 is the one I want to modify in my DLL.

If I close the game and re-open it, I get the correct values coming through using these pointers, but now my issue is I'm not sure how to implement this in C++. How do I represent this static address in C++?

My main thread currently looks like this...

DWORD WINAPI Main_Thread(LPVOID lpParam)
{
    while(1)
    {
    if(GetAsyncKeyState(VK_HOME)) {
            // Output value here???
        }
        Sleep(100);
    }
}

Any help is greatly appreciated.

Answer

Tom Wright picture Tom Wright · May 10, 2014

I've got it working. The things I had been trying before were happening because I had an incorrect base address. My solution can be seen below.

Defining addresses

#define BASE_ADDR 0x00400000
#define AMMO_ADDR 0x00109B74
#define AMMO_OFS1 0x00000384
#define AMMO_OFS2 0x00000014

Get address function

DWORD getAddress(DWORD baseAddress, DWORD offsets[], int offsetCount)
{
    DWORD address; // Where the final address will be stored
    address = *(DWORD*)(BASE_ADDR + baseAddress); // Add the base address to the modules base address.

    // Loop through each offset
    for(int i = 0; i < offsetCount; i++) {
        address = *(DWORD*)(address + offsets[i]);
    }

    return address;
}

Changing the value

DWORD ammoOffsets[] = {AMMO_OFS1, AMMO_OFS2};
DWORD ammoAddress = getAddress(AMMO_ADDR, ammoOffsets, 2);      
int* ammoPointer = (int*) ammoAddress;
*ammoPointer = 20;