如何分析 StackOverflow 异常 ?

dotNET全栈开发

共 2348字,需浏览 5分钟

 ·

2021-10-22 11:12

一般来说,当你的方法递归调用次数太多大于线程栈的默认1M内存时将会抛出 StackOverflowException 异常。

举个例子,假设你有下面这段代码:


using System;

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

这个 Main 方法会持续的调用自己直到超出默认的栈空间,因为没有栈空间了,所有 CLR 执行引擎 就会抛出 StackOverflowException 异常。


> dotnet run
Stack overflow.

接下来我们看看如何在 .netcore 中生成这种 crash dump。

netcore 生成 dump

  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 工具

dotnet-sos installc

  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=, pArguments=0x00007ffe8222e7b0, pReturnValue=0x0000000000000000, cbReturnValue=0) at callhelpers.cpp:604
    frame #261938: 0x00007f5a2d4b6182 libcoreclr.so`RunMain(MethodDesc*, short, int*, PtrArray**) [inlined] MethodDescCallSite::Call(this=, pArguments=) at callhelpers.h:468
...

  1. 可以看到栈顶的 0x00007f59b40900cc 出现了多次重复,然后使用 SOS 的 ip2md 命令通过 address 找到对应的方法。

(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 @ 9 行中找到问题代码,如果还没有水落石出的话,可以再辅助一些日志。
浏览 25
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报