1 #include <stdio.h>
2 #include <windows.h>
3 #include "testwinlib.h"
4 
5 int exceptionCount;
6 int continueCount;
customExceptionHandlder(struct _EXCEPTION_POINTERS * ExceptionInfo)7 LONG WINAPI customExceptionHandlder(struct _EXCEPTION_POINTERS *ExceptionInfo)
8 {
9     if (ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
10     {
11         exceptionCount++;
12         // prepare context to resume execution
13         CONTEXT *c = ExceptionInfo->ContextRecord;
14         c->Rip = *(ULONG_PTR *)c->Rsp;
15         c->Rsp += 8;
16         return EXCEPTION_CONTINUE_EXECUTION;
17     }
18     return EXCEPTION_CONTINUE_SEARCH;
19 }
customContinueHandlder(struct _EXCEPTION_POINTERS * ExceptionInfo)20 LONG WINAPI customContinueHandlder(struct _EXCEPTION_POINTERS *ExceptionInfo)
21 {
22     if (ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
23     {
24         continueCount++;
25         return EXCEPTION_CONTINUE_EXECUTION;
26     }
27     return EXCEPTION_CONTINUE_SEARCH;
28 }
29 
throwFromC()30 void throwFromC()
31 {
32     DebugBreak();
33 }
main()34 int main()
35 {
36     // simulate a "lazily" attached debugger, by calling some go code before attaching the exception/continue handler
37     Dummy();
38     exceptionCount = 0;
39     continueCount = 0;
40     void *exceptionHandlerHandle = AddVectoredExceptionHandler(0, customExceptionHandlder);
41     if (NULL == exceptionHandlerHandle)
42     {
43         printf("cannot add vectored exception handler\n");
44         return 2;
45     }
46     void *continueHandlerHandle = AddVectoredContinueHandler(0, customContinueHandlder);
47     if (NULL == continueHandlerHandle)
48     {
49         printf("cannot add vectored continue handler\n");
50         return 2;
51     }
52     CallMeBack(throwFromC);
53     RemoveVectoredContinueHandler(continueHandlerHandle);
54     RemoveVectoredExceptionHandler(exceptionHandlerHandle);
55     printf("exceptionCount: %d\ncontinueCount: %d\n", exceptionCount, continueCount);
56     return 0;
57 }