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)
13451정성태11/21/20232432닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232256닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232354개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20232632닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20232490닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232421닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20232733Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20232462닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232519개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232339개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20232661닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232355Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/20232868닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232468닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232670닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20232910닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20232840닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232631스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232357스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232409오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232724스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232617닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20232871닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20232935닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233115닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233290스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...