Microsoft MVP성태의 닷넷 이야기
디버깅 기술: 12. Managed Method에 Break Point 걸기 [링크 복사], [링크+제목 복사],
조회: 13551
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

Managed Method에 Break Point 걸기


지난번의 내용을 좀 더 이어서 설명해 보겠습니다.

사실, Main 함수에 BP를 거는 것은 그다지 자주 사용할만한 시나리오는 아닙니다. 그저 "호기심"으로 인해 시도를 해본 것에 불과할 뿐, 대부분의 경우는 이미 CLR이 로드되고 Managed 스레드 스택이 있는 상태에서 디버깅이 이뤄지는 것이 보통일 것입니다.

그렇다면 이번에는, "원하는 Managed 메서드의 진입점"에서 실행을 멈추고 인자값을 살펴보는 방법을 설명해 보겠습니다.

0. 예제 코드는 아래와 같고, 실행을 멈추고 싶은 지점은 "ClassLibrary2.Class2.MyMethod2"입니다.

==== ConsoleApplication1.exe =====

using System;
using System.Collections.Generic;
using System.Text;
using ClassLibrary1;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main()
    {
      new Class1().MyMethod("Hello", 5);
    }
  }
}


==== ClassLibrary1.dll =====

using System;
using System.Collections.Generic;
using System.Text;
using ClassLibrary2;

namespace ClassLibrary1
{
  public class Class1
  {
    string str;

    public void MyMethod(string arg, int i)
    {
      str = string.Format("Member Variable{0}.{1}", i, new Class2().MyMethod2());
      Console.WriteLine(str);
    }
  }
}


==== ClassLibrary2.dll =====

using System;
using System.Collections.Generic;
using System.Text;

namespace ClassLibrary2
{
  public class Class2
  {
    public string MyMethod2()
    {
      return "TEST";
    }
  }
}

예제 코드의 호출 구조는 아래와 같이 간단합니다.

 ConsoleApplication1.Program.Main 
    ==> ClassLibrary1.Class1.MyMethod 
        ==> ClassLibrary2.Class2.MyMethod2

그나저나, 처음 실행되는 시점에 BP를 거는 것은 조금 어렵긴 합니다. 왜냐하면, sos에서 제공해 주는 확장 명령어인 "bpmd"를 사용하기 위해서는 해당 메서드를 찾을 수 있어야 하는데, 관련된 IL 코드가 로드되지 않은 상태에서는 그럴 수 없기 때문입니다. 그래도 이것만 할 줄 알면 다른 경우는 쉽게 응용할 수 있기 때문에 살펴볼 가치가 있을 것 같아서 방법을 아래에 정리해 봅니다.




1. "windbg.exe ConsoleApplication1.exe" 실행
2. "sxe ld ClassLibrary2" 실행
일단, "ClassLibrary2"가 로드되는 시점까지 실행시켜 줍니다. 그러니까, 다음과 같은 메시지가 나올 때까지 "g" 명령어로 실행시킵니다.

0:000> sxe ld ClassLibrary2
0:000> g
ModLoad: 79000000 79045000   C:\Windows\system32\mscoree.dll
ModLoad: 76720000 767f8000   C:\Windows\system32\KERNEL32.dll
(1078.16c8): Break instruction exception - code 80000003 (first chance)
eax=00000000 ebx=00000000 ecx=0014f40c edx=77ca0f34 esi=fffffffe edi=77d05d14
eip=77c82ea8 esp=0014f424 ebp=0014f454 iopl=0         nv up ei pl zr na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000246
ntdll!DbgBreakPoint:
77c82ea8 cc              int     3
0:000> g
ModLoad: 77b80000 77c3f000   C:\Windows\system32\ADVAPI32.dll
...[중간 생략]...
ModLoad: 73c10000 73c18000   D:\temp\DumpTest\ConsoleApplication1\bin\Debug\ClassLibrary1.dll
ModLoad: 73b80000 73b88000   ClassLibrary2.dll
eax=00365108 ebx=00390818 ecx=79f15322 edx=77ca0f34 esi=76768be3 edi=003907e0
eip=77ca0f34 esp=0014c09c ebp=0014c0d4 iopl=0         nv up ei pl nz na po nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202
ntdll!KiFastSystemCallRet:
77ca0f34 c3              ret

3. "x mscorwks!AppDomain::LoadDomainAssembly" 실행
LoadLibrary가 호출된 시점은 사실 managed 관련 처리가 안된 상태인 듯합니다. 이 때문에 "sxe ld"로 인한 "ClassLibrary2" 로드 시점에는 "!bpmd ClassLibrary2 ClassLibrary2.Class2.MyMethod2" 메서드가 효과가 없습니다. 그렇다면 그 명령어가 유효한 시점을 찾아야 할 텐데요. 제가 호출 스택을 검사해 본 바로는 AppDomain::LoadDomainAssembly가 가장 적당한 듯 했습니다. (물론, 이것은 향후의 .NET 버전에서는 바뀔 수 있다는 것을 염두에 두어야 합니다.) 그래서, 다음과 같이 "!bpmd ClassLibrary2 ClassLibrary2.Class2.MyMethod2"가 유효할 때까지 반복해서 "g" 명령을 실행했습니다. 사실 이런 경우는 일단 감으로 정한 것이고 LoadDomainAssembly 호출 횟수를 가능한 줄이기 위해 "sxe ld ClassLibrary2"를 해준 것에 불과하겠지요.

0:000> x mscorwks!AppDomain::LoadDomainAssembly
79eb1438 mscorwks!AppDomain::LoadDomainAssembly = <no type information>
0:000> bp 79eb1438 
0:000> g
ModLoad: 01180000 01188000   ClassLibrary2.dll
eax=003e5108 ebx=000001b4 ecx=79f15322 edx=77ca0f34 esi=76768be3 edi=00410610
eip=77ca0f34 esp=0028c06c ebp=0028c0a4 iopl=0         nv up ei pl nz na po nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202
ntdll!KiFastSystemCallRet:
77ca0f34 c3              ret
0:000> g
Breakpoint 0 hit
eax=003b0250 ebx=00000000 ecx=003b0250 edx=0040f0e1 esi=003630d8 edi=00000000
eip=79eb1438 esp=0028d8c0 ebp=0028d96c iopl=0         nv up ei pl nz na po nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202
mscorwks!AppDomain::LoadDomainAssembly:
79eb1438 6a54            push    54h
0:000> !bpmd ClassLibrary2 ClassLibrary2.Class2.MyMethod2
Adding pending breakpoints... // 못 찾았지만 이 시점에서는 MyMethod는 찾을 수 있음.
0:000> g
ModLoad: 73c10000 73c18000   D:\temp\DumpTest\ConsoleApplication1\bin\Debug\ClassLibrary2.dll
eax=73c10080 ebx=00000000 ecx=45e4c9b6 edx=00000000 esi=7ffdf000 edi=20000000
eip=77ca0f34 esp=0028ce8c ebp=0028ced0 iopl=0         nv up ei pl zr na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000246
ntdll!KiFastSystemCallRet:
77ca0f34 c3              ret
0:000> g
Breakpoint 0 hit
eax=003b0250 ebx=00000000 ecx=003b0250 edx=0040f4d1 esi=0036359c edi=00000000
eip=79eb1438 esp=0028c924 ebp=0028c9d0 iopl=0         nv up ei pl nz na po nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202
mscorwks!AppDomain::LoadDomainAssembly:
79eb1438 6a54            push    54h
0:000> !bpmd ClassLibrary2 ClassLibrary2.Class2.MyMethod2
Found 1 methods... // 찾았음
Adding pending breakpoints...  

4. 호출 스택 확인
위에서 이미 "!bpmd ClassLibrary2 ClassLibrary2.Class2.MyMethod2" 명령어를 내렸기 때문에 BP 설정이 된 상태입니다. 따라서 "g" 명령어를 내려서 "MyMethod2"까지 실행을 합니다. 그리곤 "!clrstack -a" 명령을 내리면 모든 호출 스택을 볼 수 있습니다.

0:000> g
(524.10c0): CLR notification exception - code e0444143 (first chance)
JITTED ClassLibrary2!ClassLibrary2.Class2.MyMethod2()
Setting breakpoint: bp 00AB01C0 [ClassLibrary2.Class2.MyMethod2()]
Breakpoint 1 hit
eax=00363960 ebx=013e1b08 ecx=013e1b54 edx=013e1b6c esi=013e1b60 edi=013e1b54
eip=00ab01c0 esp=0028ed14 ebp=013e1b14 iopl=0         nv up ei pl nz ac po nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000212
00ab01c0 56              push    esi
0:000> !clrstack -a
OS Thread Id: 0x10c0 (0)
ESP       EIP     
0028ed14 00ab01c0 ClassLibrary2.Class2.MyMethod2()
    PARAMETERS:
        this = 0x013e1b54
    LOCALS:
        <no data>

0028ed18 00ab0150 ClassLibrary1.Class1.MyMethod(System.String, Int32)
    PARAMETERS:
        this = 0x013e1b08
        arg = 0x013e1aec
        i = 0x00000005

0028ed3c 00ab00ab ConsoleApplication1.Program.Main()
    LOCALS:
        <CLR reg> = 0x013e1b08

0028ef58 79e8273b [GCFrame: 0028ef58] 

5. 인자값 확인
자, 이제 마무리군요. 위에서 호출스택을 보면서 각각의 함수 인자값에 대한 정보도 함께 보여주는 것을 확인할 수 있습니다. 일단, MyMethod2 함수는 인자가 없으니 생략하고. MyMethod의 경우에는 2개의 인자를 가지고 있으니 그걸 살펴보도록 하겠습니다.

0028ed18 00ab0150 ClassLibrary1.Class1.MyMethod(System.String, Int32)
    PARAMETERS:
        this = 0x013e1b08
        arg = 0x013e1aec
        i = 0x00000005 

훌륭합니다. ^^ Reflection이 되는 Managed 환경이기 때문에 인자의 이름까지도 소스 코드와 일치하게 나옵니다. 게다가 arg 값은 String 형이고, i 값은 Int32라는 것도 알 수 있습니다. "Value" 형인 "i" 값은 그대로 나오는 반면 "참조" 형인 arg 값은 주솟값으로 대신하고 있습니다. 음... 이미 이 부분들은 예전에 "VS.NET 2005를 이용한 미니덤프 파일 분석 (1), (2)" 에서 설명해드렸는데요.

아래는 arg 값에 대한 덤프를 한 결과입니다. 보시는 것처럼, "arg"의 인자값이 "Hello"임을 알 수 있습니다.

0:000> !dumpobj 0x013f1aec
Name: System.String
MethodTable: 790fc6cc
EEClass: 790fc62c
Size: 28(0x1c) bytes
 (C:\Windows\assembly\GAC_32\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll)
String: Hello
Fields:
      MT    Field   Offset                 Type VT     Attr    Value Name
790ff7f0  4000096        4         System.Int32  0 instance        6 m_arrayLength
790ff7f0  4000097        8         System.Int32  0 instance        5 m_stringLength
790fe2dc  4000098        c          System.Char  0 instance       48 m_firstChar
790fc6cc  4000099       10        System.String  0   shared   static Empty
    >> Domain:Value  00060250:790d7eb4 <<
7913cb00  400009a       14        System.Char[]  0   shared   static WhitespaceChars
    >> Domain:Value  00060250:013f16a0 <<



그나저나...? !bpmd 메서드가 유효한 시점까지 실행이 되어지는 좋은 방법이 없을까요? "sxe ld"도 그다지 마음에 들진 않지요! 좋은 의견 있으시면 댓글 부탁드리겠습니다. ^^



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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/23/2021]

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

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13610정성태4/28/2024207닷넷: 2251. C# - 제네릭 인자를 가진 타입을 생성하는 방법 - 두 번째 이야기
13609정성태4/27/2024232닷넷: 2250. PInvoke 호출 시 참조 타입(class)을 마샬링하는 [IN], [OUT] 특성파일 다운로드1
13608정성태4/26/2024426닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/2024474닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/2024635닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024779닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024820오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024952닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024964닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024991닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/20241015닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024950닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024994닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024988닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241102닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241072닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241093닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241094닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241230C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241207닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241086Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241164닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241535닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241397오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241606Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...