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

本文通过一个简单的.NET控制台程序演示了StackUnwinding特性的重要性。该特性允许程序在异常时获取并显示调用堆栈信息。文章对比了Windows、Linux及Mac环境下启用与未启用StackUnwinding的不同效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://www.cnblogs.com/dudu/p/coreclr-stack-unwinding.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值