Microsoft MVP성태의 닷넷 이야기
디버깅 기술: 12. Managed Method에 Break Point 걸기 [링크 복사], [링크+제목 복사],
조회: 13565
글쓴 사람
정성태 (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)
13317정성태4/11/20234390오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/20233661오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/20233919Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/20234069개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치
13313정성태4/9/20234085개발 환경 구성: 671. Hyper-V VM에 Turbo C 2.0 설치 [2]
13312정성태4/8/20234172Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)파일 다운로드1
13311정성태4/7/20234621C/C++: 163. Visual Studio 2022 - DirectShow 예제 컴파일(WAV Dest)
13310정성태4/6/20234268C/C++: 162. Visual Studio - /NODEFAULTLIB 옵션 설정 후 수동으로 추가해야 할 library
13309정성태4/5/20234388.NET Framework: 2107. .NET 6+ FileStream의 구조 변화
13308정성태4/4/20234281스크립트: 47. 파이썬의 time.time() 실숫값을 GoLang / C#에서 사용하는 방법
13307정성태4/4/20234054.NET Framework: 2106. C# - .NET Core/5+ 환경의 Windows Forms 응용 프로그램에서 HINSTANCE 구하는 방법
13306정성태4/3/20233920Windows: 243. Win32 - 윈도우(cbWndExtra) 및 윈도우 클래스(cbClsExtra) 저장소 사용 방법
13305정성태4/1/20234301Windows: 242. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (쉬운 버전)파일 다운로드1
13304정성태3/31/20234609VS.NET IDE: 181. Visual Studio - C/C++ 프로젝트에 application manifest 적용하는 방법
13303정성태3/30/20233942Windows: 241. 환경 변수 %PATH%에 DLL을 찾는 규칙
13302정성태3/30/20234557Windows: 240. RDP 환경에서 바뀌는 %TEMP% 디렉터리 경로
13301정성태3/29/20234655Windows: 239. C/C++ - Windows 10 Version 1607부터 지원하는 /DEPENDENTLOADFLAG 옵션파일 다운로드1
13300정성태3/28/20234358Windows: 238. Win32 - Modal UI 창에 올바른 Owner(HWND)를 설정해야 하는 이유
13299정성태3/27/20234101Windows: 237. Win32 - 모든 메시지 루프를 탈출하는 WM_QUIT 메시지
13298정성태3/27/20234076Windows: 236. Win32 - MessageBeep 소리가 안 들린다면?
13297정성태3/26/20234700Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/20234066Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
13295정성태3/24/20234303Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/20234472.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/20234520오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/20234676Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...