在MinGW中生成C++异常的堆栈跟踪

6

这篇文章 "如何在我的gcc C++应用程序崩溃时生成堆栈跟踪" 解释了当应用程序崩溃时如何生成堆栈跟踪。但是,gcc版本在Windows MinGW上不起作用。实际上,由于缺少头文件execinfo.h,它甚至无法编译。

在Windows XP及以上版本的MinGW上是否已经有可用的东西?

编辑

以下是可能的步骤进行堆栈跟踪。但是,当我尝试在异常的catch块中遍历堆栈时,我没有得到期望的结果。我只能获得抛出异常的函数名称,之后显示列表-->main-->等等

步骤:

  1. Win32 API stack walk with MinGW/MSYS?的帖子中,José Luis Cebrián提供的第一个答案指向了Mr.Edd的堆栈跟踪库的链接http://www.mr-edd.co.uk/code/stack_trace

  2. 上述链接中可用的stackwalker依赖于dbghelp.dll。由于MinGW没有为此提供导入库,因此使用mingw的dlltool生成了它。命令如下:

    dlltool -k -d dbghelp.def -l dbghelp.a

    注意1:.def文件可以在Wine项目中找到

    注意2:库的生成不适用于所有版本的MinGW。我在使用4.4.1版本时遇到了问题,但在4.6.1版本中可以正常工作

  3. 除了-ldbghelp之外,还使用了-lbfd,-lintl和-liberty库进行链接

  4. 结构化异常处理来自链接http://www.programmingunlimited.net/siteexec/content.cgi?page=mingw-seh

代码视图

  1. "Try" implementation is as below. This part registers the exception handler

    { 
    __SEH_EXCEPTION_REGISTRATION _lseh_er;
    __SEH_HANDLER _lseh_handler;
    _lseh_er.handler =
    reinterpret_cast<PEXCEPTION_HANDLER>(__SEH_HANDLER::ExceptionRouter);
    _lseh_er.exthandler = &_lseh_handler;
    asm volatile ("movl %%fs:0, %0" : "=r" (_lseh_er.prev));
    asm volatile ("movl %0, %%fs:0" : : "r" (&_lseh_er));
    int _lseh_setjmp_res = setjmp(_lseh_handler.context);
    while(true) {
     if(_lseh_setjmp_res != 0) {
       break;
     }
    
  2. The ExceptionRounter function calls another function ExceptionHandler where the context and record are copied. The implementation is as below.

    EXCEPTION_DISPOSITION __SEH_HANDLER::ExceptionHandler(PEXCEPTION_RECORD pRecord, 
    __SEH_EXCEPTION_REGISTRATION* pReg,
    PCONTEXT pContext,
    PEXCEPTION_RECORD pRecord2)
    {
    
    CopyMemory(&excContext, pContext, sizeof(_CONTEXT));
    CopyMemory(&excRecord, pRecord, sizeof(_EXCEPTION_RECORD));
    
    // Jump back to the function where the exception actually occurred.  The 1 is the
    // return code that will be returned by set_jmp.
    longjmp(context, 1);
    }
    
  3. After this is my code that throws exception

  4. Followed by implementation of "catch" or seh_excep.

    break;
    }
    PEXCEPTION_RECORD rec = &_lseh_handler.excRecord;
    PCONTEXT ctx = &_lseh_handler.excContext;
    
    asm volatile ("movl %0, %%fs:0" : : "r" (_lseh_er.prev));
    if(_lseh_setjmp_res != 0)
    
  5. Then comes the code to walk the stack from Mr.Edd's stackwalker.

    lock lk(g_fill_frames_mtx);
    
    symbol_context sc;
    bfd_context bfdc;
    
    
    STACKFRAME frame = empty_pod;
    CONTEXT context = empty_pod;
    context.ContextFlags = CONTEXT_FULL;
    
    /*Below part is commented as the context of the exception causing code has to be  used and not the current context*/
    /*
    windows_dll kernel32("kernel32.dll");
    void (WINAPI *RtlCaptureContext_)(CONTEXT*) =  kernel32.function("RtlCaptureContext");
    RtlCaptureContext_(&context);
    */
    
    context = _lseh_handler.excContex;
    
    frame.AddrPC.Offset = context.Eip;
    frame.AddrPC.Mode = AddrModeFlat;
    frame.AddrStack.Offset = context.Esp;
    frame.AddrStack.Mode = AddrModeFlat;
    frame.AddrFrame.Offset = context.Ebp;
    frame.AddrFrame.Mode = AddrModeFlat;
    
    
    HANDLE process = GetCurrentProcess();
    HANDLE thread = GetCurrentThread();
    
    bool skip = true;
    bool has_limit = limit != 0;
    char symbol_buffer[sizeof(IMAGEHLP_SYMBOL) + 255];
    char module_name_raw[MAX_PATH];
    
    const DWORD machine = IMAGE_FILE_MACHINE_I386;
    
    while(StackWalk(machine, process, thread, &frame, &context, 0, SymFunctionTableAccess, SymGetModuleBase, 0))
    {
        if (skip)
        {
            skip = false;
            continue;
        }
    
        if (has_limit && limit-- == 0) break;
    
        IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(symbol_buffer);
        symbol->SizeOfStruct = (sizeof *symbol) + 255;
        symbol->MaxNameLength = 254;
        DWORD module_base = SymGetModuleBase(process, frame.AddrPC.Offset);
        std::string module_name = unknown_module;
        if (module_base && GetModuleFileNameA(reinterpret_cast<HINSTANCE>(module_base), module_name_raw, MAX_PATH))
            module_name = module_name_raw;
            std::string func = bfdc.get_function_name(frame.AddrPC.Offset);
    
            if (func.empty())
            {
                DWORD dummy = 0;
                BOOL got_symbol = SymGetSymFromAddr(process, frame.AddrPC.Offset, &dummy, symbol);
                func = got_symbol ? symbol->Name : unknown_function;
            }
    
        dbg::stack_frame f(reinterpret_cast<const void *>(frame.AddrPC.Offset), func, module_name);
        frames.push_back(f);
        }
      }
    }
    std::copy(frames.begin(), frames.end(), std::ostream_iterator<dbg::stack_frame>(std::cout, "\n"));
    

问候,Shreyas


@HansPassant,请查看我的最新编辑。使用StackWalk可以遍历堆栈是可行的。但是,当出现异常时,尽管上下文已经被复制,我仍然在尝试遍历堆栈时遇到问题。 - Shreyas S
@HansPassant,有没有办法在异常处理函数中复制堆栈帧,以便在catch子句中使用?我需要复制除上下文和记录之外的其他内容吗? - Shreyas S
@HansPassant 不是针对 MinGW 在做 http://www.programmingunlimited.net/siteexec/content.cgi?page=mingw-seh 吗?这已经在上面的代码中使用过了。感谢迄今为止的回答。 - Shreyas S
1个回答

0

在链接http://www.programmingunlimited.net/siteexec/content.cgi?page=libseh中提供了LibSEH,解决了这个问题。

从我得到的回复中可以得出结论,在我的实现中,异常处理代码与引发异常的代码在同一上下文中调用。这导致覆盖了现在不相关的部分堆栈。

然而,异常处理过滤器函数在不同的上下文中执行,并通过将堆栈跟踪器放置在过滤器函数中来实现所需的结果。

因此,我使用了类似于MSVC中找到的异常处理功能的libseh,并在过滤器函数中编写了堆栈跟踪器。


1
能否使用简单的堆栈跟踪代码?例如,一个包含完整示例的main.c文件?我自己尝试了很多次都没成功,真的很抱歉。我正在使用GCC 4.6.2(MingW)和libseh。 - morde

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接