Reputation: 35
I would like to know how to handle exceptions in C, specifically EXCEPTION_GUARD_PAGE
exceptions.
I will try explaining the situation more briefly:
I would like to mark a section/pages section as PAGE_GUARD
, and whenever the program hits them I would like to perform a few tasks, I tried causing the exception with a classical VirtualAlloc -> Write -> Exception
hit but I do know to catch the exception in C
I'd appreciate the help. Thanks in advance.
Upvotes: 2
Views: 2261
Reputation:
MSDN has everything you need:
In this particular case you want something in this vein:
__try
{
/* Code that may cause exceptions... */
}
__except(GetExceptionCode() == EXCEPTION_GUARD_PAGE
? EXCEPTION_EXECUTE_HANDLER
: EXCEPTION_CONTINUE_SEARCH)
{
/* Exception handling code... */
}
EDIT (in response to OP's comment):
The above code would do (MSDN is helpful again), but in this case there's more portable (no dependency on MSVC's extensions) and arguably less ugly solution: register a top-level exception filter using SetUnhandledExceptionFilter and let it handle the situation:
/* Our top-level exception filter. */
LONG WINAPI MyUnhandledExceptionFilter(EXCEPTION_POINTERS* exceptionInfo)
{
DWORD exceptionCode = exceptionInfo->ExceptionRecord->ExceptionCode;
if(exceptionCode == EXCEPTION_GUARD_PAGE)
{
/* Handle the situation somehow... */
/* ...and resume the exception from the place the exception was thrown. */
return EXCEPTION_CONTINUE_EXECUTION;
}
else
{
/* Unknown exception, let another exception filter worry about it. */
return EXCEPTION_CONTINUE_SEARCH;
}
}
/* Somewhere else in the code: */
SetUnhandledExceptionFilter(&MyUnhandledExceptionFilter);
Upvotes: 4