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




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]

... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13163정성태11/17/20225617개발 환경 구성: 648. 비주얼 스튜디오에서 안드로이드 기기 인식하는 방법
13162정성태11/15/20226666.NET Framework: 2069. .NET 7 - AOT(ahead-of-time) 컴파일
13161정성태11/14/20225928.NET Framework: 2068. C# - PublishSingleFile로 배포한 이미지의 역어셈블 가능 여부 (난독화 필요성) [4]
13160정성태11/11/20225842.NET Framework: 2067. C# - PublishSingleFile 적용 시 native/managed 모듈 통합 옵션
13159정성태11/10/20229117.NET Framework: 2066. C# - PublishSingleFile과 관련된 옵션 [3]
13158정성태11/9/20225306오류 유형: 826. Workload definition 'wasm-tools' in manifest 'microsoft.net.workload.mono.toolchain' [...] conflicts with manifest 'microsoft.net.workload.mono.toolchain.net7'
13157정성태11/8/20225972.NET Framework: 2065. C# - Mutex의 비동기 버전파일 다운로드1
13156정성태11/7/20226877.NET Framework: 2064. C# - Mutex와 Semaphore/SemaphoreSlim 차이점파일 다운로드1
13155정성태11/4/20226369디버깅 기술: 183. TCP 동시 접속 (연결이 아닌) 시도를 1개로 제한한 서버
13154정성태11/3/20225846.NET Framework: 2063. .NET 5+부터 지원되는 GC.GetGCMemoryInfo파일 다운로드1
13153정성태11/2/20227157.NET Framework: 2062. C# - 코드로 재현하는 소켓 상태(SYN_SENT, SYN_RECV)
13152정성태11/1/20225748.NET Framework: 2061. ASP.NET Core - DI로 추가한 클래스의 초기화 방법 [1]
13151정성태10/31/20225884C/C++: 161. Windows 11 환경에서 raw socket 테스트하는 방법파일 다운로드1
13150정성태10/30/20225928C/C++: 160. Visual Studio 2022로 빌드한 C++ 프로그램을 위한 다른 PC에서 실행하는 방법
13149정성태10/27/20225855오류 유형: 825. C# - CLR ETW 이벤트 수신이 GCHeapStats_V1/V2에 대해 안 되는 문제파일 다운로드1
13148정성태10/26/20225835오류 유형: 824. msbuild 에러 - error NETSDK1005: Assets file '...\project.assets.json' doesn't have a target for 'net5.0'. Ensure that restore has run and that you have included 'net5.0' in the TargetFramew
13147정성태10/25/20224912오류 유형: 823. Visual Studio 2022 - Unable to attach to CoreCLR. The debugger's protocol is incompatible with the debuggee.
13146정성태10/24/20225761.NET Framework: 2060. C# - Java의 Xmx와 유사한 힙 메모리 최댓값 제어 옵션 HeapHardLimit
13145정성태10/21/20226038오류 유형: 822. db2 - Password validation for user db2inst1 failed with rc = -2146500508
13144정성태10/20/20225876.NET Framework: 2059. ClrMD를 이용해 윈도우 환경의 메모리 덤프로부터 닷넷 모듈을 추출하는 방법파일 다운로드1
13143정성태10/19/20226412오류 유형: 821. windbg/sos - Error code - 0x000021BE
13142정성태10/18/20225419도서: 시작하세요! C# 12 프로그래밍
13141정성태10/17/20226912.NET Framework: 2058. [in,out] 배열을 C#에서 C/C++로 넘기는 방법 - 세 번째 이야기파일 다운로드1
13140정성태10/11/20226285C/C++: 159. C/C++ - 리눅스 환경에서 u16string 문자열을 출력하는 방법 [2]
13139정성태10/9/20226089.NET Framework: 2057. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 모든 닷넷 모듈을 추출하는 방법파일 다운로드1
13138정성태10/8/20227405.NET Framework: 2056. C# - await 비동기 호출을 기대한 메서드가 동기로 호출되었을 때의 부작용 [1]
... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...