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

비밀번호

댓글 작성자
 




... 76  77  [78]  79  80  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11985정성태7/17/201917007개발 환경 구성: 452. msbuild - csproj에 환경 변수 조건 사용 [1]
11984정성태7/9/201925535개발 환경 구성: 451. Microsoft Edge (Chromium)을 대상으로 한 Selenium WebDriver 사용법 [1]
11983정성태7/8/201914891오류 유형: 556. nodemon - 'mocha' is not recognized as an internal or external command, operable program or batch file.
11982정성태7/8/201914979오류 유형: 555. Visual Studio 빌드 오류 - result: unexpected exception occured (-1002 - 0xfffffc16)
11981정성태7/7/201918074Math: 64. C# - 3층 구조의 신경망(분류)파일 다운로드1
11980정성태7/7/201928175개발 환경 구성: 450. Visual Studio Code의 Java 확장을 이용한 간단한 프로젝트 구축파일 다운로드1
11979정성태7/7/201918428개발 환경 구성: 449. TFS에서 gitlab/github등의 git 서버로 마이그레이션하는 방법
11978정성태7/6/201917688Windows: 161. 계정 정보가 동일하지 않은 PC 간의 인증을 수행하는 방법 [1]
11977정성태7/6/201922290오류 유형: 554. git push - error: RPC failed; HTTP 413 curl 22 The requested URL returned error: 413 Request Entity Too Large
11976정성태7/4/201916620오류 유형: 553. (잘못 인증 한 후) 원격 git repo 재인증 시 "remote: HTTP Basic: Access denied" 오류 발생
11975정성태7/4/201925424개발 환경 구성: 448. Visual Studio Code에서 콘솔 응용 프로그램 개발 시 "입력"받는 방법
11974정성태7/4/201921155Linux: 22. "Visual Studio Code + Remote Development"로 윈도우 환경에서 리눅스(CentOS 7) C/C++ 개발
11973정성태7/4/201919897Linux: 21. 리눅스에서 공유 라이브러리가 로드되지 않는다면?
11972정성태7/3/201923674.NET Framework: 847. JAVA와 .NET 간의 AES 암호화 연동 [1]파일 다운로드1
11971정성태7/3/201919969개발 환경 구성: 447. Visual Studio Code에서 OpenCvSharp 개발 환경 구성
11970정성태7/2/201918568오류 유형: 552. 웹 브라우저에서 파일 다운로드 후 "Running security scan"이 끝나지 않는 문제
11969정성태7/2/201919031Math: 63. C# - 3층 구조의 신경망파일 다운로드1
11968정성태7/1/201925728오류 유형: 551. Visual Studio Code에서 Remote-SSH 연결 시 "Opening Remote..." 단계에서 진행되지 않는 문제 [1]
11967정성태7/1/201919775개발 환경 구성: 446. Synology NAS를 Windows 10에서 iSCSI로 연결하는 방법
11966정성태6/30/201918715Math: 62. 활성화 함수에 따른 뉴런의 출력을 그리드 맵으로 시각화파일 다운로드1
11965정성태6/30/201919308.NET Framework: 846. C# - 2차원 배열을 1차원 배열로 나열하는 확장 메서드파일 다운로드1
11964정성태6/30/201920858Linux: 20. C# - Linux에서의 Named Pipe를 이용한 통신
11963정성태6/29/201920602Linux: 19. C# - .NET Core Unix Domain Socket 사용 예제
11962정성태6/27/201918287Math: 61. C# - 로지스틱 회귀를 이용한 선형분리 불가능 문제의 분류파일 다운로드1
11961정성태6/27/201917819Graphics: 37. C# - PLplot - 출력 모음(Family File Output)
11960정성태6/27/201918867Graphics: 36. C# - PLplot의 16색 이상을 표현하는 방법과 subpage를 이용한 그리드 맵 표현
... 76  77  [78]  79  80  81  82  83  84  85  86  87  88  89  90  ...