Microsoft MVP성태의 닷넷 이야기
디버깅 기술: 207. Windbg로 알아보는 PTE (_MMPTE) [링크 복사], [링크+제목 복사],
조회: 4707
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

(시리즈 글이 8개 있습니다.)
디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
; https://www.sysnet.pe.kr/2/0/13500

디버깅 기술: 203. Windbg - x64 가상 주소를 물리 주소로 변환 (페이지 크기가 2MB인 경우)
; https://www.sysnet.pe.kr/2/0/13836

디버깅 기술: 206. Windbg로 알아보는 PFN (_MMPFN)
; https://www.sysnet.pe.kr/2/0/13844

디버깅 기술: 207. Windbg로 알아보는 PTE (_MMPTE)
; https://www.sysnet.pe.kr/2/0/13845

디버깅 기술: 208. Windbg로 알아보는 Trans/Soft PTE와 2가지 Page Fault 유형
; https://www.sysnet.pe.kr/2/0/13846

디버깅 기술: 209. Windbg로 알아보는 Prototype PTE
; https://www.sysnet.pe.kr/2/0/13848

디버깅 기술: 210. Windbg - 논리(가상) 주소를 Segmentation을 거쳐 선형 주소로 변경
; https://www.sysnet.pe.kr/2/0/13849

디버깅 기술: 212. Windbg - (Ring 3 사용자 모드의) FS, GS Segment 레지스터
; https://www.sysnet.pe.kr/2/0/13852




Windbg로 알아보는 PTE (_MMPTE)

PTE는 가상 메모리 지원을 위한 페이징에서 사용하는 테이블의 엔트리로 8바이트로 고정돼 있습니다. Windbg에서 MMPTE의 자료 구조를 보면,

// MMPTE
// https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/mm/mi/mmpte/index.htm?tx=147

// Windows 10 x64 환경

5: kd> dt _MMPTE
nt!_MMPTE
   +0x000 u                : <anonymous-tag>

5: kd> ?? sizeof(_MMPTE)
unsigned int64 8

// What are anonymous structs, and more importantly, how do I tell windows.h to stop using them?
// https://devblogs.microsoft.com/oldnewthing/20170907-00/?p=96956

5: kd> dt _MMPTE u.
nt!_MMPTE
   +0x000 u  : 
      +0x000 Long : Uint8B
      +0x000 VolatileLong : Uint8B
      +0x000 Hard : _MMPTE_HARDWARE
      +0x000 Proto : _MMPTE_PROTOTYPE
      +0x000 Soft : _MMPTE_SOFTWARE
      +0x000 TimeStamp : _MMPTE_TIMESTAMP
      +0x000 Trans : _MMPTE_TRANSITION
      +0x000 Subsect : _MMPTE_SUBSECTION
      +0x000 List : _MMPTE_LIST

제법 다양한 유형의 union 구조체로 나오는데요, 이 중에서 Long, VolatileLong은 각각 Uint8B로 8바이트 단일 필드로 정의돼 있고, 나머지는 같은 8바이트짜리 데이터긴 하지만 나름 구조체(Hard, Proto, Soft, TimeStamp, Trans, Subsect, List)로 정의돼 있습니다.

이번 글에서는 Hard 유형만을 살펴볼 텐데요, 이에 대해서는 아래의 문서에 자세한 설명을 찾아볼 수 있습니다.

Active Pages: PteAddress points at a hardware PTE.
; https://rayanfam.com/topics/inside-windows-page-frame-number-part2/#active-pages-pteaddress-points-at-a-hardware-pte

즉, PFN 타입이 Active 상태인 경우 PteAddress 필드가 가리키는 PTE가 바로 hardware PTE라는 것입니다. 아주 깊게는 알 수 없겠지만, 저 말의 의미에 따라 확인을 해보는 것은 가능합니다. 이를 위해 C#으로 간단하게 코드를 만든 다음,

internal class Program
{
    long _var = 0;

    static unsafe void Main(string[] args)
    {
        Console.WriteLine($"Process ID: {pid} (0x{pid:x})");

        Program pg = new Program();

        fixed (long* ptr = &pg._var)
        {
            Console.WriteLine($"variable address in gc heap: 0x{(nint)ptr:x}");
        }

        Console.ReadLine();
    }
}

/* 출력 결과:

Process ID: 7408 (0x1cf0)
variable address in gc heap: 0x2361a00b328
*/

실행으로 출력한 0x2361a00b328 주소의 물리 주소를 다음과 같이 구하고,

// 우선 가상 주소를 해석하기 위해 해당 프로세스 문맥으로 전환
4: kd> !process 0 0 mem_map.exe
PROCESS ffff82824e35c080
    SessionId: 2  Cid: 1cf0    Peb: 3fb0604000  ParentCid: 10c8
    DirBase: cd05f000  ObjectTable: ffffa58c876ab680  HandleCount: 170.
    Image: mem_map.exe

4: kd> .process /i ffff82824e35c080
You need to continue execution (press 'g' <enter>) for the context
to be switched. When the debugger breaks in again, you will be in
the new process context.

4: kd> g
Break instruction exception - code 80000003 (first chance)
nt!DbgBreakPointWithStatus:
fffff804`080082b0 cc              int     3

// 문맥 전환이 완료된 후, 물리 주소를 조회
7: kd> !vtop 0 0x2361a00b328
Amd64VtoP: Virt 000002361a00b328, pagedir 00000000cd05f000
Amd64VtoP: PML4E 00000000cd05f020
Amd64VtoP: PDPE 000000001bc7f6c0
Amd64VtoP: PDE 0000000089d80680
Amd64VtoP: PTE 000000003588e058
Amd64VtoP: Mapped phys 00000000a9d33328
Virtual address 2361a00b328 translates to physical address a9d33328.

그럼, a9d33328 물리 주소에 대한 PFN을 이렇게 확인할 수 있습니다.

7: kd> !pfn a9d33
    PFN 000A9D33 at address FFFFEF0001FD7990
    flink       00000001  blink / share count 00000001  pteaddress FFFFF2811B0D0058
    reference count 0001    used entry count  0000      Cached    color 0   Priority 5
    restore pte 00000080  containing page 03588E  Active     M      
    Modified       

출력으로 나온 FFFFF2811B0D0058 값이 바로 Hardware PTE를 가리킨다고 했는데요, 사실 이 값은 !pte로도 확인이 가능합니다.

// 문맥 전환이 완료된 후, !pte로 페이징 레벨마다 관련된 PTE 조회
7: kd> !pte 0x2361a00b328
                                           VA 000002361a00b328
PXE at FFFFF2F97CBE5020    PPE at FFFFF2F97CA046C0    PDE at FFFFF2F9408D8680    PTE at FFFFF2811B0D0058
contains 0A0000001BC7F867  contains 0A00000089D80867  contains 0A0000003588E867  contains 80000000A9D33867
pfn 1bc7f     ---DA--UWEV  pfn 89d80     ---DA--UWEV  pfn 3588e     ---DA--UWEV  pfn a9d33     ---DA--UW-V

다시 말해, PFN 엔트리에 자신에 대한 정보를 가리키는 PTE의 가상 주소를 담고 있는 것입니다. 위에서 소개한 문서를 믿는다고 했을 때 저것이 Hardware PTE라고 하면 MMPTE의 여러 union 중에서 Hard 유형으로 덤프하면 다음과 같이 나옵니다.

// MMPTE_HARDWARE
// https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/mm/mi/mmpte/hardware.htm?tx=147

7: kd> dt _MMPTE FFFFF2811B0D0058 u.Hard.
nt!_MMPTE
   +0x000 u       : 
      +0x000 Hard    : 
         +0x000 Valid   : 0y1
         +0x000 Dirty1  : 0y1
         +0x000 Owner   : 0y1
         +0x000 WriteThrough : 0y0
         +0x000 CacheDisable : 0y0
         +0x000 Accessed : 0y1
         +0x000 Dirty   : 0y1
         +0x000 LargePage : 0y0
         +0x000 Global  : 0y0
         +0x000 CopyOnWrite : 0y0
         +0x000 Unused  : 0y0
         +0x000 Write   : 0y1
         +0x000 PageFrameNumber : 0y000000000000000010101001110100110011 (0xa9d33)
         +0x000 ReservedForHardware : 0y0000
         +0x000 ReservedForSoftware : 0y0000
         +0x000 WsleAge : 0y0000
         +0x000 WsleProtection : 0y000
         +0x000 NoExecute : 0y1

결국 PTE의 (12비트 ~ 51비트 영역에 해당하는) PageFrameNumber가 가리키는 PFN 엔트리 측에서도 PteAddress 필드로 서로 연결돼 있음을 알 수 있습니다.

// https://codemachine.com/articles/prototype_ptes.html

[PTE 데이터]                      [a9d33 PFN 데이터]
+------------------+              +----------------------------------+
| Valid            | <----------- | PteAddress == FFFFF2811B0D0058   |
| PFN = a9d33      | -----------> | Active                           |
+------------------+              +----------------------------------+

참고로, !pte의 출력 결과, 예를 들어 마지막 페이징의 PTE에 대해 "pfn a9d33 ---DA--UW-V"라고 출력이 나오는데요, 이것은 Valid 필드부터 시작해 Write 필드까지의 12비트를 요약한 것입니다.

0: Present
1: Read/Write
2: User/Supervisor
3: Write-through
4: Cache disabled
5: Accessed
6: Dirty
7: Page Size // 4K or 2MB
8: Global 
9~11: AVL (100)

"dt _MMPTE FFFFF2811B0D0058 u.Hard." 출력으로 나온 개별 필드에 대한 "0y1" 값을 갖는 것과 엮어서 "---DA--UW-V" 출력을 해석해 보면 아마도 다음과 같이 연결되는 듯합니다.

// PTE at FFFFF2811B0D0058
// contains 80000000A9D33867
// pfn a9d33     ---DA--UW-V

-: ?
-: ?
-: ?
D: Dirty
A: Accessed
-: ?
-: ?
U: User/Supervisor
W: Read/Write
-: ?
V: Valid (Present)




그런데, 저 결과를 보면서 의문이 드는 지점이 있습니다. PFN 엔트리의 물리 주소 지점을 단 1개의 PTE 주소로만 참조하고 있는 것이 맞을까요? 가령, Memory Mapped File의 경우 하나의 물리 주소를 여러 개의 프로세스에서 공유할 수 있기 때문에 저런 식으로 1:1 관계로 매핑돼 있다면 공유 메모리를 표현하는 경우 어떻게 될지 궁금해집니다.

확인을 해볼까요? ^^

이를 위해 C# 코드에 공유 메모리 부분을 살짝 추가하고,

internal class Program
{
    static unsafe void Main(string[] args)
    {
        int pid = Environment.ProcessId;
        Console.WriteLine($"Process ID: {pid} (0x{pid:x})");
        long size = 1024 * 1024 * 20; // 20MB 크기

        MemoryMappedFile? mmf = null;

        try
        {
            mmf = MemoryMappedFile.OpenExisting("my_map", MemoryMappedFileRights.ReadWrite);
        }
        catch (FileNotFoundException)
        {
        }

        if (mmf == null)
        {
            mmf = MemoryMappedFile.CreateFromFile("c:\\temp\\test.txt",
                FileMode.OpenOrCreate, "my_map", size,
                MemoryMappedFileAccess.ReadWrite);
        }

        if (mmf == null)
        {
            return;
        }

        using (MemoryMappedViewAccessor mmva = mmf.CreateViewAccessor(0, size, MemoryMappedFileAccess.ReadWrite))
        {
            IntPtr ptrAddress = GetBufferAddress(mmva);

            Console.WriteLine($"virtual address: 0x{ptrAddress:x}");

            Console.ReadLine();
        }
    }

    private static unsafe IntPtr GetBufferAddress(MemoryMappedViewAccessor mmva)
    {
        SafeMemoryMappedViewHandle handle = mmva.SafeMemoryMappedViewHandle;

        byte* ptrAddress = null;
        handle.AcquirePointer(ref ptrAddress);

        return new nint(ptrAddress);
    }
}

2개의 프로세스를 실행한 결과는 이렇고,

Process ID: 7408 (0x1cf0)
virtual address: 0x276ae060000

Process ID: 9024 (0x2340)
virtual address: 0x17da8760000

windbg로 알아낸 프로세스 문맥 정보로,

2: kd> !process 0 0 mem_map.exe
PROCESS ffff82824e35c080
    SessionId: 2  Cid: 1cf0    Peb: 3fb0604000  ParentCid: 10c8
    DirBase: cd05f000  ObjectTable: ffffa58c876ab680  HandleCount: 170.
    Image: mem_map.exe

PROCESS ffff82824adf2080
    SessionId: 2  Cid: 2340    Peb: 39975c4000  ParentCid: 10c8
    DirBase: 055f2000  ObjectTable: ffffa58c877b6d80  HandleCount: 168.
    Image: mem_map.exe

Memory Mapped File의 가상 주소 2개를 각각 덤프해 보면 이렇게 나옵니다.

// ffff82824e35c080 문맥으로 전환 후...

2: kd> !vtop 0 0x276ae060000
Amd64VtoP: Virt 00000276ae060000, pagedir 00000000cd05f000
Amd64VtoP: PML4E 00000000cd05f020
Amd64VtoP: PDPE 000000001bc7fed0
Amd64VtoP: PDE 00000000827fab80
Amd64VtoP: PTE 0000000093718300
Amd64VtoP: Mapped phys 0000000047119000
Virtual address 276ae060000 translates to physical address 47119000.

2: kd> !pte 0x276ae060000
                                           VA 00000276ae060000
PXE at FFFFF2F97CBE5020    PPE at FFFFF2F97CA04ED0    PDE at FFFFF2F9409DAB80    PTE at FFFFF2813B570300
contains 0A0000001BC7F867  contains 0A000000827FA867  contains 0A00000093718867  contains C100000047119847
pfn 1bc7f     ---DA--UWEV  pfn 827fa     ---DA--UWEV  pfn 93718     ---DA--UWEV  pfn 47119     ---D---UW-V

2: kd> !pfn 47119
    PFN 00047119 at address FFFFEF0000D534B0
    flink       00000001  blink / share count 00000002  pteaddress FFFFA58C89CF3000
    reference count 0001    used entry count  0090      Cached    color 0   Priority 5
    restore pte 8A8C33B71C9004C0  containing page 1E08C7  Active      P     
     Shared              

// ffff82824adf2080 문맥으로 전환 후...

1: kd> !vtop 0 0x17da8760000
Amd64VtoP: Virt 0000017da8760000, pagedir 00000000055f2000
Amd64VtoP: PML4E 00000000055f2010
Amd64VtoP: PDPE 00000000bbe13fb0
Amd64VtoP: PDE 0000000046c16a18
Amd64VtoP: PTE 00000000a0e32b00
Amd64VtoP: Mapped phys 0000000047119000
Virtual address 17da8760000 translates to physical address 47119000.

1: kd> !pte 0x17da8760000
                                           VA 0000017da8760000
PXE at FFFFF2F97CBE5010    PPE at FFFFF2F97CA02FB0    PDE at FFFFF2F9405F6A18    PTE at FFFFF280BED43B00
contains 0A000000BBE13867  contains 0A00000046C16867  contains 0A000000A0E32867  contains C000000047119867
pfn bbe13     ---DA--UWEV  pfn 46c16     ---DA--UWEV  pfn a0e32     ---DA--UWEV  pfn 47119     ---DA--UW-V

1: kd> !pfn 47119
    PFN 00047119 at address FFFFEF0000D534B0
    flink       00000001  blink / share count 00000002  pteaddress FFFFA58C89CF3000
    reference count 0001    used entry count  0090      Cached    color 0   Priority 5
    restore pte 8A8C33B71C9004C0  containing page 1E08C7  Active      P     
     Shared              

보는 바와 같이 "share count" 값이 2로 나옵니다. 결국, 2개의 프로세스에서 0x276ae060000, 0x17da8760000 가상 주소가 동일한 물리 주소인 pfn 47119로 귀결은 되지만 정작 PFN 47119의 PteAddress 필드는 별도의 FFFFA58C89CF3000 값을 가리키고 있습니다. 재미있게도 저 PTE 값은 두 프로세스 모두에서 갖고 있는 PTE와 상관없는 주소입니다.

이런 식의 공유 메모리에 대한 PTE가 갖는 특이점이라면,

1: kd> dt _MMPTE FFFFA58C89CF3000 u.Hard.
nt!_MMPTE
   +0x000 u       : 
      +0x000 Hard    : 
         +0x000 Valid   : 0y1
         +0x000 Dirty1  : 0y0
         +0x000 Owner   : 0y0
         +0x000 WriteThrough : 0y0
         +0x000 CacheDisable : 0y0
         +0x000 Accessed : 0y1
         +0x000 Dirty   : 0y0
         +0x000 LargePage : 0y0
         +0x000 Global  : 0y1
         +0x000 CopyOnWrite : 0y0
         +0x000 Unused  : 0y0
         +0x000 Write   : 0y1
         +0x000 PageFrameNumber : 0y000000000000000001000111000100011001 (0x47119)
         +0x000 ReservedForHardware : 0y0000
         +0x000 ReservedForSoftware : 0y0000
         +0x000 WsleAge : 0y1010
         +0x000 WsleProtection : 0y000
         +0x000 NoExecute : 0y0

플래그 값 중에서 Global 필드가 1로 설정돼 있다는 차이점이 있습니다. (업데이트: 이와 관련한 자세한 사항은 Prototype PTE를 다루면서 설명합니다.) 아마도 유추해 보면, 공유 메모리인 경우에는 전역적(Global)으로 Hardware PTE 하나를 두고 PFN을 유지한 다음 각각의 프로세스는 DirBase 내에 자신만의 PTE를 별도로 유지하는 것으로 보입니다.




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







[최초 등록일: ]
[최종 수정일: 12/20/2024]

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

비밀번호

댓글 작성자
 




... 151  152  153  154  155  156  157  [158]  159  160  161  162  163  164  165  ...
NoWriterDateCnt.TitleFile(s)
1099정성태8/15/201128260오류 유형: 132. 어느 순간 갑자기 접속이 안 되는 TFS 서버
1098정성태8/15/201150340웹: 24. 네이버는 어떻게 로그인 처리를 할까요? [2]
1097정성태8/15/201121640.NET Framework: 235. 메서드의 메타 데이터 토큰 값으로 클래스를 찾아내는 방법
1096정성태8/15/201125774디버깅 기술: 42. Watson Bucket 정보를 이용한 CLR 응용 프로그램 예외 분석 - (2)
1095정성태8/14/201126159디버깅 기술: 41. Windbg - 비정상 종료된 닷넷 프로그램의 StackTrace에서 보이는 offset 값 의미
1094정성태8/14/201130605오류 유형: 131. Fiddler가 강제 종료된 경우, 웹 사이트 방문이 안되는 현상
1093정성태7/27/201124183오류 유형: 130. Unable to connect to the Microsoft Visual Studio Remote Debugging Monitor ... Access is denied.
1092정성태7/22/201126625Team Foundation Server: 46. 코드 이외의 파일에 대해 소스 제어에서 제외시키는 방법
1091정성태7/21/201125658개발 환경 구성: 128. WP7 Emulator 실행 시 audiodg.exe의 CPU 소모율 증가 [2]
1089정성태7/18/201131232.NET Framework: 234. 왜? Button 컨트롤에는 MouseDown/MouseUp 이벤트가 발생하지 않을까요?파일 다운로드1
1088정성태7/16/201124256.NET Framework: 233. Entity Framework 4.1 - 윈도우 폰 7에서의 CodeFirst 순환 참조 문제파일 다운로드1
1087정성태7/15/201126999.NET Framework: 232. Entity Framework 4.1 - CodeFirst 개체의 직렬화 시 순환 참조 해결하는 방법 - 두 번째 이야기파일 다운로드1
1086정성태7/14/201128374.NET Framework: 231. Entity Framework 4.1 - CodeFirst 개체의 직렬화 시 순환 참조 해결하는 방법 [1]파일 다운로드1
1085정성태7/14/201128890.NET Framework: 230. Entity Framework 4.1 - Code First + WCF 서비스 시 EndpointNotFoundException 오류 - 두 번째 이야기파일 다운로드1
1084정성태7/11/201134160.NET Framework: 229. SQL 서버 - DB 테이블의 데이터 변경에 대한 알림 처리 [4]파일 다운로드1
1083정성태7/11/201128206.NET Framework: 228. Entity Framework 4.1 - Code First + WCF 서비스 시 EndpointNotFoundException 오류
1082정성태7/10/201127746.NET Framework: 227. basicHttpBinding + 사용자 정의 인증 구현 [2]파일 다운로드1
1081정성태7/9/201127078VC++: 53. Windows 7에서 gcc.exe 실행 시 Access denied 오류 [2]
1080정성태7/8/201125584웹: 23. Sysnet 웹 사이트의 HTML5 변환 기록 - 두 번째 이야기파일 다운로드1
1079정성태7/6/201130005오류 유형: 129. Hyper-V + Realtek 랜카드가 설치된 시스템의 BSOD 현상 [2]
1078정성태7/5/201137479VC++: 52. Chromium 컴파일하는 방법 [2]
1077정성태6/24/201135107.NET Framework: 226. HttpWebRequest 타입의 HaveResponse 속성 이야기파일 다운로드1
1076정성태6/23/201129297오류 유형: 128. SQL Express - User Instance 옵션을 사용한 경우 발생하는 오류 메시지 유형 2가지
1075정성태6/21/201124864VS.NET IDE: 69. 윈폰 프로젝트에서 WCF 서비스 참조할 때 Reference.cs 파일이 비어있는 경우
1074정성태6/20/201124991.NET Framework: 225. 닷넷 네트워크 라이브러리의 트레이스 기능파일 다운로드1
1073정성태6/20/201127214오류 유형: 127. Visual Studio에서 WCF 서비스의 이름 변경 시 발생할 수 있는 오류
... 151  152  153  154  155  156  157  [158]  159  160  161  162  163  164  165  ...