Microsoft MVP성태의 닷넷 이야기
디버깅 기술: 12. Managed Method에 Break Point 걸기 [링크 복사], [링크+제목 복사],
조회: 13566
글쓴 사람
정성태 (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)
13521정성태1/11/20242399닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20242180오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20242220닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242483닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242295스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242404닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242722닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242383개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242308닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242257개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242261닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20242180닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20242251오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242309오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242981닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232560닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20233129닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232696닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232584Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232639닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232403개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232524디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20233190닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232594오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232693Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232627Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...