Microsoft MVP성태의 닷넷 이야기
.NET Framework: 401. windbg에서 확인해 보는 관리 힙의 인스턴스 구조 [링크 복사], [링크+제목 복사],
조회: 24391
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 8개 있습니다.)
.NET Framework: 268. .NET Array는 왜 12bytes의 기본 메모리를 점유할까?
; https://www.sysnet.pe.kr/2/0/1173

.NET Framework: 269. 일반 참조형의 기본 메모리 소비는 얼마나 될까요?
; https://www.sysnet.pe.kr/2/0/1174

.NET Framework: 270. .NET 참조 개체 인스턴스의 Object Header를 확인하는 방법
; https://www.sysnet.pe.kr/2/0/1175

.NET Framework: 271. C#에서 확인해 보는 관리 힙의 인스턴스 구조
; https://www.sysnet.pe.kr/2/0/1176

.NET Framework: 401. windbg에서 확인해 보는 관리 힙의 인스턴스 구조
; https://www.sysnet.pe.kr/2/0/1559

.NET Framework: 1003. x64 환경에서 참조형의 기본 메모리 소비는 얼마나 될까요?
; https://www.sysnet.pe.kr/2/0/12486

.NET Framework: 1004. C# - GC Heap에 위치한 참조 개체의 주소를 알아내는 방법
; https://www.sysnet.pe.kr/2/0/12487

.NET Framework: 1184. C# - GC Heap에 위치한 참조 개체의 주소를 알아내는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/13017




windbg에서 확인해 보는 관리 힙의 인스턴스 구조

이 글은 다음의 내용을 windbg로 재현한 것입니다.

C#에서 확인해 보는 관리 힙의 인스턴스 구조
; https://www.sysnet.pe.kr/2/0/1176

또는 아래의 내용에 대한 좀 더 자세한 확인 방법이라고 소개하면 될 것 같군요. ^^

.NET 참조 개체 인스턴스의 Object Header를 확인하는 방법
; https://www.sysnet.pe.kr/2/0/1175




windbg로 필드를 하나도 갖지 않는 경우 분석해 보면 다음과 같은 결과가 나옵니다.

0:004> .loadby sos clr

0:004> !name2ee ConsoleApplication1!ConsoleApplication1.Program
Module:      00292e9c
Assembly:    ConsoleApplication1.exe
Token:       02000002
MethodTable: 00293810
EEClass:     00291424
Name:        ConsoleApplication1.Program

0:004> !dumpheap -mt 00293810
 Address       MT     Size
026cbf90 00293810       12     
total 0 objects
Statistics:
      MT    Count    TotalSize Class Name
00293810        1           12 ConsoleApplication1.Program
Total 1 objects

0:004> !do 026cbf90
Name:        ConsoleApplication1.Program
MethodTable: 00293810
EEClass:     00291424
Size:        12(0xc) bytes
File:        D:\...\ConsoleApplication1.exe
Fields:
None

0:004> dd 026cbf90
026cbf90  00293810 00000000 00000000 00000000
026cbfa0  00000000 00000000 00000000 00000000

필드를 하나도 갖고 있지 않는 Program 타입의 클래스가 new로 할당되었을 때 12바이트가 관리 힙에 할당됨을 위의 결과에서 알 수 있는데요. 그러면서 메모리를 덤프하기 위해 "dd 026cbf90"라는 명령어를 내리고 그 내용으로 다음과 같은 분석을 할 수 있는데,

xxxxxxxx: (0x26cbf90 - 4바이트에 위치한) Object Header(SyncBlock Index)
00293810: MethodTable
00000000: (필드가 하나도 없어도 1개는 기본 예약)




Object Header에 SyncBlock 인덱스가 사용되고 있는 경우를 확인하기 위해 예제를 다음과 같이 만들어 보았습니다.

using System;
using System.Threading;

class MyClassA
{
    public int _a = 1;
}

class MyClassB
{
    public int _a = 2;
    public int _b = 3;
}

class MyClassC
{
    public int _a = 4;
    public int _b = 5;
    public int _c = 6;
}

class Program
{
    static void Main(string[] args)
    {
        MyClassA mca = new MyClassA();
        MyClassB mcb = new MyClassB();
        MyClassC mcc = new MyClassC();

        lock (mca)
        lock (mcb)
        lock (mcc)
        {
            new Thread(func).Start(mca);
            new Thread(func).Start(mcb);
            new Thread(func).Start(mcc);

            Console.WriteLine("Console.ReadLine...");
            Console.ReadLine();
        }
    }

    private static void func(object obj)
    {
        lock (obj)
        {
            Console.ReadLine();
        }
    }
}

Console.ReadLine까지 실행되었을 때 windbg로 붙여서 다음과 같이 mca, mcb, ccc 객체의 값을 검사할 수 있습니다.

0:007> .loadby sos clr

0:007> !name2ee *!MyClassA
Module:      720c1000
Assembly:    mscorlib.dll
--------------------------------------
Module:      00852ed4
Assembly:    ConsoleApplication1.exe
Token:       02000002
MethodTable: 00853828
EEClass:     00851368
Name:        MyClassA


0:007> !dumpheap -mt 00853828
 Address       MT     Size
025424ac 00853828       12     

Statistics:
      MT    Count    TotalSize Class Name
00853828        1           12 MyClassA
Total 1 objects


0:007> !do 025424ac 
Name:        MyClassA
MethodTable: 00853828
EEClass:     00851368
Size:        12(0xc) bytes
File:        d:\...\ConsoleApplication1.exe
Fields:
      MT    Field   Offset                 Type VT     Attr    Value Name
724d3c50  4000001        4         System.Int32  1 instance        1 _a


0:007> !name2ee *!MyClassB
Module:      720c1000
Assembly:    mscorlib.dll
--------------------------------------
Module:      00852ed4
Assembly:    ConsoleApplication1.exe
Token:       02000003
MethodTable: 0085389c
EEClass:     008513bc
Name:        MyClassB


0:007> !dumpheap -mt 0085389c
 Address       MT     Size
025424b8 0085389c       16     

Statistics:
      MT    Count    TotalSize Class Name
0085389c        1           16 MyClassB
Total 1 objects


0:007> !do 025424b8 
Name:        MyClassB
MethodTable: 0085389c
EEClass:     008513bc
Size:        16(0x10) bytes
File:        d:\...\ConsoleApplication1.exe
Fields:
      MT    Field   Offset                 Type VT     Attr    Value Name
724d3c50  4000002        4         System.Int32  1 instance        2 _a
724d3c50  4000003        8         System.Int32  1 instance        3 _b

0:007> !name2ee *!MyClassC
Module:      720c1000
Assembly:    mscorlib.dll
--------------------------------------
Module:      00852ed4
Assembly:    ConsoleApplication1.exe
Token:       02000004
MethodTable: 0085391c
EEClass:     00851410
Name:        MyClassC


0:007> !dumpheap -mt 0085391c
 Address       MT     Size
025424c8 0085391c       20     

Statistics:
      MT    Count    TotalSize Class Name
0085391c        1           20 MyClassC
Total 1 objects


0:007> !do 025424c8 
Name:        MyClassC
MethodTable: 0085391c
EEClass:     00851410
Size:        20(0x14) bytes
File:        d:\...\ConsoleApplication1.exe
Fields:
      MT    Field   Offset                 Type VT     Attr    Value Name
724d3c50  4000004        4         System.Int32  1 instance        4 _a
724d3c50  4000005        8         System.Int32  1 instance        5 _b
724d3c50  4000006        c         System.Int32  1 instance        6 _c

이를 통해서 mca, mcb, mcc 변수의 객체 할당이 각각 025424ac, 025424b8, 025424c8 주소에 되었으며 그 사이의 바이트 간격을 조사해 보면 정확히 mca, mcb 크기와 일치하는 것을 볼 수 있습니다.

0:007> ? 025424b8 - 025424ac
Evaluate expression: 12 = 0000000c

0:007> ? 025424c8 - 025424b8
Evaluate expression: 16 = 00000010

즉, 3개의 변수가 관리 힙에 연속해서 할당되어 있습니다. 이 상태에서 첫 번째 mca 변수의 "Address" 주소로 덤프를 하면 다음과 같습니다.

0:007> db 025424ac
025424ac  28 38 85 00 01 00 00 00-05 00 00 08 9c 38 85 00  (8...........8..
025424bc  02 00 00 00 03 00 00 00-06 00 00 08 1c 39 85 00  .............9..
025424cc  04 00 00 00 05 00 00 00-06 00 00 00 00 00 00 00  ................
025424dc  64 c4 4d 72 dc 24 54 02-00 00 00 00 b4 05 af 04  d.Mr.$T.........
025424ec  60 c0 85 00 00 00 00 00-00 00 00 00 01 00 00 08  `...............
025424fc  60 2e 4d 72 00 00 00 00-00 00 00 00 00 00 00 00  `.Mr............
0254250c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0254251c  30 fd b2 00 02 00 00 00-03 00 00 00 01 00 00 00  0...............

28 38 85 00: 0x00853828 - MethodTable
01 00 00 00: 0x00000001 - int _a 필드 값

그리고 025424ac 주소의 4바이트 이전 값을 확인해 보면,

0:007> db 025424ac - 4 L4
025424a8  04 00 00 08  

SyncBlock의 인덱스 번호가 나옵니다. 따라서 "db 025424ac" 출력 결과를 완전하게 분석하면 다음과 같습니다.

04 00 00 08: 0x08000004 - mca 객체의 SyncBlock 인덱스
28 38 85 00: 0x00853828 - MethodTable(MyClassA)
01 00 00 00: 0x00000001 - int _a 필드 값

05 00 00 08: 0x08000005 - mcb 객체의 SyncBlock 인덱스
9c 38 85 00: 0x0085389c - MethodTable(MyClassB)
02 00 00 00: 0x00000002 - int _a 필드 값
03 00 00 00: 0x00000003 - int _b 필드 값

06 00 00 08: 0x08000006 - mcc 객체의 SyncBlock 인덱스
1c 39 85 00: 0x0085391c - MethodTable(MyClassC)
04 00 00 00: 0x00000004 - int _a 필드 값
05 00 00 00: 0x00000005 - int _b 필드 값
06 00 00 00: 0x00000006 - int _c 필드 값

sos.dll에는 SyncBlock 인덱스 값에 대한 내용도 볼 수 있습니다.

0:007> !SyncBlk
Index         SyncBlock MonitorHeld Recursion Owning Thread Info          SyncBlock Owner
    4 00b30308            3         1 00b092a0 34e0   0   025424ac MyClassA
    5 00b3033c            3         1 00b092a0 34e0   0   025424b8 MyClassB
    6 00b30370            3         1 00b092a0 34e0   0   025424c8 MyClassC
-----------------------------
Total           6
CCW             0
RCW             0
ComClassFactory 0
Free            0

위의 필드에서 Owing Thread 정보를 보면 "00b092a0 34e0" 값을 확인할 수 있는데, 이는 !threads 명령어를 통해 확인할 수 있습니다.

0:007> !threads
ThreadCount:      5
UnstartedThread:  0
BackgroundThread: 1
PendingThread:    0
DeadThread:       0
Hosted Runtime:   no
                                                                         Lock  
       ID OSID ThreadOBJ    State GC Mode     GC Alloc Context  Domain   Count Apt Exception
   0    1 34e0 00b092a0     2a020 Preemptive  0254522C:00000000 00afda00 4     MTA 
   3    2 2ff4 00b17920     2b220 Preemptive  00000000:00000000 00afda00 0     MTA (Finalizer) 
   4    3 28c4 00b2fd30   202b020 Preemptive  00000000:00000000 00afda00 0     MTA 
   5    4 3158 00b33f80   202b020 Preemptive  00000000:00000000 00afda00 0     MTA 
   6    5 3368 00b34e58   202b020 Preemptive  00000000:00000000 00afda00 0     MTA 

즉, SyncBlock 4, 5, 6번 인덱스에 해당하는 객체들의 잠금을 소유하고 있는 스레드는 00b092a0번에 해당하는 것으로 해석할 수 있습니다.

참고로, 4바이트의 Object Header 공간은 ComData, AppDomainID, Hashcode 등을 담기도 합니다. 하지만 그런 식으로 사용되다가 lock을 하게 되면 지난 글의 두 번째 그림에서 보인 "SyncBlock"을 만들고 기존 Object Header의 값을 SyncBlock으로 옮긴 후 그것에 대한 Index 값을 Object Header에 쓰게 됩니다. 아래의 글에 보면 이러한 과정을 "Header Inflation"이라고 설명하고 있습니다.

C# 클래스 객체는 어떻게 Managed Heap에 표현되는가? 
; http://www.csharpstudy.com/network/DevNote/Article/5

이 글의 내용을 이해했다면 재미있는 생각을 해볼 수 있습니다. 가령 관리 힙의 시작/끝 주소를 안다면 그 힙에 포함된 모든 객체의 정보를 덤프하는 것도 가능하다는 이야기입니다. ^^




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/10/2021]

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

비밀번호

댓글 작성자
 



2019-06-24 06시42분
[kernel] 0x08000005 - mcc 객체의 SyncBlock 인덱스
-> 0x08000006 - mcc 객체의 SyncBlock 인덱스
이어야 할 것 같습니다.
[guest]
2019-06-24 10시00분
@kernel 님, 수정했습니다. 감사합니다. ^^
정성태

... 76  77  78  79  80  81  82  83  84  85  [86]  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11786정성태11/29/201818664오류 유형: 505. OpenGL.NET 예제 실행 시 "Managed Debugging Assistant 'CallbackOnCollectedDelegate'" 예외 발생
11785정성태11/21/201820991디버깅 기술: 120. windbg 분석 사례 - ODP.NET 사용 시 Finalizer에서 System.AccessViolationException 예외 발생으로 인한 비정상 종료
11784정성태11/18/201820259Graphics: 32. .NET으로 구현하는 OpenGL (7), (8) - Matrices and Uniform Variables, Model, View & Projection Matrices파일 다운로드1
11783정성태11/18/201818389오류 유형: 504. 윈도우 환경에서 docker가 설치된 컴퓨터 간의 ping IP 주소 풀이 오류
11782정성태11/18/201817481Windows: 152. 윈도우 10에서 사라진 "Adapters and Bindings" 네트워크 우선순위 조정 기능 - 두 번째 이야기
11781정성태11/17/201820857개발 환경 구성: 422. SFML.NET 라이브러리 설정 방법 [1]파일 다운로드1
11780정성태11/17/201821953오류 유형: 503. vcpkg install bzip2 빌드 에러 - "Error: Building package bzip2:x86-windows failed with: BUILD_FAILED"
11779정성태11/17/201822793개발 환경 구성: 421. vcpkg 업데이트 [1]
11778정성태11/14/201820096.NET Framework: 803. UWP 앱에서 한 컴퓨터(localhost, 127.0.0.1) 내에서의 소켓 연결
11777정성태11/13/201820555오류 유형: 502. Your project does not reference "..." framework. Add a reference to "..." in the "TargetFrameworks" property of your project file and then re-run NuGet restore.
11776정성태11/13/201818602.NET Framework: 802. Windows에 로그인한 계정이 마이크로소프트의 계정인지, 로컬 계정인지 알아내는 방법
11775정성태11/13/201820400Graphics: 31. .NET으로 구현하는 OpenGL (6) - Texturing파일 다운로드1
11774정성태11/8/201818832Graphics: 30. .NET으로 구현하는 OpenGL (4), (5) - Shader파일 다운로드1
11773정성태11/7/201818517Graphics: 29. .NET으로 구현하는 OpenGL (3) - Index Buffer파일 다운로드1
11772정성태11/6/201820482Graphics: 28. .NET으로 구현하는 OpenGL (2) - VAO, VBO파일 다운로드1
11771정성태11/5/201819476사물인터넷: 56. Audio Jack 커넥터의 IR 적외선 송신기 - 두 번째 이야기 [1]
11770정성태11/5/201827893Graphics: 27. .NET으로 구현하는 OpenGL (1) - OpenGL.Net 라이브러리 [3]파일 다운로드1
11769정성태11/5/201818871오류 유형: 501. 프로젝트 msbuild Publish 후 connectionStrings의 문자열이 $(ReplacableToken_...)로 바뀌는 문제
11768정성태11/2/201819348.NET Framework: 801. SOIL(Simple OpenGL Image Library) - Native DLL 및 .NET DLL 제공
11767정성태11/1/201820245사물인터넷: 55. New NodeMcu v3(ESP8266)의 IR LED (적외선 송신) 제어파일 다운로드1
11766정성태10/31/201822347사물인터넷: 54. 아두이노 환경에서의 JSON 파서(ArduinoJson) 사용법
11765정성태10/26/201819229개발 환경 구성: 420. Visual Studio Code - Arduino Board Manager를 이용한 사용자 정의 보드 선택
11764정성태10/26/201824139개발 환경 구성: 419. MIT 라이선스로 무료 공개된 Detours API 후킹 라이브러리 [2]
11763정성태10/25/201821052사물인터넷: 53. New NodeMcu v3(ESP8266)의 https 통신
11762정성태10/25/201821484사물인터넷: 52. New NodeMCU v3(ESP8266)의 http 통신파일 다운로드1
11761정성태10/25/201821451Graphics: 26. 임의 축을 기반으로 3D 벡터 회전파일 다운로드1
... 76  77  78  79  80  81  82  83  84  85  [86]  87  88  89  90  ...