Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)

windbg - 힙에서 .NET 타입에 대한 배열을 찾는 방법

.NET 입장에서, 배열은 결국 System.Array를 상속받은 개체로 다뤄집니다. 지난번 이야기에서 "System.Char[]" 개체가 "dumpheap -stat" 명령으로 확인되었던 것을 볼 수 있었는데요.

StringBuilder에서의 OutOfMemoryException 오류 원인 분석
; https://www.sysnet.pe.kr/2/0/1171

Primitive 타입에 대한 배열은 그렇다 치고, 기타 타입들에 대한 배열은 "dumpheap -stat"에서 직접적으로 보이지 않습니다. 이에 대한 이해를 돕기 위해 예제를 다뤄볼까요?

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program[] pgList = new Program[0];
            Thread.Sleep(-1);
        }
    }
}

위와 같은 코드로 작성된 프로그램을 windbg로 로드하고 Thread.Sleep까지 진행 시킨 후, Heap을 살펴보면 다음과 같은 결과를 얻을 수 있습니다.

0:004> .loadby sos clr

0:004>  !dumpheap -stat
total 0 objects
Statistics:
      MT    Count    TotalSize Class Name
72fd5f10        1           12 System.Security.HostSecurityManager
72fd5938        1           12 System.Collections.Generic.ObjectEqualityComparer`1[[System.Type, mscorlib]]
72fd4b44        1           12 System.Security.Permissions.ReflectionPermission
72fd4a60        1           12 System.Security.Permissions.FileDialogPermission
72fd4980        1           12 System.Security.PolicyManager
72fd4898        1           12 System.Security.SecurityDocument
72fd27fc        1           12 System.Collections.Generic.GenericEqualityComparer`1[[System.String, mscorlib]]
72fd5ec8        1           16 System.Security.Policy.Evidence+EvidenceLockHolder
72fd4bf4        1           16 System.Security.Permissions.UIPermission
72fd4640        1           16 System.Security.Util.Parser
... [생략] ...
72fcf92c      469        15652 System.String
72f86ba8       67        19148 System.Object[]
Total 784 objects

예상대로라면, Count == 1, TotalSize == 12 조건을 만족하는 목록 중에서 "ConsoleApplication1.Program[]"인 항목이 나와야 하는데 없는 것입니다. 왜 그럴까요?

아쉽게도 (네, 아쉽습니다.) Primitive 타입을 제외하고는 모든 타입에 대해서 "System.Object[]"로 통털어서 출력이 됩니다. 그래서, 다음과 같이 부가적인 검사를 해야 합니다.

0:004> !dumpheap -mt 72f86ba8       
 Address       MT     Size
027d18e4 72f86ba8       88     
027d5578 72f86ba8       56     
027d55d0 72f86ba8       20     
027d55e4 72f86ba8       32     
027d5604 72f86ba8       20     
... [생략] ...
037d1010 72f86ba8     4096     
037d2020 72f86ba8      528     
037d2240 72f86ba8     4096     
total 0 objects
Statistics:
      MT    Count    TotalSize Class Name
72f86ba8       67        19148 System.Object[]
Total 67 objects

그런데, 과연 67개의 인스턴스 중에서 어떤 것이 Program[]의 개체일까요? (크기를 정확하게 알고 있다면 대상이 좀 더 축소가 되겠지만) 현실적으로는 방법이 없습니다. 67개의 개체 모두 일일이 "!do" 명령어를 내려서 확인해야 합니다. 물론, 위의 경우에는 작은 프로그램이니 그나마 쉽게(?) 찾을 수 있겠지만 대형 프로그램의 경우에는 어림도 없는 작업입니다.

대신 그때그때 상황에 맞게 지름길을 선택하는 정도가 최선일 텐데요. 가령 예를 들어서, 위와 같은 예제 코드에서 pgList 인스턴스가 아직 스택에 존재할 거라는 정보가 있기 때문에 이를 찾아나서면 됩니다.

우선, "~*e!CLRStack" 명령어를 이용해서 pgList를 보유하고 있는 메서드를 어떤 스레드에서 실행하고 있는지 확인해야 하는데,

0:004> ~*e!CLRStack
OS Thread Id: 0x2490 (0)
Child SP IP       Call Site
003af0dc 7762fd81 [HelperMethodFrame: 003af0dc] System.Threading.Thread.SleepInternal(Int32)
003af128 72f03409 System.Threading.Thread.Sleep(Int32)
003af12c 004b00e9 ConsoleApplication1.Program.Main(System.String[]) [D:\...\Program.cs @ 17]
003af398 73b421bb [GCFrame: 003af398] 
OS Thread Id: 0x1dd8 (1)
Unable to walk the managed stack. The current thread is likely not a managed thread. You can run !threads to get a list of managed threads in the process
OS Thread Id: 0x2c2c (2)
Child SP IP       Call Site
00fdfdd8 7763014d [DebuggerU2MCatchHandlerFrame: 00fdfdd8] 
OS Thread Id: 0x312c (3)
Unable to walk the managed stack. The current thread is likely not a managed thread. You can run !threads to get a list of managed threads in the process
OS Thread Id: 0x2ee8 (4)
Unable to walk the managed stack. The current thread is likely not a managed thread. You can run !threads to get a list of managed threads in the process

총 5개의 스레드가 실행되는 중에 우리가 원하는 메서드(Main)를 실행 중인 것은 0번 인덱스의 0x2490 스레드임을 알 수 있습니다. 또한, 현재 windbg의 스레드 문맥은 "0:004>" 프롬프트에서 알려주듯이 4번 인덱스의 스레드이므로 이후의 명령어를 진행하기에 앞서 스레드 전환을 해줍니다.

0:004> ~0s
eax=00000000 ebx=00000001 ecx=00000000 edx=00000000 esi=003aeff8 edi=00000000
eip=7762fd81 esp=003aefb4 ebp=003af01c iopl=0         nv up ei pl zr na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246
ntdll!NtDelayExecution+0x15:
7762fd81 83c404          add     esp,4

위와 같이 "~[스레드 인덱스 번호]s" 명령어 이외에, windbg의 "View" / "Processes and Threads (Alt+9)" 메뉴를 이용하여 GUI 윈도우에서 마우스를 이용하여 전환하는 것도 가능합니다.

how_to_find_type_array_mt_1.png

그다음, 현재 선택된 스레드 문맥에 포함된 stack object들을 모두 나열시키면,

0:000> !dso
OS Thread Id: 0x2490 (0)
ESP/REG  Object   Name
003AF09C 027dbf80 System.Object[]    (System.String[])
003AF12C 027dbf90 System.Object[]    (ConsoleApplication1.Program[])
003AF130 027dbf90 System.Object[]    (ConsoleApplication1.Program[])
003AF134 027dbf90 System.Object[]    (ConsoleApplication1.Program[])
003AF140 027dbf80 System.Object[]    (System.String[])
003AF214 027dbf80 System.Object[]    (System.String[])
003AF3BC 027dbf80 System.Object[]    (System.String[])
003AF3F0 027dbf80 System.Object[]    (System.String[])

Name 필드에 친절하게도 어떤 타입의 배열인지 알려주기 때문에 쉽게 Object 주소를 알 수 있습니다. 이후의 Method Table이나 EEClass를 찾는 것은 목적에 따라 실행해 주시면 되겠고. ^^

0:000> !do 027dbf90 
Name:        System.Object[]
MethodTable: 72f86ba8
EEClass:     72d09688
Size:        20(0x14) bytes
Array:       Rank 1, Number of elements 1, Type CLASS
Element Type:ConsoleApplication1.Program
Fields:
None

0:000> !dumpmt 72f86ba8
EEClass:      72d09688
Module:       72cb1000
Name:         System.Object[]
mdToken:      02000000
File:         C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll
BaseSize:        0x10
ComponentSize:   0x4
Slots in VTable: 28
Number of IFaces in IFaceMap: 6

0:000> !dumpclass 72d09688
Class Name:      System.Object[]
mdToken:         02000000
File:            C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll
Parent Class:    72d08ad8
Module:          72cb1000
Method Table:    72f86ba8
Vtable Slots:    18
Total Method Slots:  1c
Class Attributes:    2101  
Transparency:        Transparent
NumInstanceFields:   0
NumStaticFields:     0




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/10/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)
13278정성태3/8/20234134개발 환경 구성: 669. WSL 2의 (init이 아닌) systemd 지원 [1]
13277정성태3/6/20234761개발 환경 구성: 668. 코드 사인용 인증서 신청 및 적용 방법(예: Digicert)
13276정성태3/5/20234442.NET Framework: 2102. C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어
13275정성태3/3/20234765.NET Framework: 2101. C# 11의 ref 필드 설명
13274정성태3/2/20234331.NET Framework: 2100. C# - ref 필드로 ref struct 타입을 허용하지 않는 이유
13273정성태2/28/20234053.NET Framework: 2099. C# - 관리 포인터로서의 ref 예약어 의미
13272정성태2/27/20234324오류 유형: 850. SSMS - mdf 파일을 Attach 시킬 때 Operating system error 5: "5(Access is denied.)" 에러
13271정성태2/25/20234223오류 유형: 849. Sql Server Configuration Manager가 시작 메뉴에 없는 경우
13270정성태2/24/20233841.NET Framework: 2098. dotnet build에 /p 옵션을 적용 시 유의점
13269정성태2/23/20234408스크립트: 46. 파이썬 - uvicorn의 콘솔 출력을 UDP로 전송
13268정성태2/22/20234960개발 환경 구성: 667. WSL 2 내부에서 열고 있는 UDP 서버를 호스트 측에서 접속하는 방법
13267정성태2/21/20234859.NET Framework: 2097. C# - 비동기 소켓 사용 시 메모리 해제가 finalizer 단계에서 발생하는 사례파일 다운로드1
13266정성태2/20/20234481오류 유형: 848. .NET Core/5+ - Process terminated. Couldn't find a valid ICU package installed on the system
13265정성태2/18/20234391.NET Framework: 2096. .NET Core/5+ - PublishSingleFile 유형에 대한 runtimeconfig.json 설정
13264정성태2/17/20235891스크립트: 45. 파이썬 - uvicorn 사용자 정의 Logger 작성
13263정성태2/16/20234051개발 환경 구성: 666. 최신 버전의 ilasm.exe/ildasm.exe 사용하는 방법
13262정성태2/15/20235102디버깅 기술: 191. dnSpy를 이용한 (소스 코드가 없는) 닷넷 응용 프로그램 디버깅 방법 [1]
13261정성태2/15/20234382Windows: 224. Visual Studio - 영문 폰트가 Fullwidth Latin Character로 바뀌는 문제
13260정성태2/14/20234180오류 유형: 847. ilasm.exe 컴파일 오류 - error : syntax error at token '-' in ... -inf
13259정성태2/14/20234346.NET Framework: 2095. C# - .NET5부터 도입된 CollectionsMarshal
13258정성태2/13/20234217오류 유형: 846. .NET Framework 4.8 Developer Pack 설치 실패 - 0x81f40001
13257정성태2/13/20234312.NET Framework: 2094. C# - Job에 Process 포함하는 방법 [1]파일 다운로드1
13256정성태2/10/20235159개발 환경 구성: 665. WSL 2의 네트워크 통신 방법 - 두 번째 이야기
13255정성태2/10/20234479오류 유형: 845. gihub - windows2022 이미지에서 .NET Framework 4.5.2 미만의 프로젝트에 대한 빌드 오류
13254정성태2/10/20234366Windows: 223. (WMI 쿼리를 위한) PowerShell 문자열 escape 처리
13253정성태2/9/20235153Windows: 222. C# - 다른 윈도우 프로그램이 실행되었음을 인식하는 방법파일 다운로드1
1  2  3  4  5  6  7  8  9  10  11  12  13  [14]  15  ...