Microsoft MVP성태의 닷넷 이야기
디버깅 기술: 12. Managed Method에 Break Point 걸기 [링크 복사], [링크+제목 복사],
조회: 18262
글쓴 사람
정성태 (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)
13768정성태10/15/20245397C/C++: 179. C++ - _O_WTEXT, _O_U16TEXT, _O_U8TEXT의 Unicode stream 모드파일 다운로드2
13767정성태10/14/20244774오류 유형: 929. bpftrace 수행 시 "ERROR: Could not resolve symbol: /proc/self/exe:BEGIN_trigger"
13766정성태10/14/20244555C/C++: 178. C++ - 파일에 대한 Text 모드의 "translated" 동작파일 다운로드1
13765정성태10/12/20245267오류 유형: 928. go build 시 "package maps is not in GOROOT" 오류
13764정성태10/11/20245632Linux: 85. Ubuntu - 원하는 golang 버전 설치
13763정성태10/11/20244988Linux: 84. WSL / Ubuntu 20.04 - bpftool 설치
13762정성태10/11/20245010Linux: 83. WSL / Ubuntu 22.04 - bpftool 설치
13761정성태10/11/20244917오류 유형: 927. WSL / Ubuntu - /usr/include/linux/types.h:5:10: fatal error: 'asm/types.h' file not found
13760정성태10/11/20245452Linux: 82. Ubuntu - clang 최신(stable) 버전 설치
13759정성태10/10/20246367C/C++: 177. C++ - 자유 함수(free function) 및 주소 지정 가능한 함수(addressable function) [6]
13758정성태10/8/20245579오류 유형: 926. dotnet tools를 sudo로 실행하는 경우 command not found
13757정성태10/8/20245523닷넷: 2306. Linux - dotnet tool의 설치 디렉터리가 PATH 환경변수에 자동 등록이 되는 이유
13756정성태10/8/20245630오류 유형: 925. ssh로 docker 접근을 할 때 "... malformed HTTP status code ..." 오류 발생
13755정성태10/7/20246029닷넷: 2305. C# 13 - (9) 메서드 바인딩의 우선순위를 지정하는 OverloadResolutionPriority 특성 도입 (Overload resolution priority)파일 다운로드1
13754정성태10/4/20245579닷넷: 2304. C# 13 - (8) 부분 메서드 정의를 속성 및 인덱서에도 확대파일 다운로드1
13753정성태10/4/20245596Linux: 81. Linux - PATH 환경변수의 적용 규칙
13752정성태10/2/20246282닷넷: 2303. C# 13 - (7) ref struct의 interface 상속 및 제네릭 제약으로 사용 가능 [6]파일 다운로드1
13751정성태10/2/20245410C/C++: 176. C/C++ - ARM64로 포팅할 때 유의할 점
13750정성태10/1/20245294C/C++: 175. C++ - WinMain/wWinMain 호출 전의 CRT 초기화 단계
13749정성태9/30/20245537닷넷: 2302. C# - ssh-keygen으로 생성한 Private Key와 Public Key 연동파일 다운로드1
13748정성태9/29/20245744닷넷: 2301. C# - BigInteger 타입이 byte 배열로 직렬화하는 방식
13747정성태9/28/20245597닷넷: 2300. C# - OpenSSH의 공개키 파일에 대한 "BEGIN OPENSSH PUBLIC KEY" / "END OPENSSH PUBLIC KEY" PEM 포맷파일 다운로드1
13746정성태9/28/20245691오류 유형: 924. Python - LocalProtocolError("Illegal header value ...")
13745정성태9/28/20245552Linux: 80. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (lldb)
13744정성태9/27/20245983닷넷: 2299. C# - Windows Hello 사용자 인증 다이얼로그 표시하기파일 다운로드1
13743정성태9/26/20246430닷넷: 2298. C# - Console 프로젝트에서의 await 대상으로 Main 스레드 활용하는 방법 [1]
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...