代码之家  ›  专栏  ›  技术社区  ›  c-urchin

来自未处理异常的C++堆栈跟踪?

  •  29
  • c-urchin  · 技术社区  · 16 年前

    这个问题以前曾被问过,有Windows特定的答案,但没有令人满意的GCC答案。我可以用 set_terminate() 设置将被调用的函数(代替 terminate() )当引发未处理的异常时。我知道如何使用回溯库从程序中的给定点生成堆栈跟踪。但是,当调用我的TerminateReplacement时,这不会有所帮助,因为此时堆栈已被解除绑定。

    但是如果我允许程序 abort() 它将生成一个核心转储,其中包含从引发异常的点开始的完整堆栈信息。所以信息是存在的——但是有没有一种程序化的方法来获取它,例如,这样它就可以被记录,而不必检查核心文件?

    3 回复  |  直到 11 年前
        1
  •  26
  •   Sam Miller    13 年前

    编辑回答:

    你可以使用 std::set_terminate

    #include <cstdlib>
    #include <iostream>
    #include <stdexcept>
    
    #include <execinfo.h>
    
    void
    handler()
    {
        void *trace_elems[20];
        int trace_elem_count(backtrace( trace_elems, 20 ));
        char **stack_syms(backtrace_symbols( trace_elems, trace_elem_count ));
        for ( int i = 0 ; i < trace_elem_count ; ++i )
        {
            std::cout << stack_syms[i] << "\n";
        }
        free( stack_syms );
    
        exit(1);
    }   
    
    int foo()
    {
        throw std::runtime_error( "hello" );
    }   
    
    void bar()
    {
        foo();
    }
    
    void baz()
    {
        bar();
    }
    
    int
    main()
    {
        std::set_terminate( handler );
        baz();
    }
    

    给出这个输出:

    samm@macmini ~> ./a.out 
    ./a.out [0x10000d20]
    /usr/lib/libstdc++.so.6 [0xf9bb8c8]
    /usr/lib/libstdc++.so.6 [0xf9bb90c]
    /usr/lib/libstdc++.so.6 [0xf9bbaa0]
    ./a.out [0x10000c18]
    ./a.out [0x10000c70]
    ./a.out [0x10000ca0]
    ./a.out [0x10000cdc]
    /lib/libc.so.6 [0xfe4dd80]
    /lib/libc.so.6 [0xfe4dfc0]
    samjmill@bgqfen4 ~> 
    

    假设二进制文件中有调试符号,那么就可以使用addr2line构造一个prettier堆栈跟踪后期分析。

    samm@macmini ~> addr2line 0x10000c18
    /home/samm/foo.cc:23
    samm@macmini ~> 
    

    原始答案如下


    我以前用 boost::error_info 要插入堆栈跟踪,请使用 backtrace 从 execinfo.h 引发异常。

    typedef boost::error_info<struct tag_stack_str,std::string> stack_info;
    

    当捕获异常时,您可以这样做

    } catch ( const std::exception& e ) {                                                                                                            
        if ( std::string const *stack boost::get_error_info<stack_error_info>(e) ) {                    
            std::cout << stack << std::endl;
        }
    }
    
        2
  •  3
  •   Dummy00001    16 年前

    然而,如果我只允许程序abort(),它将生成一个核心转储,其中包含从抛出异常点开始的完整堆栈信息。所以信息是存在的——但是有没有一种程序化的方法来获取它,例如,这样它就可以被记录,而不必检查核心文件?

    我怀疑我的经验能满足你的需要,但不管怎样,我还是要说。

    我超载了 abort() :在libc之前添加自己的对象文件或使用ld_preload。在我自己的版本中 中止() 我启动了调试器,告诉它附加到进程(当然,我肯定知道我的PID),并将堆栈跟踪转储到一个文件中(命令通过命令行传递给调试器)。在调试器完成后,使用例如 _exit(100) .

    那是在使用gdb的Linux上。在Solaris上,我通常使用类似的技巧,但由于没有健全的调试器,我使用pstack工具: system("pstack <PID>") .

        3
  •  1
  •   Tomilov Anatoliy    11 年前

    你可以使用 利本风 (只是添加 -lunwind 到链接器参数)(使用测试 clang++ 3.6 ):

    DEMAGLE

    #pragma once
    
    char const *
    get_demangled_name(char const * const symbol) noexcept;
    

    Dimangle CPP:

    #include "demangle.hpp"
    
    #include <memory>
    
    #include <cstdlib>
    
    #include <cxxabi.h>
    
    namespace
    {
    
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Wglobal-constructors"
    #pragma clang diagnostic ignored "-Wexit-time-destructors"
    std::unique_ptr< char, decltype(std::free) & > demangled_name{nullptr, std::free};
    #pragma clang diagnostic pop
    
    }
    
    char const *
    get_demangled_name(char const * const symbol) noexcept
    {
        if (!symbol) {
            return "<null>";
        }
        int status = -4;
        demangled_name.reset(abi::__cxa_demangle(symbol, demangled_name.release(), nullptr, &status));
        return ((status == 0) ? demangled_name.get() : symbol);
    }
    

    回溯

    #pragma once
    #include <ostream>
    
    void
    backtrace(std::ostream & _out) noexcept;
    

    RACTRAPE.CPP:

    #include "backtrace.hpp"
    
    #include <iostream>
    #include <iomanip>
    #include <limits>
    #include <ostream>
    
    #include <cstdint>
    
    #define UNW_LOCAL_ONLY
    #include <libunwind.h>
    
    namespace
    {
    
    void
    print_reg(std::ostream & _out, unw_word_t reg) noexcept
    {
        constexpr std::size_t address_width = std::numeric_limits< std::uintptr_t >::digits / 4;
        _out << "0x" << std::setfill('0') << std::setw(address_width) << reg;
    }
    
    char symbol[1024];
    
    }
    
    void
    backtrace(std::ostream & _out) noexcept
    {
        unw_cursor_t cursor;
        unw_context_t context;
        unw_getcontext(&context);
        unw_init_local(&cursor, &context);
        _out << std::hex << std::uppercase;
        while (0 < unw_step(&cursor)) {
            unw_word_t ip = 0;
            unw_get_reg(&cursor, UNW_REG_IP, &ip);
            if (ip == 0) {
                break;
            }
            unw_word_t sp = 0;
            unw_get_reg(&cursor, UNW_REG_SP, &sp);
            print_reg(_out, ip);
            _out << ": (SP:";
            print_reg(_out, sp);
            _out << ") ";
            unw_word_t offset = 0;
            if (unw_get_proc_name(&cursor, symbol, sizeof(symbol), &offset) == 0) {
                _out << "(" << get_demangled_name(symbol) << " + 0x" << offset << ")\n\n";
            } else {
                _out << "-- error: unable to obtain symbol name for this frame\n\n";
            }
        }
        _out << std::flush;
    }
    

    backtrace_on_terminate.hpp:

    #include "demangle.hpp"
    #include "backtrace.hpp"
    
    #include <iostream>
    #include <type_traits>
    #include <exception>
    #include <memory>
    #include <typeinfo>
    
    #include <cstdlib>
    
    #include <cxxabi.h>
    
    namespace
    {
    
    [[noreturn]]
    void
    backtrace_on_terminate() noexcept;
    
    static_assert(std::is_same< std::terminate_handler, decltype(&backtrace_on_terminate) >{});
    
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Wglobal-constructors"
    #pragma clang diagnostic ignored "-Wexit-time-destructors"
    std::unique_ptr< std::remove_pointer_t< std::terminate_handler >, decltype(std::set_terminate) & > terminate_handler{std::set_terminate(backtrace_on_terminate), std::set_terminate};
    #pragma clang diagnostic pop
    
    [[noreturn]]
    void
    backtrace_on_terminate() noexcept
    {
        std::set_terminate(terminate_handler.release()); // to avoid infinite looping if any
        backtrace(std::clog);
        if (std::exception_ptr ep = std::current_exception()) {
            try {
                std::rethrow_exception(ep);
            } catch (std::exception const & e) {
                std::clog << "backtrace: unhandled exception std::exception:what(): " << e.what() << std::endl;
            } catch (...) {
                if (std::type_info * et = abi::__cxa_current_exception_type()) {
                    std::clog << "backtrace: unhandled exception type: " << get_demangled_name(et->name()) << std::endl;
                } else {
                    std::clog << "backtrace: unhandled unknown exception" << std::endl;
                }
            }
        }
        std::_Exit(EXIT_FAILURE);
    }
    
    }
    

    有 good article 关于这个问题。

    推荐文章