.NET高级调试之sos命令输出看不懂怎么办

一:背景

1. 讲故事

很多.NET开发者在学习高级调试的时候,使用sos的命令输出会发现这里也看不懂那里也看不懂,比如截图中的这位朋友。


.NET高级调试属于一个偏冷门的领域,国内可观测的资料比较少,所以很多东西需要你自己去探究源代码,然后用各种调试工具去验证,相关源代码如下:

这一篇权当抛砖引玉,来引导一下如何去探索。

二:WinDbg 分析

1. 复原现象

为了方便讲述先上一段简单的测试代码,来观察一下线程列表中所谓的 lockcount 列。

C# 复制代码
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("hello world...");
            Debugger.Break();
        }
    }

接下来用 windbg 附加一下,使用 !threads 命令观察输出。

C# 复制代码
0:000> !t
ThreadCount:      3
UnstartedThread:  0
BackgroundThread: 2
PendingThread:    0
DeadThread:       0
Hosted Runtime:   no
                                                                                                            Lock  
 DBG   ID     OSID ThreadOBJ           State GC Mode     GC Alloc Context                  Domain           Count Apt Exception
   0    1     14c8 000001A8B862DBB0    2a020 Preemptive  000001A8BA1DDEE0:000001A8BA1DF478 000001a8b8623c20 0     MTA 
   5    2     71e0 000001A8D25740B0    2b220 Preemptive  0000000000000000:0000000000000000 000001a8b8623c20 0     MTA (Finalizer) 
   7    3     31b0 000001A8B86E7730  102a220 Preemptive  0000000000000000:0000000000000000 000001a8b8623c20 0     MTA (Threadpool Worker) 

从上面的卦中可以看到 Lock Count=0,那这里的值取自源码的哪里呢?

2. 取自哪里

大家要知道每一行记录都是在coreclr Thread中摘取出来的字段,言外之意就是可以把 Thread 所有信息给展示出来,可以用 dt 命令,简化后如下:

C# 复制代码
0:000> dt coreclr!Thread 000001A8B862DBB0
   +0x000 __VFN_table : 0x00007ffd`d2f93c70 
   =00007ffd`d30ce8d8 m_DetachCount    : 0n0
   =00007ffd`d30ce8d4 m_ActiveDetachCount : 0n0
   =00007ffd`d30cf4dc m_threadsAtUnsafePlaces : Volatile<long>
   +0x008 m_State          : Volatile<enum Thread::ThreadState>
   +0x00c m_fPreemptiveGCDisabled : Volatile<unsigned long>
   +0x010 m_pFrame         : 0x0000006f`df57e328 Frame
   +0x018 m_pDomain        : 0x000001a8`b8623c20 AppDomain
   +0x020 m_dwLockCount    : 0
   +0x024 m_ThreadId       : 1
   ...

通过仔细分析卦中信息,可以发现这个 lockcount 其实就是 m_dwLockCount 字段,知道是这个字段之后接下来就是寻找coreclr源码啦,截图如下:

从源码注释中看的非常清楚,这个字段可用来跟踪5中锁。

  • critical section
  • spin lock
  • syncblock lock
  • EE Crst
  • GC lock

接下来搜索下源码看看 m_dwLockCount 是怎么更新的,可以发现如下两处,并且都是和同步块索引相关,截图如下:

C# 复制代码
inline void Thread::IncLockCount()
{
    LIMITED_METHOD_CONTRACT;
    _ASSERTE(GetThread() == this);
    m_dwLockCount++;
    _ASSERTE(m_dwLockCount != 0 || HasThreadStateNC(TSNC_UnbalancedLocks));
}

inline void Thread::DecLockCount()
{
    LIMITED_METHOD_CONTRACT;
    _ASSERTE(GetThread() == this);
    _ASSERTE(m_dwLockCount > 0 || HasThreadStateNC(TSNC_UnbalancedLocks));
    m_dwLockCount--;
}

接下来要做的一件事就是如何自增 m_dwLockCount 值 来模拟达到这位朋友的 1024。

3. 如何模拟复现

其实当你知道是跟踪这五种锁,要模拟就非常简单了,为了方便讲述上一段测试代码,利用 lock 让 m_dwLockCount 字段不断自增,参考如下:

C# 复制代码
    internal class Program
    {
        public static object[] locks;

        static void Main(string[] args)
        {
            locks = Enumerable.Range(0, 100).Select(i => new object()).ToArray();

            foreach (var item in locks)
            {
                Monitor.Enter(item);
            }

            Debugger.Break();
            Console.ReadLine();
        }
    }

接下来用 windbg 附加观察一下。

C# 复制代码
0:000> !t
ThreadCount:      3
UnstartedThread:  0
BackgroundThread: 2
PendingThread:    0
DeadThread:       0
Hosted Runtime:   no
                                                                                                            Lock  
 DBG   ID     OSID ThreadOBJ           State GC Mode     GC Alloc Context                  Domain           Count Apt Exception
   0    1     6c90 00000239840DDBB0    2a020 Preemptive  0000023985B2BB38:0000023985B2D478 00000239840d3c20 100   MTA 
   5    2     2178 00000239859640B0    2b220 Preemptive  0000000000000000:0000000000000000 00000239840d3c20 0     MTA (Finalizer) 
   7    3     6d00 0000023984197700  102a220 Preemptive  0000000000000000:0000000000000000 00000239840d3c20 0     MTA (Threadpool Worker) 

0:000> dt coreclr!Thread 00000239840DDBB0
   +0x000 __VFN_table : 0x00007ffd`d2f93c70 
   =00007ffd`d30ce8d8 m_DetachCount    : 0n0
   =00007ffd`d30ce8d4 m_ActiveDetachCount : 0n0
   =00007ffd`d30cf4dc m_threadsAtUnsafePlaces : Volatile<long>
   +0x008 m_State          : Volatile<enum Thread::ThreadState>
   +0x00c m_fPreemptiveGCDisabled : Volatile<unsigned long>
   +0x010 m_pFrame         : 0x00000074`a937e888 Frame
   +0x018 m_pDomain        : 0x00000239`840d3c20 AppDomain
   +0x020 m_dwLockCount    : 0x64

这里顺便提一下,如果你想实时观察 m_dwLockCount 更改的线程栈信息,可以在 Thread+0x20处下一个ba硬件断点即可。

C# 复制代码
0:000> !t
ThreadCount:      3
UnstartedThread:  0
BackgroundThread: 2
PendingThread:    0
DeadThread:       0
Hosted Runtime:   no
                                                                                                            Lock  
 DBG   ID     OSID ThreadOBJ           State GC Mode     GC Alloc Context                  Domain           Count Apt Exception
   0    1     6188 00000290D550DBB0    2a020 Preemptive  00000290D6F4AD20:00000290D6F4B478 00000290d5503c20 0     MTA 
   5    2     686c 00000290EF3F40B0    2b220 Preemptive  0000000000000000:0000000000000000 00000290d5503c20 0     MTA (Finalizer) 
   7    3     312c 00000290D55C7740  102a220 Preemptive  0000000000000000:0000000000000000 00000290d5503c20 0     MTA (Threadpool Worker) 
0:000> ba w4 00000290D550DBB0+0x20
0:000> g
ModLoad: 00007ffd`cff80000 00007ffd`cffd1000   C:\Program Files\dotnet\shared\Microsoft.NETCore.App\3.1.32\System.Collections.dll
ModLoad: 00007ffd`d00d0000 00007ffd`d0103000   C:\Program Files\dotnet\shared\Microsoft.NETCore.App\3.1.32\System.Runtime.Extensions.dll
Breakpoint 1 hit
coreclr!JIT_MonEnter_Portable+0x65:
00007ffd`d298c8a5 4883c430        add     rsp,30h

0:000> kL 5
 # Child-SP          RetAddr               Call Site
00 000000b5`f917e780 00007ffd`72e917f4     coreclr!JIT_MonEnter_Portable+0x65
01 000000b5`f917e7c0 00007ffd`d29b6ca3     0x00007ffd`72e917f4
02 000000b5`f917e860 00007ffd`d294cc62     coreclr!CallDescrWorkerInternal+0x83
03 (Inline Function) --------`--------     coreclr!CallDescrWorkerWithHandler+0x57
04 000000b5`f917e8a0 00007ffd`d2953c29     coreclr!MethodDescCallSite::CallTargetWorker+0x196
...

三:总结

还是那句话,国内.NET高级调试方面的资料甚少,要想理解sos命令输出是什么意思,切记多看源码,其实本篇重要的不是知识,而是告诉你如何去探究新知的方法。