Crash a thread in a Win32 application

231 views Asked by At

I have an application which implements crash handling and reporting using Google Crashpad and Sentry.

The application implements a watchdog which checks for freezes on critical threads, and aborts the application if it detects such a case.

However, when the "crash" gets reported to Sentry, the thread that "crashed" is, of course, the watchdog thread and not the actual thread which was frozen.

I need to trigger the frozen thread to abort to enable Sentry to correctly group related freezes together for analysis.

On POSIX systems, I can do this trivially:

pthread_kill(_threadHandle, SIGABRT);

On Windows, however, there doesn't seem to be an equivalent.

TerminateThread cleanly kills the thread without triggering an abort, which is not suitable.

I believe that what I want to do is accomplishable with SuspendThread, GetThreadContext and ResumeThread, but how do I do this without significantly corrupting the call stack (which needs to be intact for diagnosis)?

1

There are 1 answers

0
Axalo On BEST ANSWER

You can set the trap flag to cause an EXCEPTION_SINGLE_STEP.

CONTEXT context = { 0 };
context.ContextFlags = CONTEXT_ALL;

if (SuspendThread(hThread) == (DWORD)-1)
    handleError();

if (!GetThreadContext(hThread, &context))
    handleError();

context.EFlags |= 0x100; // set trap flag

if (!SetThreadContext(hThread, &context))
    handleError();

if (ResumeThread(hThread) == (DWORD)-1)
    handleError();