Microsoft MVP성태의 닷넷 이야기
디버깅 기술: 207. Windbg로 알아보는 PTE (_MMPTE) [링크 복사], [링크+제목 복사],
조회: 4716
글쓴 사람
정성태 (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)
999정성태2/28/201146541개발 환경 구성: 108. RemoteFX - Windows 7 가상 머신에서 DirectX 9c 환경을 제공 [5]
998정성태2/27/201120227Team Foundation Server: 42. TFS Application-Tier만 재설치
996정성태2/12/201137683디버깅 기술: 35. windbg - 분석 예: 시작하자마자 비정상 종료하는 프로세스 - NullReferenceException
995정성태2/11/201156243.NET Framework: 205. 코드(C#)를 통한 풀 덤프 만드는 방법 [4]
994정성태2/10/201136121디버깅 기술: 34. Windbg - ERROR: Unable to load DLL mscordacwks_x86_x86_2.0.50727.4200.dll, Win32 error 0n2 [1]
993정성태2/10/201128507개발 환경 구성: 107. 하나의 WPF 프로젝트를 WinExe / Library로 빌드하는 방법
992정성태10/15/201129351개발 환경 구성: 106. VSS(Volume Shadow Service)를 이용한 Hyper-V VM 백업/복원 [2]
991정성태2/6/201148786개발 환경 구성: 105. 풀 덤프 파일을 남기는 방법 [4]
990정성태2/2/201133992개발 환경 구성: 104. Visual C++ Custom Build Tool 사용예 [1]파일 다운로드1
989정성태2/1/201130489개발 환경 구성: 103. DOS batch - 동기 방식으로 원격 서비스 제어
988정성태1/30/201126641개발 환경 구성: 102. MSBuild - DefineConstants에 다중 전처리 값 설정
987정성태1/29/201139843디버깅 기술: 33. PDB Symbol 로드 오류 - Cannot find or open the PDB file. [2]
986정성태1/26/201131240.NET Framework: 204. 분리된 ThreadPool 사용 - Smart Thread Pool
985정성태1/25/201127930디버깅 기술: 32. 인증서로 서명된 닷넷 어셈블리의 실행 지연 현상
984정성태1/25/201122600개발 환경 구성: 101. SharePoint 2010 - Form Design
983정성태1/23/201127630제니퍼 .NET: 15. 눈으로 확인하는 maxWorkerThreads, minFreeThreads 설정값 [1]
982정성태1/22/201124915개발 환경 구성: 100. SharePoint 2010 - iPad 친화적인 게시판 만들기 (사용자 지정 목록) [1]
981정성태1/19/201120869개발 환경 구성: 99. SharePoint 2010 - 웹 애플리케이션 생성 시 고려해야 할 점. [1]
980정성태1/19/201132250개발 환경 구성: 98. SharePoint 2010 - Office Web Apps 설치
979정성태1/18/201124988개발 환경 구성: 97. SharePoint 2010 팀 사이트 구성
978정성태1/16/201131938.NET Framework: 203. VPN 자동 연결 및 Router 설정 추가
977정성태1/12/201131294개발 환경 구성: 96. SharePoint 2010 설치 [5]
976정성태1/11/201153908오류 유형: 111. IIS - 500.19 오류 (0x8007000d)
975정성태1/10/201128108.NET Framework: 202. CLR JIT 컴파일러가 생성한 기계어 코드 확인하는 방법 [3]파일 다운로드1
974정성태1/8/201126952.NET Framework: 201. 윈폼 TreeView - Bold 폰트 설정 후 텍스트가 잘리는 문제 [1]파일 다운로드1
973정성태1/7/201126278.NET Framework: 200. IIS Metabase와 ServerManager 개체 활용파일 다운로드1
... 151  152  153  154  155  156  157  158  159  160  161  [162]  163  164  165  ...