文章出處

有了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)

文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()