I'm trying to call a C function using x64 ASM with specific parameters. Calling the function itself works, and the correct arguments are supplied too, but later in the function an access violation will occur, and I'm not sure what causes this. My code looks as follows:
int __stdcall TestFunction(void *arg1, unsigned long arg2, void *arg3)
{
MessageBoxW(NULL, L"Called", L"Test", MB_OK); //Causes access violation: "Access violation reading location 0xFFFFFFFFFFFFFFFF"
return 0;
}
int main()
{
//Shellcode to call the test function
BYTE shellCode[] = "\x48\xB9\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" //mov rcx, ...
"\x48\xC7\xC2\x01\x00\x00\x00" //mov rdx, 1h
"\x49\xC7\xC0\x00\x00\x00\x00" //mov r8, 0
"\x48\xB8\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" //mov rax, ...
"\xFF\xD0"; //call rax
//Allocate executable page(s)
PVOID alloc = VirtualAllocEx(GetCurrentProcess(), NULL, sizeof(shellCode), MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
//Replace dummy addresses with actual addresses in the shellcode
*(PDWORD_PTR)(shellCode + 2) = (DWORD_PTR)GetModuleHandleW(L"kernel32.dll");
*(PDWORD_PTR)(shellCode + 26) = (DWORD_PTR)TestFunction;
//Copy shellcode to allocated memory
memcpy(alloc, shellCode, sizeof(shellCode));
//Create a new thread that will start execution at the start address of the allocated executable memory
CreateThread(NULL, 0, (PTHREAD_START_ROUTINE)alloc, NULL, 0, NULL);
}
I'm rather confident that it is not a problem with the call to MessageBoxW or CreateThread, but that it's a problem with my assembly code. How can I fix this error?