Search code examples
c++cexceptionseh

Imitation of hardware exceptions


Can anyone tell me a code for next function, which raises EXCEPTION_FLT_STACK_CHECK or EXCEPTION_BREAKPOINT, for I could catch them in main func:

int _tmain(int argc, _TCHAR* argv[])
{
    __try 
    { 
        FaultingStack(); // What I need to write in this function???
    } 
    __except(GetExceptionCode() == EXCEPTION_FLT_STACK_CHECK ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
    { 
        return FALSE;
    }
    return TRUE;

    return 0;
}

Do not suggest RaiseException func, I need an example of fault code, not software raised exception

UPD: I need one more code snippet for next exception EXCEPTION_INT_OVERFLOW


Solution

  • Breakpoint exception is raised easily. You can use one of the following (which is all the same):

    DebugBreak(); // API function
    __debugbreak(); // MSVC intrinsic
    __asm int 3; // Actual instruction
    

    Now, EXCEPTION_FLT_STACK_CHECK is related to the invalid floating-point register stack state.

    First one should enable FP exceptions related to the FP stack:

    #include <float.h>
    _clearfp();
    _controlfp(_controlfp(0, 0) & ~(EM_INVALID), MCW_EM);
    

    Next, make FP stack overflow/underflow:

    for (float f; ; )
        __asm fstp f;