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

비밀번호

댓글 작성자
 




... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12116정성태1/15/202011278디버깅 기술: 158. Visual Studio로 디버깅 시 sos.dll 확장 명령어를 (비롯한 windbg의 다양한 기능을) 수행하는 방법
12115정성태1/14/202011044디버깅 기술: 157. C# - PEB.ProcessHeap을 이용해 디버깅 중인지 확인하는 방법파일 다운로드1
12114정성태1/13/202012892디버깅 기술: 156. C# - PDB 파일로부터 심벌(Symbol) 및 타입(Type) 정보 열거 [1]파일 다운로드3
12113정성태1/12/202013524오류 유형: 590. Visual C++ 빌드 오류 - fatal error LNK1104: cannot open file 'atls.lib' [1]
12112정성태1/12/202010073오류 유형: 589. PowerShell - 원격 Invoke-Command 실행 시 "WinRM cannot complete the operation" 오류 발생
12111정성태1/12/202013374디버깅 기술: 155. C# - KernelMemoryIO 드라이버를 이용해 실행 프로그램을 숨기는 방법(DKOM: Direct Kernel Object Modification) [16]파일 다운로드1
12110정성태1/11/202011968디버깅 기술: 154. Patch Guard로 인해 블루 스크린(BSOD)가 발생하는 사례 [5]파일 다운로드1
12109정성태1/10/20209863오류 유형: 588. Driver 프로젝트 빌드 오류 - Inf2Cat error -2: "Inf2Cat, signability test failed."
12108정성태1/10/20209925오류 유형: 587. Kernel Driver 시작 시 127(The specified procedure could not be found.) 오류 메시지 발생
12107정성태1/10/202010866.NET Framework: 877. C# - 프로세스의 모든 핸들을 열람 - 두 번째 이야기
12106정성태1/8/202012243VC++: 136. C++ - OSR Driver Loader와 같은 Legacy 커널 드라이버 설치 프로그램 제작 [1]
12105정성태1/8/202010943디버깅 기술: 153. C# - PEB를 조작해 로드된 DLL을 숨기는 방법
12104정성태1/7/202011614DDK: 9. 커널 메모리를 읽고 쓰는 NT Legacy driver와 C# 클라이언트 프로그램 [4]
12103정성태1/7/202014357DDK: 8. Visual Studio 2019 + WDK Legacy Driver 제작- Hello World 예제 [1]파일 다운로드2
12102정성태1/6/202011945디버깅 기술: 152. User 권한(Ring 3)의 프로그램에서 _ETHREAD 주소(및 커널 메모리를 읽을 수 있다면 _EPROCESS 주소) 구하는 방법
12101정성태1/5/202011272.NET Framework: 876. C# - PEB(Process Environment Block)를 통해 로드된 모듈 목록 열람
12100정성태1/3/20209314.NET Framework: 875. .NET 3.5 이하에서 IntPtr.Add 사용
12099정성태1/3/202011629디버깅 기술: 151. Windows 10 - Process Explorer로 확인한 Handle 정보를 windbg에서 조회 [1]
12098정성태1/2/202011205.NET Framework: 874. C# - 커널 구조체의 Offset 값을 하드 코딩하지 않고 사용하는 방법 [3]
12097정성태1/2/20209765디버깅 기술: 150. windbg - Wow64, x86, x64에서의 커널 구조체(예: TEB) 구조체 확인
12096정성태12/30/201911724디버깅 기술: 149. C# - DbgEng.dll을 이용한 간단한 디버거 제작 [1]
12095정성태12/27/201913151VC++: 135. C++ - string_view의 동작 방식
12094정성태12/26/201911327.NET Framework: 873. C# - 코드를 통해 PDB 심벌 파일 다운로드 방법
12093정성태12/26/201911356.NET Framework: 872. C# - 로딩된 Native DLL의 export 함수 목록 출력파일 다운로드1
12092정성태12/25/201910796디버깅 기술: 148. cdb.exe를 이용해 (ntdll.dll 등에 정의된) 커널 구조체 출력하는 방법
12091정성태12/25/201912317디버깅 기술: 147. pdb 파일을 다운로드하기 위한 symchk.exe 실행에 필요한 최소 파일 [1]
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...