编译器/平台处理buggy std :: terminate()处理程序

时间:2014-07-02 16:45:20

标签: c++

在查看一些代码时,我遇到了一个错误的std::terminate()处理程序 那不是终止程序,而是返回。基于std::set_terminate()的文档,我认为这属于未定义 - 或至少是实现定义 - 行为的范围。

在Linux下,并使用GCC编译,我发现核心被转储,这意味着一些守护天使正在代表我们调用abort()或类似的东西。

所以我编写了以下测试片段,这证实了我的预感。它看起来像GCC或它的std库确实包装std::terminate()处理程序,所以它们会终止程序。

#include <iostream>
#include <exception>
#include <dlfcn.h>

// Compile using
// g++ main.cpp -ldl

// Wrap abort() in my own implementation using
// dlsym(), so I can see if GCC generates code to
// call it if my std::terminate handler doesn't.
namespace std
{
    void abort()
    {
        typedef void (*aborter)();
        static aborter real_abort = 0x0;
        if (0x0 == real_abort)
        {
            void * handle = 0x0;
            handle = dlsym(RTLD_NEXT, "abort");
            if (handle)
            {
                real_abort = (aborter )(handle);
            }
        }
        std::cout << "2. Proof that GCC calls abort() if my buggy\n"
                  << "   terminate handler returns instead of terminating."
                  << std::endl;
        if (real_abort)
        {
            real_abort();
        }
    }
}

// Buggy terminate handler that returns instead of terminating
// execution via abort (or exit)
void buggyTerminateHandler()
{
    std::cout << "1. In buggyTerminateHandler." << std::endl;
}

int main (int argc, char ** argv)
{
    // Set terminate handler
    std::set_terminate(buggyTerminateHandler);
    // Raise unhandled exception
    throw 1;
}

编译器(或库)将包装std::terminate()处理程序似乎是明智的,所以我猜想大多数编译器都会沿着这些行做某事。

有人可以建议使用GCC使用Visual Studio或OS X在Windows上进行操作吗?

0 个答案:

没有答案