Super bored so I decided to do this, now I'm bored again. >_>
The example below shows how forcing an access violation and setting up an exception handler to catch the exception could be used to hook a function. Yep...
Remember, I'm always looking for criticism to improve my code. |:
Well, enjoy?
Code:#include <windows.h> /* xor eax,eax mov eax,[eax] nop */ BYTE bytes[] = { 0x33,0xC0,0x8B,0x00,0x90 }; //force access violation BYTE origBytes[5]; BYTE *addy; int __stdcall Func(HWND hwnd,LPCTSTR text,LPCTSTR caption,UINT code) { text = "Hooked"; caption = "Hooked"; return MessageBox(hwnd,text,caption,code); } LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS pException) { pException->ContextRecord->Eip = (DWORD)Func; for(int i=0;i<sizeof(bytes)+1;i++) { *(addy+i) = origBytes[i]; } return EXCEPTION_CONTINUE_EXECUTION; } void Main() { while(!GetModuleHandle("user32.dll")) { Sleep(10); } AddVectoredExceptionHandler(1,&ExceptionHandler); addy = (BYTE*)GetProcAddress( LoadLibrary("user32.dll"),"MessageBoxA" ); DWORD old; VirtualProtect(addy,4096,PAGE_EXECUTE_READWRITE,&old); for(int i=0;i<sizeof(bytes)+1;i++) { origBytes[i] = *(addy+i); *(addy+i) = bytes[i]; } } bool __stdcall DllMain(HINSTANCE hInst,DWORD dwReason,void* useless) { if(dwReason == DLL_PROCESS_ATTACH) { CreateThread(0,0,(LPTHREAD_START_ROUTINE)Main,0,0,0); } return true; }
Last edited by master131; 12-06-2012 at 12:43 AM.
This thread was inspired by me.
未来が見えなくて怖いから
未来が見えてしまって悲しいから
目を閉じて優しい思い出に浸ってしまう
momagkromag (08-01-2016)
Uhg, I should have added the exception handler before writing the bytes to cause the exception. |:
kdone.
Heh, neato. Might try this out some time soon =o
Languages: C, C++, x86 ASM, PHP, Lua
Apparently it's also something you do to the dust when you reach 2,000 posts..
If the game has its own exception handler (For a crash log, telling the player something bad happened, etc), would this method not work?
I've not poked exception handlers enough. Is it limited to where the exception happens or something?
Languages: C, C++, x86 ASM, PHP, Lua
Well, the first parameter of AddVectoredExceptionHandler is to tell the exception handler whether its the first handler or the last handler to be called. So assuming this is the last handler created, it should be called first. But Idk too much about it. |:
Edit: Mhm, MSDN: If the FirstHandler parameter is nonzero, the handler is the first handler to be called until a subsequent call to AddVectoredExceptionHandler is used to specify a different handler as the first handler.
I was right.
Last edited by therofl; 10-02-2010 at 08:16 AM.
Still modifying bytes, thus you might as well use a jmp hook ;P
Debug Registers
Ah we-a blaze the fyah, make it bun dem!
therofl (10-02-2010)
only problem is that a page spans across quite an address range, so it would trigger for other functions as well(and you can't return to the same function since it'd break again)
Ah we-a blaze the fyah, make it bun dem!
therofl (10-03-2010)