Microsoft MVP성태의 닷넷 이야기
.NET Framework: 271. C#에서 확인해 보는 관리 힙의 인스턴스 구조 [링크 복사], [링크+제목 복사],
조회: 29128
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 9개 있습니다.)
(시리즈 글이 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




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

지난 글에서, 배열과 일반 참조형에 대한 관리 힙의 인스턴스 구조를 살펴보았는데요.

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

.NET Array는 왜 12bytes의 기본 메모리를 점유할까?
; https://www.sysnet.pe.kr/2/0/1173

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

어려운 windbg를 사용하지 않아도 C#에서 간단하게 unsafe/fixed를 이용하여 확인을 하는 것도 가능합니다.

어떻게 그럴 수 있는지 ^^ 배열부터 시험삼아서 테스트를 해볼까요? ".NET Array는 왜 12bytes의 기본 메모리를 점유할까?"글에서 배열은 다음과 같은 구조를 갖는다고 설명했었습니다.

-4 : OBJECT HEADER(예: SyncBlock Index를 담는 용도)
+0 : MethodTable Address
+4 : 배열 요소 크기
+8 ~ : 값 배열

위의 값을 구해오기 위해서, C#으로는 다음과 같이 코딩을 할 수 있습니다.

static unsafe void Main(string[] args)
{
    int [] test = new int[1];
    test[0] = 0xff;

    Console.WriteLine("int [] ================== ");
    fixed (int *p1 = &test[0])
    {
        Console.WriteLine("OBJECT Header(SyncBlock Index): " + (*(p1 - 3)).ToString("x"));
        Console.WriteLine("MethodTable Address: " + (*(p1 - 2)).ToString("x"));
        Console.WriteLine("배열 요소 크기: " + (*(p1 - 1)).ToString("x"));
        Console.WriteLine("0번째 배열 값: " + (*(p1 - 0)).ToString("x"));
    }
}

// 출력 결과
OBJECT Header(SyncBlock Index): 0
MethodTable Address: 72fd28b8
배열 요소 크기: 1
0번째 배열 값: ff

만약, test 인스턴스에 대해 lock 구문을 걸면 Object Header의 값이 변경된 것을 확인할 수 있습니다.

Console.WriteLine("locked int [] ================== ");
lock (test)
{
    fixed (int* p1 = &test[0])
    {
        Console.WriteLine("OBJECT Header(SyncBlock Index): " + (*(p1 - 3)).ToString("x"));
		...[생략]...
    }
}

// 출력 결과
OBJECT Header(SyncBlock Index): 1

출력된 0x72fd28b8 값이 MethodTable 주솟값인지 확인하려면 windbg를 사용하여 !dumpobj 명령어를 실행해야만 하는데, 실제로 해보시면 값이 맞다는 것을 알 수 있습니다.

그다음, 일반 참조 개체의 인스턴스 메모리를 살펴볼 차례인데요. 아쉽게도 object 형 개체에 대해서는 직접적으로 포인터를 받아올 수 없고 다음과 같이 해당 개체에 정의된 필드의 주소를 가져오는 방식을 사용하여 우회할 수 있습니다.

class Program
{
    public int value = 0xff;

    static unsafe void Main(string[] args)
    {
        Program pg = new Program();

        fixed (int* p2 = &pg.value)
        {
            Console.WriteLine("OBJECT Header(SyncBlock Index): " + (*(p2 - 2)).ToString("x"));
            Console.WriteLine("MethodTable Address: " + (*(p2 - 1)).ToString("x"));
            Console.WriteLine("첫 번째 필드 값: " + (*(p2 - 0)).ToString("x"));
        }
    }
}

// 출력 결과

SyncBlock Index: 0
MethodTable Address: 1d3810
첫 번째 필드 값: ff




지금까지 살펴본 코드에 착안해서 ^^ 현실성은 다소 떨어지지만... 재미있는 실험을 하나 해볼까요? ^^

다음은, 무한 대기 상태로 빠지는 예제입니다.

class Program
{
    public int value = 0xff;

    static void LockThread(object lockObject)
    {
        lock (lockObject)
        {
            Console.WriteLine("You can't see this message!");
        }
    }


    static unsafe void Main(string[] args)
    {
        Program pg = new Program();

        lock (pg)
        {
            Thread t1 = new Thread(LockThread);
            t1.Start(pg);
            t1.Join();
        }
    }
}

그런데, 다음과 같이 강제로 SyncBlock Index 값을 설정/해제하는 코드를 작성하고,

unsafe static void ForceSetLock(object lockObject, int oldValue)
{
    Program pg = lockObject as Program;

    fixed (int* p2 = &pg.value)
    {
        *(p2 - 2) = oldValue;
    }
}

unsafe static int ForceReleaseLock(object lockObject)
{
    Program pg = lockObject as Program;
    int lastValue = 0;

    fixed (int* p2 = &pg.value)
    {
        lastValue = *(p2 - 2);
        *(p2 - 2) = 0;
    }

    return lastValue;
}

LockThread에서 lock을 얻는 앞 뒤로 다음과 같이 처리를 해주면,

static void LockThread(object lockObject)
{
    int oldValue = ForceReleaseLock(lockObject);
    lock (lockObject)
    {
        Console.WriteLine("You can't see this message!");
    }
    ForceSetLock(lockObject, oldValue);
}

^^ 정상적으로 lock을 얻는 것을 확인할 수 있습니다. 참고로, ForceSetLock을 호출하지 않는 경우 - 즉, 나중에 SyncBlock index 값을 돌려놓지 않으면 t1.Join() 함수에서 다음과 같은 예외가 발생합니다.

System.Threading.SynchronizationLockException was unhandled
  Message=Object synchronization method was called from an unsynchronized block of code.
  Source=ConsoleApplication1
  StackTrace:
       at ConsoleApplication1.Program.Main(String[] args) in D:\...\Program.cs:line 57
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

암튼... 재미있는 탐구였지요? ^^

(첨부된 파일은 위의 코드를 포함한 예제 프로젝트입니다.)




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

[연관 글]






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

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

비밀번호

댓글 작성자
 



2021-01-12 04시10분
[jt] 첫번째 예제는 -6, -4, -2로 해야 뭔가 비슷하게 나오는데 x64 라서 그런걸까요?
[guest]
2021-01-12 09시17분
@jt 다음의 글에 정리해 두었으니 참고하세요.

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

또한 이번 글에 포함된 예제 코드도 x64 환경에서 동작하게 수정했으니 다시 내려받아 테스트하시면 됩니다.
정성태
2021-01-12 10시56분
[jt] 감사합니다 👍
[guest]

... 76  77  78  79  [80]  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11935정성태6/9/201919864.NET Framework: 843. C# - PLplot 출력을 파일이 아닌 Window 화면으로 변경
11934정성태6/7/201921197VC++: 133. typedef struct와 타입 전방 선언으로 인한 C2371 오류파일 다운로드1
11933정성태6/7/201919552VC++: 132. enum 정의를 C++11의 enum class로 바꿀 때 유의할 사항파일 다운로드1
11932정성태6/7/201918734오류 유형: 544. C++ - fatal error C1017: invalid integer constant expression파일 다운로드1
11931정성태6/6/201919269개발 환경 구성: 441. C# - CairoSharp/GtkSharp 사용을 위한 프로젝트 구성 방법
11930정성태6/5/201919797.NET Framework: 842. .NET Reflection을 대체할 System.Reflection.Metadata 소개 [1]
11929정성태6/5/201919345.NET Framework: 841. Windows Forms/C# - 클립보드에 RTF 텍스트를 복사 및 확인하는 방법 [1]
11928정성태6/5/201918132오류 유형: 543. PowerShell 확장 설치 시 "Catalog file '[...].cat' is not found in the contents of the module" 오류 발생
11927정성태6/5/201919314스크립트: 15. PowerShell ISE의 스크립트를 복사 후 PPT/Word에 붙여 넣으면 한글이 깨지는 문제 [1]
11926정성태6/4/201919902오류 유형: 542. Visual Studio - pointer to incomplete class type is not allowed
11925정성태6/4/201919717VC++: 131. Visual C++ - uuid 확장 속성과 __uuidof 확장 연산자파일 다운로드1
11924정성태5/30/201921335Math: 57. C# - 해석학적 방법을 이용한 최소 자승법 [1]파일 다운로드1
11923정성태5/30/201920978Math: 56. C# - 그래프 그리기로 알아보는 경사 하강법의 최소/최댓값 구하기파일 다운로드1
11922정성태5/29/201918511.NET Framework: 840. ML.NET 데이터 정규화파일 다운로드1
11921정성태5/28/201924359Math: 55. C# - 다항식을 위한 최소 자승법(Least Squares Method)파일 다운로드1
11920정성태5/28/201916029.NET Framework: 839. C# - PLplot 색상 제어
11919정성태5/27/201920273Math: 54. C# - 최소 자승법의 1차 함수에 대한 매개변수를 단순 for 문으로 구하는 방법 [1]파일 다운로드1
11918정성태5/25/201921128Math: 53. C# - 행렬식을 이용한 최소 자승법(LSM: Least Square Method)파일 다운로드1
11917정성태5/24/201922094Math: 52. MathNet을 이용한 간단한 통계 정보 처리 - 분산/표준편차파일 다운로드1
11916정성태5/24/201919925Math: 51. MathNET + OxyPlot을 이용한 간단한 통계 정보 처리 - Histogram파일 다운로드1
11915정성태5/24/201923051Linux: 11. 리눅스의 환경 변수 관련 함수 정리 - putenv, setenv, unsetenv
11914정성태5/24/201921994Linux: 10. 윈도우의 GetTickCount와 리눅스의 clock_gettime파일 다운로드1
11913정성태5/23/201918752.NET Framework: 838. C# - 숫자형 타입의 bit(2진) 문자열, 16진수 문자열 구하는 방법파일 다운로드1
11912정성태5/23/201918698VS.NET IDE: 137. Visual Studio 2019 버전 16.1부터 리눅스 C/C++ 프로젝트에 추가된 WSL 지원
11911정성태5/23/201917478VS.NET IDE: 136. Visual Studio 2019 - 리눅스 C/C++ 프로젝트에 인텔리센스가 동작하지 않는 경우
11910정성태5/23/201927119Math: 50. C# - MathNet.Numerics의 Matrix(행렬) 연산 [1]파일 다운로드1
... 76  77  78  79  [80]  81  82  83  84  85  86  87  88  89  90  ...