I was trying to perform exception handling manually (through a call to language specific handler function) inside a VEH. This is the code:
DWORD64 imagebase;
LONG handler(EXCEPTION_POINTERS* ex) {
if (ex->ExceptionRecord->ExceptionCode == 0xE06D7363) {
const int maxFrames = 62;
void* frames[maxFrames];
USHORT framesCaptured = RtlCaptureStackBackTrace(0, maxFrames, frames, nullptr);
void* handler_data = NULL;
uint64_t establisher_frame = NULL;
for (USHORT i = 0; i < framesCaptured; ++i)
{
auto lookup = RtlLookupFunctionEntry((DWORD64)frames[i],&imagebase,NULL);
UNWIND_INFO* ui = (UNWIND_INFO*)(imagebase + lookup->UnwindInfoAddress);
if (ui->Flags == UNW_FLAG_EHANDLER) {
auto language_handler = RtlVirtualUnwind(UNW_FLAG_EHANDLER, imagebase, (DWORD64)frames[i], lookup, ex->ContextRecord, &handler_data, &establisher_frame, NULL);
DISPATCHER_CONTEXT new_dc = {};
new_dc.ControlPc = (DWORD64)frames[i];
new_dc.ImageBase = imagebase;
new_dc.FunctionEntry = lookup;
new_dc.EstablisherFrame = establisher_frame;
new_dc.TargetIp = reinterpret_cast<uint64_t>(&lookup);
new_dc.ContextRecord = ex->ContextRecord;
new_dc.LanguageHandler = language_handler;
new_dc.HandlerData = handler_data;
auto result = language_handler(ex->ExceptionRecord, reinterpret_cast<void*>(establisher_frame), ex->ContextRecord, &new_dc);
return result;
}
}
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
void excep() {
try {
int k = 0;
throw (k);
}
catch (int j) {
std::cout << j;
}
}
int main() {
AddVectoredExceptionHandler(1, handler);
excep();
return 0;
}
Firsty, I installed a VEH that would catch only exceptions with 0xE06D7363
code, which the code that RaiseException() uses when throing C++ Exceptions (try,throw,catch).I did a stack trace using RtlCaptureStackBackTrace() and then get the function entries with RtlLookupFunctionEntry in order to pass the arguments that RtlVirtualUnwind needs to make a call to language specific handler. The code breaks when RtlVirtualUnwind is called.Any ideas?
xmr21 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.