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

... 46  47  48  49  50  51  [52]  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12367정성태10/12/202023379오류 유형: 667. Ubuntu - Temporary failure resolving 'kr.archive.ubuntu.com' [2]
12366정성태10/12/202012205.NET Framework: 950. C# 9.0 - (4) 원시 크기 정수(Native ints) [1]파일 다운로드1
12365정성태10/12/202011048.NET Framework: 949. C# 9.0 - (3) 람다 메서드의 매개 변수 무시(Lambda discard parameters)파일 다운로드1
12364정성태10/11/202012257.NET Framework: 948. C# 9.0 - (2) localsinit 플래그 내보내기 무시(Suppress emitting localsinit flag)파일 다운로드1
12363정성태10/11/202013373.NET Framework: 947. C# 9.0 - (1) 대상으로 형식화된 new 식(Target-typed new expressions) [2]파일 다운로드1
12362정성태10/11/202010107VS.NET IDE: 151. Visual Studio 2019에 .NET 5 rc/preview 적용하는 방법
12361정성태10/11/202011752.NET Framework: 946. C# 9.0을 위한 개발 환경 구성
12360정성태10/8/20208796오류 유형: 666. The type or namespace name '...' does not exist in the namespace 'Microsoft.VisualStudio.TestTools' (are you missing an assembly reference?)
12359정성태10/7/202010323오류 유형: 665. Windows - 재부팅 후 iSCSI 연결이 끊기는 문제
12358정성태10/7/202010444오류 유형: 664. Web Deploy 설치 시 "A newer version of Microsoft Web Deploy 3.6 was found on this machine." 오류 [3]
12357정성태10/7/20208352오류 유형: 663. 이벤트 로그 - The storage optimizer couldn't complete retrim on New Volume
12356정성태10/7/202023521오류 유형: 662. ASP.NET Core와 500.19, 500.21 오류 (0x8007000d)
12355정성태10/3/20208499오류 유형: 661. Hyper-V Linux VM의 Internal 유형의 가상 Switch에 대한 IP 연결이 되지 않는 경우
12354정성태10/2/202021474오류 유형: 660. Web Deploy (msdeploy.axd) 실행 시 오류 기록 [1]
12353정성태10/2/202011298개발 환경 구성: 518. 비주얼 스튜디오에서 IIS 웹 서버로 "Web Deploy"를 이용해 배포하는 방법
12352정성태10/2/202011857개발 환경 구성: 517. Hyper-V Internal 네트워크에 NAT을 이용한 인터넷 연결 제공
12351정성태10/2/202011354오류 유형: 659. Nox 실행이 안 되는 경우 - Unable to bind to the underlying transport for ...
12350정성태9/25/202014913Windows: 175. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 [2]파일 다운로드1
12349정성태9/25/20209605Linux: 32. Ubuntu 20.04 - docker를 위한 tcp 바인딩 추가
12348정성태9/25/202010459오류 유형: 658. 리눅스 docker - Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock
12347정성태9/25/202024850Windows: 174. WSL 2의 네트워크 통신 방법 [4]
12346정성태9/25/20209625오류 유형: 657. IIS - http://localhost 방문 시 Service Unavailable 503 오류 발생
12345정성태9/25/20209198오류 유형: 656. iisreset 실행 시 "Restart attempt failed." 오류가 발생하지만 웹 서비스는 정상적인 경우파일 다운로드1
12344정성태9/25/202010470Windows: 173. 서비스 관리자에 "IIS Admin Service"가 등록되어 있지 않다면?
12343정성태9/24/202020433.NET Framework: 945. C# - 닷넷 응용 프로그램에서 메모리 누수가 발생할 수 있는 패턴 [5]
12342정성태9/24/202011555디버깅 기술: 171. windbg - 인스턴스가 살아 있어 메모리 누수가 발생하고 있는지 확인하는 방법
... 46  47  48  49  50  51  [52]  53  54  55  56  57  58  59  60  ...