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

... 61  62  63  64  65  66  67  68  69  70  [71]  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12158정성태2/25/202017750디버깅 기술: 165. C# - Marshal.GetIUnknownForObject/GetIDispatchForObject 사용 시 메모리 누수(Memory Leak) 발생파일 다운로드1
12157정성태2/25/202017839디버깅 기술: 164. C# - Marshal.GetNativeVariantForObject 사용 시 메모리 누수(Memory Leak) 발생 및 해결 방법파일 다운로드1
12156정성태2/25/202016407오류 유형: 595. LINK : warning LNK4098: defaultlib 'nafxcw.lib' conflicts with use of other libs; use /NODEFAULTLIB:library
12155정성태2/25/202015841오류 유형: 594. Warning NU1701 - This package may not be fully compatible with your project
12154정성태2/25/202015233오류 유형: 593. warning LNK4070: /OUT:... directive in .EXP differs from output filename
12153정성태2/23/202019356.NET Framework: 898. Trampoline을 이용한 후킹의 한계파일 다운로드1
12152정성태2/23/202018440.NET Framework: 897. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선 - 세 번째 이야기(Trampoline 후킹)파일 다운로드1
12151정성태2/22/202019190.NET Framework: 896. C# - Win32 API를 Trampoline 기법을 이용해 C# 메서드로 가로채는 방법 - 두 번째 이야기 (원본 함수 호출)파일 다운로드1
12150정성태2/21/202019446.NET Framework: 895. C# - Win32 API를 Trampoline 기법을 이용해 C# 메서드로 가로채는 방법 [1]파일 다운로드1
12149정성태2/20/202018275.NET Framework: 894. eBEST C# XingAPI 래퍼 - 연속 조회 처리 방법 [1]
12148정성태2/19/202020667디버깅 기술: 163. x64 환경에서 구현하는 다양한 Trampoline 기법 [1]
12147정성태2/19/202018476디버깅 기술: 162. x86/x64의 기계어 코드 최대 길이
12146정성태2/18/202019220.NET Framework: 893. eBEST C# XingAPI 래퍼 - 로그인 처리파일 다운로드1
12145정성태2/18/202019038.NET Framework: 892. eBEST C# XingAPI 래퍼 - Sqlite 지원 추가파일 다운로드1
12144정성태2/13/202019214.NET Framework: 891. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선 - 두 번째 이야기파일 다운로드1
12143정성태2/13/202015861.NET Framework: 890. 상황별 GetFunctionPointer 반환값 정리 - x64파일 다운로드1
12142정성태2/12/202018229.NET Framework: 889. C# 코드로 접근하는 MethodDesc, MethodTable파일 다운로드1
12141정성태2/10/202017253.NET Framework: 888. C# - ASP.NET Core 웹 응용 프로그램의 출력 가로채기 [2]파일 다운로드1
12140정성태2/10/202017724.NET Framework: 887. C# - ASP.NET 웹 응용 프로그램의 출력 가로채기파일 다운로드1
12139정성태2/9/202019019.NET Framework: 886. C# - Console 응용 프로그램에서 UI 스레드 구현 방법
12138정성태2/9/202022952.NET Framework: 885. C# - 닷넷 응용 프로그램에서 SQLite 사용 [6]파일 다운로드1
12137정성태2/9/202016272오류 유형: 592. [AhnLab] 경고 - 디버거 실행을 탐지했습니다.
12136정성태2/6/202017232Windows: 168. Windows + S(또는 Q)로 뜨는 작업 표시줄의 검색 바가 동작하지 않는 경우
12135정성태2/6/202022494개발 환경 구성: 468. Nuget 패키지의 로컬 보관 폴더를 옮기는 방법 [2]
12134정성태2/5/202020906.NET Framework: 884. eBEST XingAPI의 C# 래퍼 버전 - XingAPINet Nuget 패키지 [5]파일 다운로드1
12133정성태2/5/202018319디버깅 기술: 161. Windbg 환경에서 확인해 본 .NET 메서드 JIT 컴파일 전과 후 - 두 번째 이야기
... 61  62  63  64  65  66  67  68  69  70  [71]  72  73  74  75  ...