屏蔽掉VC_runtime_error的类似对话框

公司最后发现某一运行在windows的服务端会弹出

runtime error


的对话框,

而用了之前的

与另一篇文章中的  禁用windows的错误报告(仅在winser 03)上试过 并不彻底..

方法并不能解决问题,


所以在网上找了一下资料,

打算

如果还没人处理,则调用操作系统的默认异常处理代码UnhandledExceptionHandler,不过操作系统允许你Hook这个函数,就是通过SetUnhandledExceptionFilter函数来设置。


主要用了

http://www.codeproject.com/KB/winsdk/crash_hook.aspx




Introduction

Windows provides a way for applications to override the default application "crash" handling functionality by the means of the SetUnhandledExceptionFilter function.

Usually, the SetUndhandledExceptionFilter function is used in conjunction with the crash reporting activity. Having the ability of pinpointing the line of code which caused a crash is invaluable in post mortem debugging.

Post mortem debugging has been discussed in other articles on CodeProject and is not the scope of this article.

Here is how a simple unhandled exception filter (which displays only "Gotcha!" in the console) looks like:

bool g_showCrashDialog = false;

LONG WINAPI OurCrashHandler(EXCEPTION_POINTERS * /*ExceptionInfo*/)
{
    std::cout << "Gotcha!" << std::endl;

    return g_showCrashDialog ? EXCEPTION_CONTINUE_SEARCH : EXCEPTION_EXECUTE_HANDLER;
}

If the crash handling function returns EXCEPTION_EXECUTE_HANDLER, the Operating System will display the default crash dialog or call the Just in time (JIT) debugger if such a debugger is installed on the system.

In order to test the code, we will simulate a null pointer invalid access like this:

int main()
{
    ::SetUnhandledExceptionFilter(OurCrashHandler);

    std::cout << "Normal null pointer crash" << std::endl;

    char *p = 0;
    *p = 5;
}

The program should then display:

Normal null pointer crash
Gotcha!

The C/C++ Runtime Library

The C/C++ Runtime Library will remove any custom crash handler in certain circumstances, and our crash handler will never be called.

Circumstances such as:

abort() function

void AbortCrash()
{
    std::cout << "Calling Abort" << std::endl;
    abort();
}

will display:

Calling Abort

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

abort is called internally in the CRT, we need to catch all those cases too.

Out of bounds vector access

void OutOfBoundsVectorCrash()
{
    std::cout << "std::vector out of bounds crash!" << std::endl;

    std::vector<int> v;
    v[0] = 5;
}

Will display:

std::vector out of bounds crash!

Pure virtual function call

void VirtualFunctionCallCrash()
{
    struct B
    {
        B()
        {
            std::cout << "Pure Virtual Function Call crash!" << std::endl;
            Bar();
        }

        virtual void Foo() = 0;

        void Bar()
        {
            Foo();
        }
    };

    struct D: public B
    {
        void Foo()
        {
        }
    };

    B* b = new D;
    // Just to silence the warning C4101:
    //    'VirtualFunctionCallCrash::B::Foo' : unreferenced local variable
    b->Foo(); 
}

Will display:

Pure Virtual Function Call crash!
R6025
- pure virtual function call

The fix

In order to have the above cases also caught, we need to redirect the SetUnhandledExceptionFilter function to a dummy function so that when the CRT calls SetUnhandledExceptionFilter(0) in order to remove any custom crash handlers, it will call our dummy function.

The redirection was done using the CAPIHook class presented in Chapter 22: DLL Injection and API Hooking of the book Windows via C/C++, Fifth Edition written by Jeffrey Richter and Christophe Nasarre, Microsoft Press (c) 2008.

The code looks like:

LONG WINAPI RedirectedSetUnhandledExceptionFilter(EXCEPTION_POINTERS * /*ExceptionInfo*/)
{
    // When the CRT calls SetUnhandledExceptionFilter with NULL parameter
    // our handler will not get removed.
    return 0;
}

int main()
{
    ::SetUnhandledExceptionFilter(OurCrashHandler);

    CAPIHook apiHook("kernel32.dll", 
      "SetUnhandledExceptionFilter", 
      (PROC)RedirectedSetUnhandledExceptionFilter);

    // Code that crashes
}

最后发现系统也不会再弹出runtime error这种运行时错误的框了...


不过看了一下,(下面转这篇不知是我哪里没有设置好.现在不管用...)

http://www.cppblog.com/woaidongmao/archive/2009/10/21/99129.html?opt=admin

里面说上面这个办法并不是什么异常都能捕捉到的.


很多软件通过设置自己的异常捕获函数,捕获未处理的异常,生成报告或者日志(例如生成mini-dump文件),达到Release版本下追踪Bug的目的。但是,到了VS2005(即VC8),Microsoft对CRT(C运行时库)的一些与安全相关的代码做了些改动,典型的,例如增加了对缓冲溢出的检查。新CRT版本在出现错误时强制把异常抛给默认的调试器(如果没有配置的话,默认是Dr.Watson),而不再通知应用程序设置的异常捕获函数,这种行为主要在以下三种情况出现。

(1)       调用abort函数,并且设置了_CALL_REPORTFAULT选项(这个选项在Release版本是默认设置的)。

(2)       启用了运行时安全检查选项,并且在软件运行时检查出安全性错误,例如出现缓存溢出。(安全检查选项 /GS 默认也是打开的)

(3)       遇到_invalid_parameter错误,而应用程序又没有主动调用

_set_invalid_parameter_handler设置错误捕获函数。

所以结论是,使用VS2005(VC8)编译的程序,许多错误都不能在SetUnhandledExceptionFilter捕获到。这是CRT相对于前面版本的一个比较大的改变,但是很遗憾,Microsoft却没有在相应的文档明确指出。

解决方法

       之所以应用程序捕获不到那些异常,原因是因为新版本的CRT实现在异常处理中强制删除所有应用程序先前设置的捕获函数,如下所示:

 /* Make sure any filter already in place is deleted. */

 SetUnhandledExceptionFilter(NULL);

 UnhandledExceptionFilter(&ExceptionPointers);

解决方法是拦截CRT调用SetUnhandledExceptionFilter函数,使之无效。在X86平台下,可以使用以下代码。

#ifndef _M_IX86

       #error "The following code only works for x86!"

#endif

 

void DisableSetUnhandledExceptionFilter()

{

    void *addr = (void*)GetProcAddress(LoadLibrary(_T("kernel32.dll")),

                                                         "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);

       }

}

在设置自己的异常处理函数后,调用DisableSetUnhandledExceptionFilter禁止CRT设置即可。

其它讨论

       上面通过设置api hook,解决了在VS2005上的异常捕获问题,这种虽然不是那么“干净”的解决方案,确是目前唯一简单有效的方式。

       虽然也可以通过_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT), signal(SIGABRT, ...), 和_set_invalid_parameter_handler(...) 解决(1)(3),但是对于(2),设置api hook是唯一的方式。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值