Microsoft MVP성태의 닷넷 이야기
.NET Framework: 271. C#에서 확인해 보는 관리 힙의 인스턴스 구조 [링크 복사], [링크+제목 복사],
조회: 29079
글쓴 사람
정성태 (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]

... 151  152  153  154  155  156  157  158  159  160  161  [162]  163  164  165  ...
NoWriterDateCnt.TitleFile(s)
994정성태2/10/201135989디버깅 기술: 34. Windbg - ERROR: Unable to load DLL mscordacwks_x86_x86_2.0.50727.4200.dll, Win32 error 0n2 [1]
993정성태2/10/201128322개발 환경 구성: 107. 하나의 WPF 프로젝트를 WinExe / Library로 빌드하는 방법
992정성태10/15/201129167개발 환경 구성: 106. VSS(Volume Shadow Service)를 이용한 Hyper-V VM 백업/복원 [2]
991정성태2/6/201148654개발 환경 구성: 105. 풀 덤프 파일을 남기는 방법 [4]
990정성태2/2/201133795개발 환경 구성: 104. Visual C++ Custom Build Tool 사용예 [1]파일 다운로드1
989정성태2/1/201130319개발 환경 구성: 103. DOS batch - 동기 방식으로 원격 서비스 제어
988정성태1/30/201126537개발 환경 구성: 102. MSBuild - DefineConstants에 다중 전처리 값 설정
987정성태1/29/201139684디버깅 기술: 33. PDB Symbol 로드 오류 - Cannot find or open the PDB file. [2]
986정성태1/26/201131113.NET Framework: 204. 분리된 ThreadPool 사용 - Smart Thread Pool
985정성태1/25/201127712디버깅 기술: 32. 인증서로 서명된 닷넷 어셈블리의 실행 지연 현상
984정성태1/25/201122397개발 환경 구성: 101. SharePoint 2010 - Form Design
983정성태1/23/201127445제니퍼 .NET: 15. 눈으로 확인하는 maxWorkerThreads, minFreeThreads 설정값 [1]
982정성태1/22/201124824개발 환경 구성: 100. SharePoint 2010 - iPad 친화적인 게시판 만들기 (사용자 지정 목록) [1]
981정성태1/19/201120682개발 환경 구성: 99. SharePoint 2010 - 웹 애플리케이션 생성 시 고려해야 할 점. [1]
980정성태1/19/201132187개발 환경 구성: 98. SharePoint 2010 - Office Web Apps 설치
979정성태1/18/201124821개발 환경 구성: 97. SharePoint 2010 팀 사이트 구성
978정성태1/16/201131777.NET Framework: 203. VPN 자동 연결 및 Router 설정 추가
977정성태1/12/201131146개발 환경 구성: 96. SharePoint 2010 설치 [5]
976정성태1/11/201153725오류 유형: 111. IIS - 500.19 오류 (0x8007000d)
975정성태1/10/201128059.NET Framework: 202. CLR JIT 컴파일러가 생성한 기계어 코드 확인하는 방법 [3]파일 다운로드1
974정성태1/8/201126803.NET Framework: 201. 윈폼 TreeView - Bold 폰트 설정 후 텍스트가 잘리는 문제 [1]파일 다운로드1
973정성태1/7/201126074.NET Framework: 200. IIS Metabase와 ServerManager 개체 활용파일 다운로드1
972정성태1/7/201124076개발 환경 구성: 95. SQL Server 2008 R2 이하 버전 정보 확인
971정성태1/5/201133652.NET Framework: 199. .NET 코드 - Named Pipe 닷넷 서버와 VC++ 클라이언트 제작 [2]파일 다운로드1
970정성태1/4/201134183.NET Framework: 198. 윈도우 응용 프로그램에 Facebook 로그인 연동 [1]파일 다운로드1
969정성태12/31/201040320VC++: 45. Winsock 2 Layered Service Provider - Visual Studio 2010용 프로젝트 [1]파일 다운로드1
... 151  152  153  154  155  156  157  158  159  160  161  [162]  163  164  165  ...