I am extending the functionality of a Windows component using code injection. I overwrite a method's instructions, calling my own method that does the job of the original one. Let's say we have:
void Target(HDC magic123)
{ ... }
Below are the first few instructions of the method:
push rbx //
push rbp // stores registers to recover later
...
sub rsp, 0x260 // for all 7 pushes
...
mov r12, [rsp+0x28] // stores a pointer to 'magic123'
...
...a lot more instructions
Immediately after mov r12, [rsp+0x28]
, I overwrite the next instructions with:
mov rcx, r12 // 1st parameter to pass to a called function goes in RCX
add rsp, 0x260 // restore the stack
push 0 // create shadow space |EDIT: MISALIGNED STACK. WRONG.
mov rax, &DetouredFunction // function in my injected DLL
call rax // call it with the HDC as parameter
My function in the DLL:
void DetouredFunction(uintptr_t hdcPointer)
{
uintptr_t hdcAddress = *(uintptr_t*)(hdcPointer); // convert pointer to address
HDC hdc = (HDC)hdcAddress; // create a HDC from the address
HBITMAP hBitmapWallpaper = (HBITMAP)LoadImage(NULL, L"C:\\Users\\<user>\\Desktop\\image.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
SelectObject(hdc, hBitmapWallpaper);
}
Everything works until I reach a call to 'LoadImage' in my injected DLL's function. It throws an 'Access Violation Exception (5)' trying to read a non-existing address 0xFFFFFFFFFFFFFFFF.
What is the problem? Please correct any of my comments above if they contain mistakes. Thank you!
My problem was misaligning the stack. It did not have any evident effect until another call to LoadImage was made.