如何排查 StackOverflow 异常

StackOverflowException 从名字上就能看出来它表示当前执行栈溢出,通常都是由于无限的方法递归调用导致的。

举个例子,假如你有下面的一段代码:


using System;

namespace temp
{
    class Program
    {
        static void Main(string[] args)
        {
            Main(args); // Oops, this recursion won't stop.
        }
    }
}

上面的 Main 方法会不断的调用自己直到没有足够的栈空间,一旦到了这个临界值,执行引擎将会抛出 StackOverflowException


> dotnet run
Stack overflow.

Example

  1. 运行程序前先配置变量 export DOTNET_DbgEnableMiniDump=1,这样就可以在crash的时候自动生成dump文件。


> export DOTNET_DbgEnableMiniDump=1
> dotnet run
Stack overflow.
Writing minidump with heap to file /tmp/coredump.6412
Written 58191872 bytes (14207 pages) to core file

  1. 使用 dotnet-sos 安装 sos 扩展


dotnet-sos install

  1. 使用 lldb 查看dump中抛出堆栈溢出的线程栈。


lldb --core /temp/coredump.6412
(lldb) bt
...
    frame #261930: 0x00007f59b40900cc
    frame #261931: 0x00007f59b40900cc
    frame #261932: 0x00007f59b40900cc
    frame #261933: 0x00007f59b40900cc
    frame #261934: 0x00007f59b40900cc
    frame #261935: 0x00007f5a2d4a080f libcoreclr.so`CallDescrWorkerInternal at unixasmmacrosamd64.inc:867
    frame #261936: 0x00007f5a2d3cc4c3 libcoreclr.so`MethodDescCallSite::CallTargetWorker(unsigned long const*, unsigned long*, int) at callhelpers.cpp:70
    frame #261937: 0x00007f5a2d3cc468 libcoreclr.so`MethodDescCallSite::CallTargetWorker(this=<unavailable>, pArguments=0x00007ffe8222e7b0, pReturnValue=0x0000000000000000, cbReturnValue=0) at callhelpers.cpp:604
    frame #261938: 0x00007f5a2d4b6182 libcoreclr.so`RunMain(MethodDesc*, short, int*, PtrArray**) [inlined] MethodDescCallSite::Call(this=<unavailable>, pArguments=<unavailable>) at callhelpers.h:468
...

  1. 从堆栈看 0x00007f59b40900cc 重复了很多次,然后使用 !ip2md 查看该地址对应的方法描述符。


(lldb) ip2md 0x00007f59b40900cc
MethodDesc:   00007f59b413ffa8
Method Name:          temp.Program.Main(System.String[])
Class:                00007f59b4181d40
MethodTable:          00007f59b4190020
mdToken:              0000000006000001
Module:               00007f59b413dbf8
IsJitted:             yes
Current CodeAddr:     00007f59b40900a0
Version History:
  ILCodeVersion:      0000000000000000
  ReJIT ID:           0
  IL Addr:            0000000000000000
     CodeAddr:           00007f59b40900a0  (MinOptJitted)
     NativeCodeVersion:  0000000000000000
Source file:  /temp/Program.cs @ 9

  1. 通过 /temp/Program.cs @ 9temp.Program.Main(System.String[]) 两个信息相信就可以找出程序中的问题,当然,如果你还不是特别明白的话,可以在质疑处多加点日志排查。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值