偵錯 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.

注意

在 .NET 5 和更新版本上,呼叫堆疊會輸出至主控台。

注意

本文說明如何使用 lldb 對堆疊溢位進行偵錯。 如果您在 Windows 上執行,建議您使用 Visual StudioVisual Studio Code 對應用程式進行偵錯。

範例

  1. 執行已設定為在當機時收集傾印的應用程式

    > 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
    

    注意

    .NET 6 會針對設定 .NET Runtime 行為的環境變數,透過前置詞 DOTNET_ (而非 COMPlus_) 進行標準化。 不過,COMPlus_ 前置詞將繼續運作。 如果使用舊版的 .NET 執行階段,則您仍應對環境變數使用 COMPlus_ 前置詞。

  2. 使用 dotnet-sos 安裝 SOS 擴充功能

    dotnet-sos install
    
  3. 偵錯 lldb 中的傾印以檢視失敗的堆疊

    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
    ...
    
  4. 頂端框架 0x00007f59b40900cc 重複數次。 使用SOSip2md 命令找出位於 0x00007f59b40900cc 位址的方法

    (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
    
  5. 查看指示的方法暫 temp.Program.Main(System.String[]) 和來源 "/temp/Program.cs @ 9",以查看您是否可以找出您發生錯誤的內容。 如果仍不清楚,您可以在程式碼的該區域中新增記錄。

另請參閱