Microsoft MVP성태의 닷넷 이야기
디버깅 기술: 70. windbg + 닷넷 디버깅 (1) - 배열 인덱스 사용 패턴 [링크 복사], [링크+제목 복사],
조회: 14448
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

windbg + 닷넷 디버깅 (1) - 배열 인덱스 사용 패턴

모듈명 지정은 대체로 확장자를 빼도 잘 됩니다.

0:021> !lmi TestApp
Loaded Module Info: [TestApp] 
         Module: TestApp
   Base Address: 6ded0000
     Image Name: C:\Windows\assembly\GAC_MSIL\TestApp\5.0.5.0__cc862a9be44088eb\TestApp.dll
   Machine Type: 332 (I386)
     Time Stamp: 54ec24dc Tue Feb 24 16:14:36 2015
           Size: 102000
       CheckSum: fe709
Characteristics: 2102  
Debug Data Dirs: Type  Size     VA  Pointer
             CODEVIEW   11c, fc290,   fb290 RSDS - GUID: {D7414896-35BC-40B9-9897-C786B3457959}
               Age: 1, Pdb: d:\TestApp\obj\Release\TestApp.pdb
    Symbol Type: DEFERRED - No error - symbol load deferred
    Load Report: no symbols loaded

실제로 lm 명령을 내려도 모듈 명으로 확장자가 누락되어 있기도 한데요.

0:021> lm
start    end        module name
6bba0000 6bffa000   mscorlib   (pdb symbols)          d:\symbols\mscorlib.pdb\F9DA4689335E4020947985CC71F44A541\mscorlib.pdb
6ded0000 6dfd2000   TestApp   (no symbols)           
...
77020000 770e6000   ADVAPI32   (pdb symbols)          d:\symbols\advapi32.pdb\66A66DBC8B0E4D88B54A47510DD8039B2\advapi32.pdb
77280000 773a8000   ntdll      (pdb symbols)          d:\symbols\ntdll.pdb\78B918DA4A614679A2053B1FB82EEE652\ntdll.pdb

그런데 위의 목록에 보면 TestApp 모듈이 pdb 로딩이 안되어 있어서 다음과 같이 명시적인 reload를 모듈명만 전달해 실행했더니 로드를 하지 못합니다.

0:021> .reload TestApp

"TestApp" was not found in the image list.
Debugger will attempt to load "TestApp" at given base 00000000.

Please provide the full image name, including the extension (i.e. kernel32.dll)
for more reliable results.Base address and size overrides can be given as
.reload <image.ext>=<base>,<size>.
DBGENG:  TestApp - Partial symbol image load missing image info
DBGHELP: No header for TestApp.  Searching for dbg file
DBGHELP: .\TestApp.dbg - file not found
DBGHELP: TestApp missing debug info.  Searching for pdb anyway
DBGHELP: Can't use symbol server for TestApp.pdb - no header information available
DBGHELP: TestApp.pdb - file not found
DBGHELP: TestApp - no symbols loaded
Unable to add module at 00000000'

헷갈리게도 /f /v 옵션을 붙이면 'unmatched'라는 결과값을 보여줍니다.

0:021> .reload /f /v TestApp

"TestApp" was not found in the image list.
Debugger will attempt to load "TestApp" at given base 00000000.

Please provide the full image name, including the extension (i.e. kernel32.dll)
for more reliable results.Base address and size overrides can be given as
.reload <image.ext>=<base>,<size>.
DBGENG:  TestApp - Partial symbol image load missing image info
DBGHELP: No header for jennifer5.  Searching for dbg file
DBGHELP: d:\TestApp\bin\TestApp.dbg - file not found
DBGHELP: .\TestApp.dbg - file not found
DBGHELP: TestApp missing debug info.  Searching for pdb anyway
DBGHELP: Can't use symbol server for TestApp.pdb - no header information available
DBGHELP: TestApp_0 - private symbols & lines 
         d:\TestApp\bin\TestApp.pdb - unmatched
Unable to add module at 00000000'

물론, chkmatch.exe로 확인해 보면 둘다 일치하다고 나옵니다.

D:\TestApp\bin>ChkMatch.exe -c C:\Windows\assembly\GAC_MSIL\TestApp\5.0.5.0__cc862a9be44088eb\TestApp.dll  D:\TestApp\bin\TestApp.pdb
ChkMatch - version 1.0
Copyright (C) 2004 Oleg Starodumov
http://www.debuginfo.com/


Executable: C:\Windows\assembly\GAC_MSIL\TestApp\5.0.5.0__cc862a9be44088eb\TestApp.dll
Debug info file: TestApp.pdb

Executable:
TimeDateStamp: 54ec24dc
Debug info: 2 ( CodeView )
TimeStamp: 54ec24dc  Characteristics: 0  MajorVer: 0  MinorVer: 0
Size: 284  RVA: 000fc290  FileOffset: 000fb290
CodeView format: RSDS
Signature: {d7414896-35bc-40b9-9897-c786b3457959}  Age: 1
PdbFile: d:\TestApp\obj\Release\TestApp.pdb


Debug information file:
Format: PDB 7.00
Signature: {d7414896-35bc-40b9-9897-c786b3457959}  Age: 1

Result: Matched

.reload 명령으로 pdb를 로드할 때는 (에러메시지에서도 나오지만) "full image name", 즉 확장자를 포함한 이름을 줘야 합니다. 그럼, 이렇게 잘 로드가 됩니다. ^^

0:021> .reload /f /v TestApp.dll
AddImage: C:\Windows\assembly\GAC_MSIL\jennifer5\5.0.5.0__cc862a9be44088eb\TestApp.dll
 DllBase  = 6ded0000
 Size     = 00102000
 Checksum = 000fe709
 TimeDateStamp = 54ec24dc
SYMSRV:  d:\symbols\TestApp.pdb\D741489635BC40B99897C786B34579591\TestApp.pdb not found
SYMSRV:  http://msdl.microsoft.com/download/symbols/TestApp.pdb/D741489635BC40B99897C786B34579591/TestApp.pdb not found
DBGHELP: TestApp - private symbols & lines 
         d:\TestApp\bin\TestApp.pdb




어셈블리의 cdq 명령어는,

...[생략]...
04ce0844 99              cdq
04ce0845 f7f9            idiv    eax,ecx

대부분 idiv와 쌍을 이룬다고 보시면 됩니다. 나눗셈 명령어는 나누는 수(divisor)가 32비트인 경우 피젯수(dividend)는 64비트가 되는 식으로 2배의 피젯수가 사용되는데요. cdq는 eax 레지스터의 내용을 부호를 고려해 edx 레지스터로 확장해 주는 역할을 합니다. 즉, 32비트의 값을 64비트로 확장해 주는 것입니다. 이 때문에 자연스럽게 idiv 명령어가 요구하는 64비트 피젯수가 마련됩니다.

CDQ - Convert Double to Quad
; http://faydoc.tripod.com/cpu/cdq.htm

위의 매뉴얼에 보면, 코드가 99로 동일한 CWD 명령어도 나오는데요. 아마도 이것은 16비트 시절에 사용된 명령어가 아닌가 생각됩니다.

그렇다면 64비트에서는 128비트로 확장해 주는 명령어가 필요하다는 것을 유추할 수 있는데요. 찾아보니 cqo 명령어가 그것입니다.

x64 Instructions
; https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/x64-instructions

rax 레지스터의 내용을 부호 비트를 고려해 rdx:rax로 확장해 주는데 명령어 코드도 역시 99입니다.

참고로, 1바이트의 내용을 2바이트로 확장해 주는 명령어로 cbw가 있는데... 예외적으로 이것은 명령어 코드가 98입니다.




닷넷 프로그램에서 배열 인덱스를 사용하는 경우,

int [] array = new int [4];
int n = 3;

int result = array[n];

닷넷은 관리코드로써 n의 값이 array.Length를 벗어나지 않음을 체크하기 때문에 이런 경우 다음과 같이 JIT_RngChkFail 메서드 호출이 JIT 컴파일 이후에 나타나게 됩니다.

04ce084a 8b45d8          mov     eax,3     // 배열 인덱스로 지정된 값
04ce084d 8b55c0          mov     edx,4     // 실제로는 Array타입의 Length값을 구해서 들어감.
04ce0850 3b4204          cmp     eax, edx  // cmp 명령어는 sub처럼 동작하지만 결과값을 저장하지는 않고 FLAG 레지스터만 변경
                                           // 결국, eax의 값에서 edx값을 빼기
                                           // 만약 이 값이 음수가 되면 CF=1을 설정
                                           // 간단히 말해서,
                                           // 배열 인덱스 값(eax)이 edx보다 작으면 CF=1 설정
                                           // 배열 인덱스 값(eax)이 edx보다 같거나 크면 CF=0 설정
04ce0853 7205            jb      04ce085a  // jb 명령어는 CF=1인 경우, 지정된 주소를 EIP 레지스터로 로드
                                           // 따라서, 배열 인덱스 값이 Array.Length보다 작으면 점프하게 되고,
                                           //                                         같거나 크면 바로 다음 구문을 실행
04ce0855 e86a1cd863      call    mscorwks!JIT_RngChkFail (68a624c4) // 이것이 바로 System.IndexOutOfRangeException 예외를 발생.

04ce085a 8b44820c        mov     eax,dword ptr [edx+eax*4+0Ch]

배열 인덱스가 사용되면 거의 저 패턴으로 기계어 코드가 나타난다고 보면 됩니다.




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







[최초 등록일: ]
[최종 수정일: 7/17/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)
13439정성태11/10/20233095닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232668닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232850닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20233105닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20233003닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232779스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232470스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232551오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232930스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232761닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20233052닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233147닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233335닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233480스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233253닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233233스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233379닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233474닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235776스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233285스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233998닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233526닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233299오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233802닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233578디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233775닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...