Microsoft MVP성태의 닷넷 이야기
디버깅 기술: 207. Windbg로 알아보는 PTE (_MMPTE) [링크 복사], [링크+제목 복사],
조회: 2902
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13859정성태1/9/20251851디버깅 기술: 215. Windbg - syscall 이후 실행되는 KiSystemCall64 함수 및 SSDT 디버깅
13858정성태1/8/20251877개발 환경 구성: 738. PowerShell - 원격 호출 시 "powershell.exe"가 아닌 "pwsh.exe" 환경으로 명령어를 실행하는 방법
13857정성태1/7/20251899C/C++: 187. Golang - 콘솔 응용 프로그램을 Linux 데몬 서비스를 지원하도록 변경파일 다운로드1
13856정성태1/6/20251917디버깅 기술: 214. Windbg - syscall 단계까지의 Win32 API 호출 (예: Sleep)
13855정성태12/28/20242211오류 유형: 941. Golang - os.StartProcess() 사용 시 오류 정리
13854정성태12/27/20242555C/C++: 186. Golang - 콘솔 응용 프로그램을 NT 서비스를 지원하도록 변경파일 다운로드1
13853정성태12/26/20242430디버깅 기술: 213. Windbg - swapgs 명령어와 (Ring 0 커널 모드의) FS, GS Segment 레지스터
13852정성태12/25/20242334디버깅 기술: 212. Windbg - (Ring 3 사용자 모드의) FS, GS Segment 레지스터파일 다운로드1
13851정성태12/23/20242283디버깅 기술: 211. Windbg - 커널 모드 디버깅 상태에서 사용자 프로그램을 디버깅하는 방법
13850정성태12/23/20242331오류 유형: 940. "Application Information" 서비스를 중지한 경우, "This file does not have an app associated with it for performing this action."
13849정성태12/20/20242516디버깅 기술: 210. Windbg - 논리(가상) 주소를 Segmentation을 거쳐 선형 주소로 변경
13848정성태12/18/20242509디버깅 기술: 209. Windbg로 알아보는 Prototype PTE파일 다운로드2
13847정성태12/18/20242611오류 유형: 939. golang - 빌드 시 "unknown directive: toolchain" 오류 빌드 시 이런 오류가 발생한다면?
13846정성태12/17/20242616디버깅 기술: 208. Windbg로 알아보는 Trans/Soft PTE와 2가지 Page Fault 유형파일 다운로드1
13845정성태12/16/20242902디버깅 기술: 207. Windbg로 알아보는 PTE (_MMPTE)
13844정성태12/14/20242677디버깅 기술: 206. Windbg로 알아보는 PFN (_MMPFN)파일 다운로드1
13843정성태12/13/20242642오류 유형: 938. Docker container 내에서 빌드 시 error MSB3021: Unable to copy file "..." to "...". Access to the path '...' is denied.
13842정성태12/12/20243031디버깅 기술: 205. Windbg - KPCR, KPRCB
13841정성태12/11/20243117오류 유형: 937. error MSB4044: The "ValidateValidArchitecture" task was not given a value for the required parameter "RemoteTarget"
13840정성태12/11/20242946오류 유형: 936. msbuild - Your project file doesn't list 'win' as a "RuntimeIdentifier"
13839정성태12/11/20242900오류 유형: 936. msbuild - error CS1617: Invalid option '12.0' for /langversion. Use '/langversion:?' to list supported values.
13838정성태12/4/20242901오류 유형: 935. Windbg - Breakpoint 0's offset expression evaluation failed.
13837정성태12/3/20243047디버깅 기술: 204. Windbg - 윈도우 핸들 테이블 (3) - Windows 10 이상인 경우
13836정성태12/3/20243204디버깅 기술: 203. Windbg - x64 가상 주소를 물리 주소로 변환 (페이지 크기가 2MB인 경우)
13835정성태12/2/20243109오류 유형: 934. Azure - rm: cannot remove '...': Directory not empty
13834정성태11/29/20243112Windows: 275. C# - CUI 애플리케이션과 Console 윈도우 (Windows 10 미만의 Classic Console 모드인 경우) [1]파일 다운로드1
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...