歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> 體驗CoreCLR的stack unwinding特性在Linux/Mac上的初步實現

體驗CoreCLR的stack unwinding特性在Linux/Mac上的初步實現

日期:2017/2/28 14:02:07   编辑:Linux教程

有了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)
Copyright © Linux教程網 All Rights Reserved