C++软件开发,安装运行程序后SetUnhandledExceptionFilter无法捕获异常问题

自 VC++2005 开始出于安全因素微软改变了 CRT 的行为,导致 CRT 不会通知被注册的 Unhandled Exception Filter。其原因在于CRT 通过调用 SetUnhandledExceptionFilter 并传递参数 NULL 来清除用户注册的 Unhandled Exception Filter。CRT调用如下:

SetUnhandledExceptionFilter(NULL);
UnhandledExceptionFilter(&ExceptionPointers);

因此为了避免出现这种情况,使用以下方式阻止CRT对SetUnhandledExceptionFilter的调用:

// 此函数一旦成功调用,之后对 SetUnhandledExceptionFilter 的调用将无效
void DisableSetUnhandledExceptionFilter()
{
    HMODULE hDbgHelp = LoadLibrary(L"kernel32.dll");
    void* addr = (void*)GetProcAddress(hDbgHelp,"SetUnhandledExceptionFilter");
    if (addr) 
    {
        unsigned char code[16];
        int size = 0;
        code[size++] = 0x33;
        code[size++] = 0xC0;
        code[size++] = 0xC2;
        code[size++] = 0x04;
        code[size++] = 0x00;
        DWORD dwOldFlag, dwTempFlag;
        VirtualProtect(addr, size, PAGE_READWRITE, &dwOldFlag);
        WriteProcessMemory(GetCurrentProcess(), addr, code, size, NULL);
        VirtualProtect(addr, size, dwOldFlag, &dwTempFlag);
    }
}

在注册 Unhandled Exception Filter 后调用 DisableSetUnhandledExceptionFilter() 函数,之后所有对 SetUnhandledExceptionFilter 的调用都将无效。CRT 对SetUnhandledExceptionFilter 的调用也将无效。

DisableSetUnhandledExceptionFilter调用:

SetUnhandledExceptionFilter(ExceptionFilter);//异常处理 生成dmp文件
DisableSetUnhandledExceptionFilter();//设置CRT对SetUnhandledExceptionFilter调用无效
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值