Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- Generates a handler routine for SetConsoleCtrlHandler, that
- sets hEvent upon invocation without the need for global
- variables (hEvent is attached to the function code).
- Usage:
- PHANDLER_ROUTINE lpfnHandlerRoutine = NULL;
- if(CreateConsoleCtrlEventHandler(hExitEvent, &lpfnHandlerRoutine))
- {
- SetConsoleCtrlHandler(lpfnHandlerRoutine, TRUE);
- // ... code ...
- SetConsoleCtrlHandler(lpfnHandlerRoutine, FALSE);
- VirtualFree(lpfnHandlerRoutine, 0U, MEM_RELEASE);
- }
- */
- BOOL WINAPI CreateConsoleCtrlEventHandler(HANDLE hEvent, PHANDLER_ROUTINE* lppfnHandlerRoutine)
- {
- static const BYTE z_ucThunkTemplate[] =
- {
- 0xC8, 0x00, 0x00, 0x00, // ENTER 0,0
- 0xE8, 0x00, 0x00, 0x00, 0x00, // CALL <+0>
- 0x58, // POP EAX <- EIP
- 0xFF, 0x70, 0x0F, // PUSH [EAX+0Fh] <- hEvent
- 0xFF, 0x50, 0x0B, // CALL [EAX+0Bh] <- SetEvent
- 0xC9, // LEAVE
- 0xC2, 0x04, 0x00, // RETN 4h
- 0x00, 0x00, 0x00, 0x00, // &SetEvent
- 0x00, 0x00, 0x00, 0x00, // hEvent
- };
- BYTE* lpucBuffer = VirtualAlloc(NULL, sizeof(z_ucThunkTemplate), MEM_COMMIT, PAGE_READWRITE);
- if(lpucBuffer)
- {
- void** const lppSetEvent = (void**)&lpucBuffer[sizeof(z_ucThunkTemplate)-sizeof(void*)*2];
- void** const lppEventHan = (void**)&lpucBuffer[sizeof(z_ucThunkTemplate)-sizeof(void*)*1];
- memcpy(lpucBuffer, z_ucThunkTemplate, sizeof(z_ucThunkTemplate));
- lppSetEvent[0] = &SetEvent;
- lppEventHan[0] = hEvent;
- if(VirtualProtect(lpucBuffer, sizeof(z_ucThunkTemplate), PAGE_EXECUTE_READ, NULL))
- {
- lppfnHandlerRoutine[0] = (PHANDLER_ROUTINE)lpucBuffer;
- return TRUE;
- }
- VirtualFree(lpucBuffer, 0U, MEM_RELEASE);
- }
- return FALSE;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement