体验CoreCLR的stack unwinding特性在Linux/Mac上的初步实现

有了stack unwinding特性,才能在.NET程序中获取调用堆栈(call stack)信息,才能在异常时显示调用堆栈信息。这个特性之前只在Windows上有实现,Linux/Mac上的实现最近才刚刚添加,用的是libunwind,详见Merge branch 'unix_issue177'

如果你不了解stack unwinding,推荐阅读 C++ Tutorial: Exceptions - Stack Unwinding

下面我们来一起体验一下。

所使用的示例控制台程序如下:

using System;
class Program
{
    static void A()
    {
        B();
    }

    static void B()
    {
        C();
    }

    static void C()
    {
        D();
    }

    static void D()
    {
        Console.WriteLine(System.Environment.StackTrace);
    }

    static void Main(string[] args)
    {
        A();
    }
}

对应的代码文件名为StackTrace.cs,编译为StackTrace.exe。

我们先在Visual Studio中创建同样的控制台程序体验一下stack unwinding的效果:

at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at Program.D()
at Program.C()
at Program.B()
at Program.A()
at Program.Main(String[] args)

接着看一下没有实现stack unwinding时的效果。

在Linux上运行corerun StackTrace.exe,控制台无任何输出。

# runtime_linux/corerun app/StackTrace.exe
# 

在Mac上运行corerun StackTrace.exe出错:

sh-3.2$ runtime_mac/corerun app/StackTrace.exe
Assert failure (unable to format)
/Users/dudu/git/dotnet/coreclr/src/vm/stackwalktypes.h
SPOffset >= pUnwindInfo->RSPOffsetFromUnwindInfo
**** MessageBox invoked, title 'Assert failure (unable to format)' ****
  SPOffset >= pUnwindInfo->RSPOffsetFromUnwindInfo
********

Assert failure (unable to format)
/Users/dudu/git/dotnet/coreclr/src/vm/stackwalktypes.h
FitsIn(pUnwindInfo->RBPOffset + (SPOffset - pUnwindInfo->RSPOffsetFromUnwindInfo))
**** MessageBox invoked, title 'Assert failure (unable to format)' ****
  FitsIn(pUnwindInfo->RBPOffset + (SPOffset - pUnwindInfo->RSPOffsetFromUnwindInfo))
********

然后看一下stack unwinding初步实现之后的效果。 

在Mac与Linux上运行corerun StackTrace.exe的结果如下:

at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at Program.Main(String[] args)
posted @ 2015-02-21 16:30  dudu  阅读(858)  评论(2编辑  收藏  举报