Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

windbg - x64 환경에서 닷넷 예외가 발생한 경우 인자를 확인할 수 없었던 사례

지난번에는 (운이 좋게) 메서드의 인자를 확인했던 사례를,

windbg - x64 역어셈블 코드에서 닷넷 메서드 호출의 인자를 확인하는 방법
; https://www.sysnet.pe.kr/2/0/11348

설명했지만, 언제나 저렇게 할 수 있는 것은 아닙니다. 이번에는 확인할 수 없었던 사례를 한 번 볼까요? ^^

다음과 같은 예외가 발생했는데,

System.ApplicationException:
   at TestLib.MyType.FindId(Dictionary`2 dict, String idToFind) at D:\TestApp\TestLib\MyType.cs:Line 751
   at TestLib.MyType.ViewBind(Dictionary`2 dict, Int32 port, Site site, String rootPath, TreeNode iisNode) at D:\TestApp\TestLib\MyType.cs:Line 663
   at TestLib.MyType.PopulateWeb(TreeNode iisNode) at D:\TestApp\TestLib\MyType.cs:Line 523
   at TestLib.MainForm.Refresh_Clicked(Object sender, EventArgs arg) at D:\TestApp\TestLib\MainForm.cs:Line 915
   at TestLib.MainForm.OnLoad(EventArgs e) at D:\TestApp\TestLib\MainForm.cs:Line 192
   at System.Windows.Forms.Form.OnCreateControl()
   at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   at System.Windows.Forms.Control.CreateControl()
   at System.Windows.Forms.Control.WmShowWindow(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.Form.WmShowWindow(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

"idToFind"에 들어온 문자열을 확인하고 싶어졌습니다. (물론, 재빠르게 빌드해서 idToFind 문자열을 출력하는 것을 만들어 배포해 다시 실행해 보는 것이 가장 좋습니다. ^^) 일단 이 예외 메시지가 떴을 때 윈도우 덤프를 받았는데요. 이전에도 언급했지만, 행운이 따라준다면 dso 명령어만으로 호출 스택에서 해당 문자열을 확인할 수 있습니다.

0:000> !dso
OS Thread Id: 0x2d1c (0)
RSP/REG          Object           Name
rbx              0000000002b491a8 System.Windows.Forms.Application+ThreadContext
r14              0000000002c35858 System.Windows.Forms.NativeMethods+MSG[]
r15              0000000002b491a8 System.Windows.Forms.Application+ThreadContext
0000000000D7BCA0 0000000002b491a8 System.Windows.Forms.Application+ThreadContext
0000000000D7BD08 0000000002b491a8 System.Windows.Forms.Application+ThreadContext
...[생략]...
0000000000D7EE80 0000000002ba4420 System.Windows.Forms.ApplicationContext
0000000000D7EEA0 0000000002b491a8 System.Windows.Forms.Application+ThreadContext
0000000000D7EEA8 0000000002ba4420 System.Windows.Forms.ApplicationContext
0000000000D7EEC0 0000000002b491a8 System.Windows.Forms.Application+ThreadContext
0000000000D7EED0 0000000002ba4420 System.Windows.Forms.ApplicationContext
0000000000D7EF00 0000000002b45f18 TestLib.MainForm
0000000000D7EF20 0000000002b491a8 System.Windows.Forms.Application+ThreadContext
0000000000D7EF30 0000000002ba4420 System.Windows.Forms.ApplicationContext
0000000000D7F130 0000000002a62bf0 System.Security.Policy.AssemblyEvidenceFactory
0000000000D7F868 0000000002a61440 System.SharedStatics

하지만 이번 덤프에서는 문자열이 없었습니다. 그 말인즉, idToFind 인자가 내부에서 rcx, rdx, r8, r9 레지스터로만 전달되고 스택에 백업된 적이 없다는 것을 의미합니다. 자, 이런 경우라면 어쩔 수 없이 좀 더 요행을 바라야 합니다. 그러려면 우선 해당 메서드의 실행 상태를 분석해야 하는데 clrstack으로 IP를 찾아야 합니다.

0:000> !clrstack
OS Thread Id: 0x2d1c (0)
        Child SP               IP Call Site
...[생략]...
0000000000d7bf40 00007ff92eb36bed System.Windows.Forms.Form.ShowDialog(System.Windows.Forms.IWin32Window)
0000000000d7c040 00007ff92eb072e3 System.Windows.Forms.Application+ThreadContext.OnThreadException(System.Exception)
0000000000d7c0b0 00007ff92eb1493a System.Windows.Forms.Control.WndProcException(System.Exception)
0000000000d7c0e0 00007ff92e42a433 System.Windows.Forms.NativeWindow.Callback(IntPtr, Int32, IntPtr, IntPtr)
0000000000d7e218 00007ff949edfc5d [HelperMethodFrame: 0000000000d7e218] 
0000000000d7e300 00007ff8ea7ac030 TestLib.MyType.FindId(System.Collections.Generic.Dictionary`2, System.String)
0000000000d7e390 00007ff8ea7aaef3 TestLib.MyType.ViewBind(System.Collections.Generic.Dictionary`2, Int32, Microsoft.Web.Administration.Site, System.String, System.Windows.Forms.TreeNode)
...[생략]...
0000000000d7eec0 00007ff92e43e9ff System.Windows.Forms.Application+ThreadContext.RunMessageLoop(Int32, System.Windows.Forms.ApplicationContext)
0000000000d7ef20 00007ff8ea7a05ed TestLib.Program.Main()
0000000000d7f1b0 00007ff949d96d93 [GCFrame: 0000000000d7f1b0]

TestLib.MyType.FindId를 역어셈블하니,

0:000> !U /d 00007ff8ea7ac030
Normal JIT generated code
TestLib.MyType.FindId(System.Collections.Generic.Dictionary`2<System.String,System.Windows.Forms.TreeNode>, System.String)
Begin 00007ff8ea7abef0, size 141
00007ff8`ea7abef0 57              push    rdi
00007ff8`ea7abef1 56              push    rsi
00007ff8`ea7abef2 4883ec78        sub     rsp,78h
00007ff8`ea7abef6 488bf1          mov     rsi,rcx
00007ff8`ea7abef9 488d7c2428      lea     rdi,[rsp+28h]
00007ff8`ea7abefe b914000000      mov     ecx,14h
00007ff8`ea7abf03 33c0            xor     eax,eax
00007ff8`ea7abf05 f3ab            rep stos dword ptr [rdi]
00007ff8`ea7abf07 488bce          mov     rcx,rsi
00007ff8`ea7abf0a 488bfa          mov     rdi,rdx
00007ff8`ea7abf0d 498bf0          mov     rsi,r8
00007ff8`ea7abf10 8b0f            mov     ecx,dword ptr [rdi]
00007ff8`ea7abf12 488bcf          mov     rcx,rdi
00007ff8`ea7abf15 488bd6          mov     rdx,rsi
00007ff8`ea7abf18 e8d3ac425e      call    mscorlib_ni!System.Collections.Generic.Dictionary`2[System.__Canon,System.__Canon].FindEntry(System.__Canon)$##600391F (00007ff9`48bd6bf0)
...[생략]...
00007ff8`ea7ac02b e8204d735f      call    clr!IL_Throw (00007ff9`49ee0d50)
>>> 00007ff8`ea7ac030 cc              int     3

FindEntry로 넘겨진 idToFind 인자는 (this를 포함해) 2번째이므로 rdx로 전달하고 있습니다. rdx의 값은 rsi에서 왔고 rsi는 다시 r8에서 왔으므로 결국 TestLib.MyType.FindId 메서드의 3번째 인자로 넘겨진 값이 (스택이 아닌) 레지스터들 사이에서만 이동하고 있으므로 일단 이 메서드에서는 값을 확인할 길이 없습니다. (왜냐하면, 예외 메시지가 발생한 상황에서는 이미 rdx, r8 레지스터에 다른 값이 들어있기 때문입니다.)

따라서 이번 메서드는 포기하고, 이제 TestLib.MyType.FindId를 호출한 측 메서드로 넘어갑니다.

0:000> !U /d 00007ff8ea7aaef3
Normal JIT generated code
TestLib.MyType.ViewBind(System.Collections.Generic.Dictionary`2<System.String,System.Windows.Forms.TreeNode>, Int32, Microsoft.Web.Administration.Site, System.String, System.Windows.Forms.TreeNode)
Begin 00007ff8ea7aab50, size 88d
00007ff8`ea7aab50 55              push    rbp
00007ff8`ea7aab51 4157            push    r15
00007ff8`ea7aab53 4156            push    r14
00007ff8`ea7aab55 4154            push    r12
00007ff8`ea7aab57 57              push    rdi
00007ff8`ea7aab58 56              push    rsi
00007ff8`ea7aab59 53              push    rbx
00007ff8`ea7aab5a 4881ec00010000  sub     rsp,100h
00007ff8`ea7aab61 488dac2430010000 lea     rbp,[rsp+130h]
00007ff8`ea7aab69 488bf1          mov     rsi,rcx
00007ff8`ea7aab6c 488dbd28ffffff  lea     rdi,[rbp-0D8h]
00007ff8`ea7aab73 b92a000000      mov     ecx,2Ah
00007ff8`ea7aab78 33c0            xor     eax,eax
00007ff8`ea7aab7a f3ab            rep stos dword ptr [rdi]
00007ff8`ea7aab7c 488bce          mov     rcx,rsi
00007ff8`ea7aab7f 4889a510ffffff  mov     qword ptr [rbp-0F0h],rsp
00007ff8`ea7aab86 48895518        mov     qword ptr [rbp+18h],rdx
00007ff8`ea7aab8a 44894520        mov     dword ptr [rbp+20h],r8d
00007ff8`ea7aab8e 488bf9          mov     rdi,rcx
00007ff8`ea7aab91 498bf1          mov     rsi,r9
00007ff8`ea7aab94 48b930cf83eaf87f0000 mov rcx,7FF8EA83CF30h (MT: TestLib.ItemEntry)
00007ff8`ea7aab9e e89d795e5f      call    clr!JIT_TrialAllocSFastMP_InlineGetThread (00007ff9`49d92540)
00007ff8`ea7aaba3 488bd8          mov     rbx,rax
00007ff8`ea7aaba6 488b14250836a612 mov     rdx,qword ptr [12A63608h] ("")
...[생략]...
00007ff8`ea7aaede e8bdcdc243      call    System_Windows_Forms_ni!System.Windows.Forms.Application.Run(System.Windows.Forms.Form)$##6000565 <PERF> (System_Windows_Forms_ni+0x207ca0) (00007ff9`2e3d7ca0)
00007ff8`ea7aaee3 4c8b4340        mov     r8,qword ptr [rbx+40h]
00007ff8`ea7aaee7 488bcf          mov     rcx,rdi
00007ff8`ea7aaeea 488b5518        mov     rdx,qword ptr [rbp+18h]
00007ff8`ea7aaeee e8fd54ffff      call    00007ff8`ea7a03f0 (TestLib.MyType.FindId(System.Collections.Generic.Dictionary`2<System.String,System.Windows.Forms.TreeNode>, System.String), mdToken: 00000000060000cb)
>>> 00007ff8`ea7aaef3 488bc8          mov     rcx,rax
...[생략]...

이번에는, 비록 스택은 아니지만 RBX 레지스터에 기반을 둔 오프셋 연산을 확인할 수 있습니다. TestLib.MyType.FindId의 3번째 인자(r8)에 전달한 값은, JIT_TrialAllocSFastMP_InlineGetThread의 결과로 나온 rax로부터 온 것입니다. 메서드 이름에 AllocSFast가 있다는 것에서 C# 코드의 "new ..."임을 짐작게 하는데, 즉 new로 새롭게 할당받은 객체에 대한 heap 주소를 rax로 반환했는데 그것을 (C# 코드에서는 지역 변수인데도) 스택이 아닌 rbx 레지스터에 보관해 들고 다니고 있습니다.

이로써, 희망이 사라진 것입니다. ^^; CPU의 레지스터가 풍부해진 바람에 스택을 이용하지 않고도 지역 변수를 저렇게 마음대로 처리할 수 있게 되었으니... 이제는 프로그램에서 진단 로그를 남기는 데에 더 신경을 써야 할 시기가 온 것입니다.




참고로, new로 할당받은 객체의 필드(위의 코드에서는 rbx + 40h)에 값을 대입하는 코드를 찾아 다시 그것의 호출 관계를 찾아들어가는 것도 가능합니다. 하지만, 그건 스택을 사용한다 해도 이미 해제될 가능성도 많기 때문에 역시 요행을 바라는 과정일 수밖에 없습니다. 그러니까... 디버깅 입장에서는 x86 시절이 참 좋았습니다. ^^




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







[최초 등록일: ]
[최종 수정일: 7/19/2019]

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

비밀번호

댓글 작성자
 




... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13144정성태10/20/20225695.NET Framework: 2059. ClrMD를 이용해 윈도우 환경의 메모리 덤프로부터 닷넷 모듈을 추출하는 방법파일 다운로드1
13143정성태10/19/20226208오류 유형: 821. windbg/sos - Error code - 0x000021BE
13142정성태10/18/20224891도서: 시작하세요! C# 12 프로그래밍
13141정성태10/17/20226697.NET Framework: 2058. [in,out] 배열을 C#에서 C/C++로 넘기는 방법 - 세 번째 이야기파일 다운로드1
13140정성태10/11/20226045C/C++: 159. C/C++ - 리눅스 환경에서 u16string 문자열을 출력하는 방법 [2]
13139정성태10/9/20225906.NET Framework: 2057. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 모든 닷넷 모듈을 추출하는 방법파일 다운로드1
13138정성태10/8/20227182.NET Framework: 2056. C# - await 비동기 호출을 기대한 메서드가 동기로 호출되었을 때의 부작용 [1]
13137정성태10/8/20225568.NET Framework: 2055. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 닷넷 모듈을 추출하는 방법
13136정성태10/7/20226151.NET Framework: 2054. .NET Core/5+ SDK 설치 없이 dotnet-dump 사용하는 방법
13135정성태10/5/20226382.NET Framework: 2053. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프를 분석하는 방법 - 두 번째 이야기
13134정성태10/4/20225094오류 유형: 820. There is a problem with AMD Radeon RX 5600 XT device. For more information, search for 'graphics device driver error code 31'
13133정성태10/4/20225436Windows: 211. Windows - (commit이 아닌) reserved 메모리 사용량 확인 방법 [1]
13132정성태10/3/20225309스크립트: 42. 파이썬 - latexify-py 패키지 소개 - 함수를 mathjax 식으로 표현
13131정성태10/3/20227954.NET Framework: 2052. C# - Windows Forms의 데이터 바인딩 지원(DataBinding, DataSource) [2]파일 다운로드1
13130정성태9/28/20225086.NET Framework: 2051. .NET Core/5+ - 에러 로깅을 위한 Middleware가 동작하지 않는 경우파일 다운로드1
13129정성태9/27/20225375.NET Framework: 2050. .NET Core를 IIS에서 호스팅하는 경우 .NET Framework CLR이 함께 로드되는 환경
13128정성태9/23/20227946C/C++: 158. Visual C++ - IDL 구문 중 "unsigned long"을 인식하지 못하는 #import파일 다운로드1
13127정성태9/22/20226400Windows: 210. WSL에 systemd 도입
13126정성태9/15/20227008.NET Framework: 2049. C# 11 - 정적 메서드에 대한 delegate 처리 시 cache 적용
13125정성태9/14/20227196.NET Framework: 2048. C# 11 - 구조체 필드의 자동 초기화(auto-default structs)
13124정성태9/13/20226924.NET Framework: 2047. Golang, Python, C#에서의 CRC32 사용
13123정성태9/8/20227379.NET Framework: 2046. C# 11 - 멤버(속성/필드)에 지정할 수 있는 required 예약어 추가
13122정성태8/26/20227393.NET Framework: 2045. C# 11 - 메서드 매개 변수에 대한 nameof 지원
13121정성태8/23/20225379C/C++: 157. Golang - 구조체의 slice 필드를 Reflection을 이용해 변경하는 방법
13120정성태8/19/20226813Windows: 209. Windows NT Service에서 UI를 다루는 방법 [3]
13119정성태8/18/20226385.NET Framework: 2044. .NET Core/5+ 프로젝트에서 참조 DLL이 보관된 공통 디렉터리를 지정하는 방법
... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...