Ai4rei

When you need SetConsoleCtrlHandler without globals...

Jul 23rd, 2017
557
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.     Generates a handler routine for SetConsoleCtrlHandler, that
  3.     sets hEvent upon invocation without the need for global
  4.     variables (hEvent is attached to the function code).
  5.  
  6.     Usage:
  7.  
  8.     PHANDLER_ROUTINE lpfnHandlerRoutine = NULL;
  9.  
  10.     if(CreateConsoleCtrlEventHandler(hExitEvent, &lpfnHandlerRoutine))
  11.     {
  12.         SetConsoleCtrlHandler(lpfnHandlerRoutine, TRUE);
  13.  
  14.         // ... code ...
  15.  
  16.         SetConsoleCtrlHandler(lpfnHandlerRoutine, FALSE);
  17.         VirtualFree(lpfnHandlerRoutine, 0U, MEM_RELEASE);
  18.     }
  19. */
  20. BOOL WINAPI CreateConsoleCtrlEventHandler(HANDLE hEvent, PHANDLER_ROUTINE* lppfnHandlerRoutine)
  21. {
  22.     static const BYTE z_ucThunkTemplate[] =
  23.     {
  24.         0xC8, 0x00, 0x00, 0x00,         // ENTER    0,0
  25.         0xE8, 0x00, 0x00, 0x00, 0x00,   // CALL     <+0>
  26.         0x58,                           // POP      EAX <- EIP
  27.         0xFF, 0x70, 0x0F,               // PUSH     [EAX+0Fh] <- hEvent
  28.         0xFF, 0x50, 0x0B,               // CALL     [EAX+0Bh] <- SetEvent
  29.         0xC9,                           // LEAVE
  30.         0xC2, 0x04, 0x00,               // RETN     4h
  31.         0x00, 0x00, 0x00, 0x00,         // &SetEvent
  32.         0x00, 0x00, 0x00, 0x00,         // hEvent
  33.     };
  34.     BYTE* lpucBuffer = VirtualAlloc(NULL, sizeof(z_ucThunkTemplate), MEM_COMMIT, PAGE_READWRITE);
  35.  
  36.     if(lpucBuffer)
  37.     {
  38.         void** const lppSetEvent = (void**)&lpucBuffer[sizeof(z_ucThunkTemplate)-sizeof(void*)*2];
  39.         void** const lppEventHan = (void**)&lpucBuffer[sizeof(z_ucThunkTemplate)-sizeof(void*)*1];
  40.  
  41.         memcpy(lpucBuffer, z_ucThunkTemplate, sizeof(z_ucThunkTemplate));
  42.         lppSetEvent[0] = &SetEvent;
  43.         lppEventHan[0] = hEvent;
  44.  
  45.         if(VirtualProtect(lpucBuffer, sizeof(z_ucThunkTemplate), PAGE_EXECUTE_READ, NULL))
  46.         {
  47.             lppfnHandlerRoutine[0] = (PHANDLER_ROUTINE)lpucBuffer;
  48.  
  49.             return TRUE;
  50.         }
  51.  
  52.         VirtualFree(lpucBuffer, 0U, MEM_RELEASE);
  53.     }
  54.  
  55.     return FALSE;
  56. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×