Microsoft MVP성태의 닷넷 이야기
디버깅 기술: 12. Managed Method에 Break Point 걸기 [링크 복사], [링크+제목 복사],
조회: 13590
글쓴 사람
정성태 (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)
13473정성태12/5/20232743닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232416C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232598Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232813닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232671닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232445닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232647오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232794닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232572개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232642닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232512오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232506오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232582닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232587닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232594닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232606닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232534VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232866닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232747닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20233062닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/20232459오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232539닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232668닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232482닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232648개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20232982닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...