Microsoft MVP성태의 닷넷 이야기
.NET Framework: 392. .NET 스레드 콜 스택 덤프 (6) - MDbg를 이용한 방법 [링크 복사], [링크+제목 복사],
조회: 19585
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 7개 있습니다.)
.NET Framework: 167. 다른 스레드의 호출 스택 덤프 구하는 방법
; https://www.sysnet.pe.kr/2/0/802

.NET Framework: 260. .NET 스레드 콜 스택 덤프 (2) - Managed Stack Explorer 소스 코드를 이용한 스택 덤프 구하는 방법
; https://www.sysnet.pe.kr/2/0/1162

.NET Framework: 261. .NET 스레드 콜 스택 덤프 (3) - MSE 소스 코드 개선
; https://www.sysnet.pe.kr/2/0/1163

.NET Framework: 262. .NET 스레드 콜 스택 덤프 (4) - .NET 4.0을 지원하지 않는 MSE 응용 프로그램 원인 분석
; https://www.sysnet.pe.kr/2/0/1164

.NET Framework: 311. .NET 스레드 콜 스택 덤프 (5) - ICorDebug 인터페이스 사용법
; https://www.sysnet.pe.kr/2/0/1249

.NET Framework: 392. .NET 스레드 콜 스택 덤프 (6) - MDbg를 이용한 방법
; https://www.sysnet.pe.kr/2/0/1534

.NET Framework: 606. .NET 스레드 콜 스택 덤프 (7) - ClrMD(Microsoft.Diagnostics.Runtime)를 이용한 방법
; https://www.sysnet.pe.kr/2/0/11043




.NET 스레드 콜 스택 덤프 (6) - MDbg를 이용한 방법

".NET 스레드 콜 스택 덤프" 관련 시리즈의 마지막이 될 것 같군요. ^^

4편에 보면 MDbg를 이용한 방법을 설명드렸는데요.

오늘은 문득, MDbg가 GUI에서 Attach했을 때 .NET 4.0 응용 프로그램이 지원되지 않았던 것일 뿐 명령행 프롬프트 창에서는 가능하지 않을까...라는 생각이 들었습니다. ^^; 세상에나 그런 간단한 생각이 이제서야 떠오르다니.

그래서 실제로 한번 해봤습니다. 다음과 같이 예제로 Sleep 프로그램을 실행하고,

static void Main(string[] args)
{
    Console.WriteLine(Process.GetCurrentProcess().Id);
    Thread.Sleep(new TimeSpan(60, 0, 0));
}

MDbg를 이용해 콜스택을 뜨면,

CLR Managed Debugger (mdbg) Sample 
; http://www.microsoft.com/en-us/download/details.aspx?id=19621
; https://github.com/ichengzi/MDbg-Sample

MDbg 명령행 모드에서 .NET 4.0 응용 프로그램을 attach시켜 콜 스택을 뜰 수 있습니다.

managed_thread_call_stack_dump_0.png

MDbg (Managed debugger) v2.1.0.0 started.
Copyright (C) Microsoft Corporation. All rights reserved.

For information about commands type "help";
to exit program type "quit".

mdbg> a 11336
[p#:0, t#:1] mdbg> t 0
Current thread is #0 [waiting].
STOP AttachComplete
IP: 0 @ System.Threading.Thread.Sleep - MAPPING_APPROXIMATE
[p#:0, t#:0] mdbg> w
Thread [#:0]
*0. System.Threading.Thread.Sleep (source line information unavailable)
 1. System.Threading.Thread.Sleep (source line information unavailable)
 2. ConsoleApplication1.Program.Main (d:\...\ConsoleApplication1\Program.cs:37)
[p#:0, t#:0] mdbg> de
mdbg>

간단하게 명령어 설명을 해보면 "a 11336"은 PID가 11336인 프로세스에 디버거를 attach시키고, "t 0"을 통해 0번 Managed Thread로 문맥 전환을 한 후 "w(here)" 명령어를 이용해 최종적으로 콜스택을 뜨게 됩니다. 마지막으로 "de(ttach)" 명령으로 디버거 연결을 끊게 되는데, 만약 명시적인 de 명령없이 mdbg를 종료시키면 디버거로 연결된 프로세스까지 강제종료되므로 주의해야 합니다.




자, 그럼 이 명령어를 코드에서 그대로 수행해 주면 .NET 2.0/4.0 프로세스의 콜스택을 얻는 것이 가능하겠지요. ^^

MDbg는 소스코드가 공개되어 있으므로 Visual Studio에서 열어보면 다음과 같은데,

managed_thread_call_stack_dump_1.png

이 중에서 라이브러리처럼 사용하는 경우 실제 필요한 것은 corapi, mdbgeng, NativeDebugWrappers, raw 프로젝트입니다. 이들을 참조하는 간단한 콘솔 프로젝트를 만들고 다음과 같이 코딩을 해주면 됩니다.

using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using Microsoft.Samples.Debugging.CorDebug;
using Microsoft.Samples.Debugging.MdbgEngine;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int pid = 4768;

            ThreadDump(pid);
        }

        private static void ThreadDump(int pid)
        {
            MDbgEngine debugger = new MDbgEngine();

            if (Process.GetCurrentProcess().Id == pid)
            {
                Console.WriteLine("Cannot attach to myself!");
                return;
            }

            // Can't attach to a process that we're already debugging.
            foreach (MDbgProcess procOther in debugger.Processes)
            {
                if (pid == procOther.CorProcess.Id)
                {
                    Console.WriteLine("Can't attach to process " + pid + " because it's already being debugged");
                    return;
                }
            }

            string debuggerVersion = CorDebugger.GetDefaultDebuggerVersion();

            // "attach" 명령어 단계
            string version = debuggerVersion;
            if (string.IsNullOrEmpty(version) == true)
            {
                Console.WriteLine("Can't determine .NET Version");
                return;
            }

            MDbgProcess p = null;

            try 
            { 
                p = debugger.Attach(pid, version);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Attach failed: " + ex.ToString());
                return;
            }

            p.Go().WaitOne();

            // "t 0" 명령어 단계
            MDbgThread targetThread = p.Threads[0];
            p.Threads.Active = targetThread;

            // "where" 명령어 단계
            StringBuilder sb = new StringBuilder();

            foreach (MDbgThread t in p.Threads)
            {
                InternalWhereCommand(sb, t, 0, false);
            }

            // InternalWhereCommand(sb, targetThread, 0, false);

            Console.WriteLine(sb.ToString());

            // "dettach" 명령어 단계
            p.Detach();

            if (p.CanExecute() == true)
            {
                p.StopEvent.WaitOne();
            }
        }

        private static void InternalWhereCommand(StringBuilder sb, MDbgThread thread, int depth, bool verboseOutput)
        {
            Debug.Assert(thread != null);
            bool ShowInternalFrames = true;

            sb.AppendLine("Thread [#:" + thread.Id + "]");

            MDbgFrame af = thread.HaveCurrentFrame ? thread.CurrentFrame : null;
            MDbgFrame f = thread.BottomFrame;
            int i = 0;
            while (f != null && (depth == 0 || i < depth))
            {
                string line;
                if (f.IsInfoOnly)
                {
                    if (!ShowInternalFrames)
                    {
                        // in cases when we don't want to show internal frames, we'll skip them
                        f = f.NextUp;
                        continue;
                    }
                    line = string.Format(CultureInfo.InvariantCulture, "    {0}", f.ToString());
                }
                else
                {
                    string frameDescription = f.ToString(verboseOutput ? "v" : null);
                    line = string.Format(CultureInfo.InvariantCulture, "{0}{1}. {2}", f.Equals(af) ? "*" : " ", i, frameDescription);
                    ++i;
                }
                sb.AppendLine(line);
                f = f.NextUp;
            }
            if (f != null && depth != 0) // means we still have some frames to show....
            {
                sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "displayed only first {0} frames. For more frames use -c switch", depth));
            }
        }
    }
}

끝입니다. 더 설명할 것이 없군요. ^^




참고로 다음과 같은 오류가 발생한다면?

Attach failed: System.Runtime.InteropServices.COMException (0x80131C30): The operation failed because debuggee and debugger are on incompatible platforms. (Exception from HRESULT: 0x80131C30)
   at Microsoft.Samples.Debugging.CorDebug.NativeApi.ICorDebug.DebugActiveProcess(UInt32 id, Int32 win32Attach, ICorDebugProcess& ppProcess)
   at Microsoft.Samples.Debugging.CorDebug.CorDebugger.DebugActiveProcess(Int32processId, Boolean win32Attach, CorRemoteTarget target) in d:\...\debugger\corapi\Debugger.cs:line 340
   at Microsoft.Samples.Debugging.MdbgEngine.MDbgProcess.Attach(Int32 processId, SafeWin32Handle attachContinuationEvent, CorRemoteTarget target) in d:\...\debugger\mdbgeng\Process.cs:line 1225
   at Microsoft.Samples.Debugging.MdbgEngine.MDbgProcess.Attach(Int32 processId, SafeWin32Handle attachContinuationEvent) in d:\...\debugger\mdbgeng\Process.cs:line 1183
   at Microsoft.Samples.Debugging.MdbgEngine.MDbgEngine.Attach(Int32 processId, SafeWin32Handle attachContinuationEvent, String version) in d:\...\debugger\mdbgeng\Engine.cs:line 571
   at Microsoft.Samples.Debugging.MdbgEngine.MDbgEngine.Attach(Int32 processId, String version) in d:\...\debugger\mdbgeng\Engine.cs:line 553
   at ConsoleApplication1.Program.ThreadDump(Int32 pid) in d:\...\ConsoleApplication1\Program.cs:line 53

대상 응용 프로그램과 그것에 attach하려는 프로그램의 플랫폼 빌드가 맞지 않아서입니다. 가령 대상 응용 프로그램은 32비트인데, 덤프 뜨는 측은 64비트인 경우 저런 오류가 발생합니다.

재미있는 점이 하나 있다면 대상 응용 프로그램이 64비트이고, 덤프 뜨는 측이 32비트인 경우에는 오류 메시지가 정확하지 않아서 좀 당혹스럽습니다.

System.Runtime.InteropServices.COMException (0x80070032): The request is not supported. (Exception from HRESULT: 0x80070032)

또는 이렇게도 오류가 발생할 수 있습니다.

Unhandled Exception: System.Runtime.InteropServices.COMException: Only part of a ReadProcessMemory or WriteProcessMemory request was completed. (Exception from HRESULT: 0x8007012B)
   at Microsoft.Samples.Debugging.CorDebug.ICLRMetaHost.EnumerateLoadedRuntimes(ProcessSafeHandle hndProcess)
   at Microsoft.Samples.Debugging.CorDebug.CLRMetaHost.EnumerateLoadedRuntimes(Int32 processId) in d:\...\corapi\Debugger.cs:line 747
   at Microsoft.Samples.Debugging.MdbgEngine.MdbgVersionPolicy.GetDefaultAttachVersion(Int32 processId) in d:\...\mdbgeng\Engine.cs:line 370
   at ConsoleApplication1.Program.ThreadDump(Int32 pid) in d:\...\Program.cs:line 44
   at ConsoleApplication1.Program.Main(String[] args) in d:\...\Program.cs:line 20

이어서 다른 예외를 소개하자면, MDbgEngine.Attach시에 "Failed to load the runtime" 오류가 발생할 수 있습니다.

string debuggerVersion = "v4.0.30319.34003";

p = debugger.Attach(pid, debuggerVersion); // "Failed to load the runtime"

System.Runtime.InteropServices.COMException was caught
  HResult=-2146232576
  Message=Failed to load the runtime. (Exception from HRESULT: 0x80131700)
  Source=corapi
  ErrorCode=-2146232576
  StackTrace:
       at Microsoft.Samples.Debugging.CorDebug.ICLRMetaHost.GetRuntime(String pwzVersion, Guid& riid)
       at Microsoft.Samples.Debugging.CorDebug.CLRMetaHost.GetRuntime(String version) in d:\...\corapi\Debugger.cs:line 763
       at Microsoft.Samples.Debugging.CorDebug.CorDebugger.InitFromVersion(String debuggerVersion) in d:\...\corapi\Debugger.cs:line 405
       at Microsoft.Samples.Debugging.CorDebug.CorDebugger..ctor(String debuggerVersion) in d:\...\corapi\Debugger.cs:line 95
       at Microsoft.Samples.Debugging.MdbgEngine.MDbgEngine.Attach(Int32 processId, SafeWin32Handle attachContinuationEvent, String version) in d:\...\mdbgeng\Engine.cs:line 570
       at Microsoft.Samples.Debugging.MdbgEngine.MDbgEngine.Attach(Int32 processId, String version) in d:\...\mdbgeng\Engine.cs:line 553
       at ConsoleApplication1.Program.ThreadDump(Int32 pid) in d:\...\Program.cs:line 61
  InnerException: 

원인이 좀 황당합니다. ^^ 디버거 버전으로 전달되는 문자열은 [major].[minor].[build].[revision]가 있는데요. 여기서 허용되는 버전 길이는 build까지입니다. 따라서 반드시 다음과 같이 전달해야 합니다.

string debuggerVersion = "v4.0.30319";
p = debugger.Attach(pid, debuggerVersion);

이것이 왜 문제가 되냐면 테스트하다 보니 가끔씩 MdbgVersionPolicy.GetDefaultAttachVersion의 결과로 revision 번호가 포함될 때가 있기 때문입니다.

그것 외에, 대상 프로세스의 CLR 버전을 구하는 방법으로 GetDebuggerVersionFromPid 메서드가 제공되는데요. 대상 응용 프로그램이 CLR 2인 경우에는 잘 수행되지만 CLR 4인 경우에는 다음과 같은 오류가 발생합니다.

string debuggerVersion = CorDebugger.GetDebuggerVersionFromPid(pid);

Unhandled Exception: System.ArgumentException: Value does not fall within the expected range.
   at Microsoft.Samples.Debugging.CorDebug.NativeMethods.GetVersionFromProcess(ProcessSafeHandle hProcess, StringBuilder versionString, Int32 bufferSize, Int32& dwLength)
   at Microsoft.Samples.Debugging.CorDebug.CorDebugger.GetDebuggerVersionFromPid(Int32 pid) in d:\...\debugger\corapi\Debugger.cs:line 59
   at ConsoleApplication1.Program.ThreadDump(Int32 pid) in d:\...\Program.cs:line 44
   at ConsoleApplication1.Program.Main(String[] args) in d:\...\Program.cs:line 20

왜냐하면, 이것의 근간이 되는 GetVersionFromProcess Win32 API가 .NET 4.0의 mscoree.dll에서는 deprecated 상태이기 때문입니다. 설령 Win32 API로 직접 호출해도 빈 문자열만 나옵니다.

마지막으로 대상 응용 프로그램이 CLR 2인데, 덤프뜨려는 측에서 v4.0 문자열로 Attach 시키면,

string debuggerVersion = "v4.0.30319";
p = debugger.Attach(pid, debuggerVersion); 

p.Go().WaitOne(); // hang!

Go().WaitOne() 단계에서 블록이 걸립니다. 스레드가 멈추는데요, 따라서 반드시 대상 응용 프로그램의 CLR과 동일한 버전으로 Attach해야 합니다.




정리를 해보면, 결국 덤프를 뜨는 기능을 안정적으로 구현하고 싶다면 반드시 x86/x64에 따른 플랫폼과 .NET 버전을 세심하게 신경쓰셔야 합니다. 그렇지 않으면 각종 오류에 빠져 헤어나지 못할 수 있습니다. ^^

(첨부된 프로젝트는 위의 예제를 실습한 프로젝트입니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 8/21/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2013-11-13 11시46분
[ryujh] 안녕하세요.
위의 오류들을 보니 말씀하신대로 .NET 이 CPU,Windows 를 벗어나서 생각할 수 없다는 것을 더욱 확신하게 되었군요.
COM 컴포넌트와 연동할때 x86/x64 문제로 어쩔 수 없이 COM+ 구성요소에 등록하여 사용하게 됩니다.

그러면 글 내용은 콘솔어플리케이션을 예로 들었는데, 클래스라이브러리에도 위와 같이 콜스택 확인할 수 있는 건지요?
이상입니다.
[guest]
2013-11-14 12시04분
MDbg는 Managed 환경을 위한 디버거입니다. 쉽게 생각해서 Visual Studio의 C# 디버깅 부분을 라이브러리로 만들어 놓은 거라고 보면 됩니다. 그러니 당연히 클래스라이브러리에 포함된 콜스택도 확인할 수 있습니다.

그리고, 사실 .NET이 CPU, Windows의 한계를 갖는다기 보다는 ^^ 디버거는 다소 시스템 레벨이라 예외로 봐야할 것 같습니다.
정성태

... 16  17  18  19  [20]  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13151정성태10/31/20226131C/C++: 161. Windows 11 환경에서 raw socket 테스트하는 방법파일 다운로드1
13150정성태10/30/20226048C/C++: 160. Visual Studio 2022로 빌드한 C++ 프로그램을 위한 다른 PC에서 실행하는 방법
13149정성태10/27/20226036오류 유형: 825. C# - CLR ETW 이벤트 수신이 GCHeapStats_V1/V2에 대해 안 되는 문제파일 다운로드1
13148정성태10/26/20225957오류 유형: 824. msbuild 에러 - error NETSDK1005: Assets file '...\project.assets.json' doesn't have a target for 'net5.0'. Ensure that restore has run and that you have included 'net5.0' in the TargetFramew
13147정성태10/25/20225029오류 유형: 823. Visual Studio 2022 - Unable to attach to CoreCLR. The debugger's protocol is incompatible with the debuggee.
13146정성태10/24/20225879.NET Framework: 2060. C# - Java의 Xmx와 유사한 힙 메모리 최댓값 제어 옵션 HeapHardLimit
13145정성태10/21/20226201오류 유형: 822. db2 - Password validation for user db2inst1 failed with rc = -2146500508
13144정성태10/20/20226084.NET Framework: 2059. ClrMD를 이용해 윈도우 환경의 메모리 덤프로부터 닷넷 모듈을 추출하는 방법파일 다운로드1
13143정성태10/19/20226591오류 유형: 821. windbg/sos - Error code - 0x000021BE
13142정성태10/18/20225924도서: 시작하세요! C# 12 프로그래밍
13141정성태10/17/20227204.NET Framework: 2058. [in,out] 배열을 C#에서 C/C++로 넘기는 방법 - 세 번째 이야기파일 다운로드1
13140정성태10/11/20226552C/C++: 159. C/C++ - 리눅스 환경에서 u16string 문자열을 출력하는 방법 [2]
13139정성태10/9/20226224.NET Framework: 2057. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 모든 닷넷 모듈을 추출하는 방법파일 다운로드1
13138정성태10/8/20227628.NET Framework: 2056. C# - await 비동기 호출을 기대한 메서드가 동기로 호출되었을 때의 부작용 [1]
13137정성태10/8/20225914.NET Framework: 2055. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 닷넷 모듈을 추출하는 방법
13136정성태10/7/20226497.NET Framework: 2054. .NET Core/5+ SDK 설치 없이 dotnet-dump 사용하는 방법
13135정성태10/5/20226778.NET Framework: 2053. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프를 분석하는 방법 - 두 번째 이야기
13134정성태10/4/20225461오류 유형: 820. There is a problem with AMD Radeon RX 5600 XT device. For more information, search for 'graphics device driver error code 31'
13133정성태10/4/20225842Windows: 211. Windows - (commit이 아닌) reserved 메모리 사용량 확인 방법 [1]
13132정성태10/3/20225734스크립트: 42. 파이썬 - latexify-py 패키지 소개 - 함수를 mathjax 식으로 표현
13131정성태10/3/20228564.NET Framework: 2052. C# - Windows Forms의 데이터 바인딩 지원(DataBinding, DataSource) [2]파일 다운로드1
13130정성태9/28/20225429.NET Framework: 2051. .NET Core/5+ - 에러 로깅을 위한 Middleware가 동작하지 않는 경우파일 다운로드1
13129정성태9/27/20225709.NET Framework: 2050. .NET Core를 IIS에서 호스팅하는 경우 .NET Framework CLR이 함께 로드되는 환경
13128정성태9/23/20228402C/C++: 158. Visual C++ - IDL 구문 중 "unsigned long"을 인식하지 못하는 #import파일 다운로드1
13127정성태9/22/20226877Windows: 210. WSL에 systemd 도입
13126정성태9/15/20227477.NET Framework: 2049. C# 11 - 정적 메서드에 대한 delegate 처리 시 cache 적용
... 16  17  18  19  [20]  21  22  23  24  25  26  27  28  29  30  ...