Microsoft MVP성태의 닷넷 이야기
.NET Framework: 871. .NET AnyCPU로 빌드된 PE 헤더의 로딩 전/후 차이점 [링크 복사], [링크+제목 복사]
조회: 10497
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

.NET AnyCPU로 빌드된 PE 헤더의 로딩 전/후 차이점

잠시 지난 글의 코드를 실습하고 있는데,

해당 DLL이 Managed인지 / Unmanaged인지 확인하는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/1296

AnyCPU의 PE 헤더가 로딩 전/후에 따라 달라지는 것을 알게 되었습니다.

예를 들어, AnyCPU로 빌드한 콘솔 프로그램의 경우 디스크 상의 파일을 기반으로 "CFF Explorer"를 이용해 로딩해 보면 다음과 같은 PE Header 정보를 볼 수 있습니다.

anycpu_pe_header_1.png

anycpu_pe_header_2.png

즉, 완벽하게 32bit 규격의 PE header를 가지고 있습니다. 하지만 이것을 windbg로 로딩해 보면,

Microsoft (R) Windows Debugger Version 10.0.17763.132 AMD64
Copyright (c) Microsoft Corporation. All rights reserved.

CommandLine: C:\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe

************* Path validation summary **************
Response                         Time (ms)     Location
Deferred                                       SRV*c:\Symbols*http://msdl.microsoft.com/download/symbols
Symbol search path is: SRV*c:\Symbols*http://msdl.microsoft.com/download/symbols
Executable search path is: 
ModLoad: 00000000`00ef0000 00000000`00ef8000   ConsoleApplication1.exe
ModLoad: 00007ffe`19c60000 00007ffe`19e50000   ntdll.dll
ModLoad: 00007ffe`022f0000 00007ffe`02354000   C:\WINDOWS\SYSTEM32\MSCOREE.DLL
ModLoad: 00007ffe`18e20000 00007ffe`18ed2000   C:\WINDOWS\System32\KERNEL32.dll
ModLoad: 00007ffe`16e70000 00007ffe`17113000   C:\WINDOWS\System32\KERNELBASE.dll
(5abc.5564): Break instruction exception - code 80000003 (first chance)
ntdll!LdrpDoDebuggerBreak+0x30:
00007ffe`19d311dc cc              int     3

0:000> dt _IMAGE_DOS_HEADER 00000000`00ef0000 
ntdll!_IMAGE_DOS_HEADER
   +0x000 e_magic          : 0x5a4d
   +0x002 e_cblp           : 0x90
   +0x004 e_cp             : 3
   +0x006 e_crlc           : 0
   +0x008 e_cparhdr        : 4
   +0x00a e_minalloc       : 0
   +0x00c e_maxalloc       : 0xffff
   +0x00e e_ss             : 0
   +0x010 e_sp             : 0xb8
   +0x012 e_csum           : 0
   +0x014 e_ip             : 0
   +0x016 e_cs             : 0
   +0x018 e_lfarlc         : 0x40
   +0x01a e_ovno           : 0
   +0x01c e_res            : [4] 0
   +0x024 e_oemid          : 0
   +0x026 e_oeminfo        : 0
   +0x028 e_res2           : [10] 0
   +0x03c e_lfanew         : 0n128

0:000> ? 00000000`00ef0000 + 0n128 + 0n4
Evaluate expression: 15663236 = 00000000`00ef0084

0:000> dt _IMAGE_FILE_HEADER 00000000`00ef0084
ntdll!_IMAGE_FILE_HEADER
   +0x000 Machine          : 0x14c
   +0x002 NumberOfSections : 3
   +0x004 TimeDateStamp    : 0x5e022dd0
   +0x008 PointerToSymbolTable : 0
   +0x00c NumberOfSymbols  : 0
   +0x010 SizeOfOptionalHeader : 0xf0
   +0x012 Characteristics  : 0x22

보는 바와 같이 _IMAGE_FILE_HEADER의 Machine 값이 (현재 x64 프로세스 공간임에도 불구하고) 0x14c(IMAGE_FILE_MACHINE_I386) 값을 갖고 있기 때문에 AnyCPU 이미지인 경우에는 Machine 필드의 값으로 타겟 플랫폼을 판단해서는 안 됩니다.

그런데, 재미있는 변화가 있습니다. 바로 SizeOfOptionalHeader의 값이 디스크 상에서는 0xe0이었던 것과는 달리 DLL 메모리 매핑이 이뤄진 시점에는 0xf0으로 변경되었다는 점입니다. 따라서 이 값을 기반으로 현재 로딩된 이미지를 x86 또는 x64 중 어떤 것으로 다뤄야 하는지 판단할 수 있습니다.

혹은, IMAGE_FILE_HEADER의 바로 다음 int16 값을 읽어보는 것도 방법일 수 있습니다. 즉, IMAGE_OPTIONAL_HEADER 영역의 Magic 필드 값을 읽어보는 건데요. 이 값도 디스크 상에 있을 때는 0x010B로 "PE32" 유형을 의미하지만 DLL 메모리 매핑이 이뤄진 시점에는,

0:000> dw 00000000`00ef0084+0x14 L1
00000000`00ef0098  020b

0x020b로 PE64를 의미하는 값으로 바뀌어 있습니다.




그런데 좀 미심쩍은 면이 있습니다. windbg에 로딩하자마자, 다음과 같이 mscoree.dll이 로드된 것을 볼 수 있습니다.

ModLoad: 00000000`00ef0000 00000000`00ef8000   ConsoleApplication1.exe
ModLoad: 00007ffe`19c60000 00007ffe`19e50000   ntdll.dll
ModLoad: 00007ffe`022f0000 00007ffe`02354000   C:\WINDOWS\SYSTEM32\MSCOREE.DLL
ModLoad: 00007ffe`18e20000 00007ffe`18ed2000   C:\WINDOWS\System32\KERNEL32.dll
ModLoad: 00007ffe`16e70000 00007ffe`17113000   C:\WINDOWS\System32\KERNELBASE.dll

혹시 저 DLL에서 PE 헤더의 값을 동적으로 바꾸는 것일까요? 이를 확인하기 위해 windbg의 "Debug" / "Event Filters..." 메뉴를 선택하고, "Load module" 이벤트 항목에 대해 "Execution"을 "Enabled"로, "Continue"를 "Not Handled"로 바꿔준 다음,

anycpu_pe_header_3.png

다시 AnyCPU 실행 파일을 로드해 보면 이렇게 2개만 로드된 것을 확인할 수 있습니다.

ModLoad: 00000000`00380000 00000000`00388000   ConsoleApplication1.exe
ModLoad: 00007ffe`19c60000 00007ffe`19e50000   ntdll.dll

이제 다시 PE Header 관련 값을 덤프해 보면,

0:000> ? 00000000`00380000 + 0n128 + 0n4
Evaluate expression: 3670148 = 00000000`00380084

0:000> dt _IMAGE_FILE_HEADER 00000000`00380084
ntdll!_IMAGE_FILE_HEADER
   +0x000 Machine          : 0x14c
   +0x002 NumberOfSections : 3
   +0x004 TimeDateStamp    : 0x5e022dd0
   +0x008 PointerToSymbolTable : 0
   +0x00c NumberOfSymbols  : 0
   +0x010 SizeOfOptionalHeader : 0xe0
   +0x012 Characteristics  : 0x22

0:000> dw 00000000`00380084+0x14 L1
00000000`00380098  010b

오호... 놀랍군요. ^^ 이 시점까지는 디스크 상의 PE 파일 내용과 동일하게 값을 유지하고 있습니다. 그렇다면 이러한 PE Header를 동적으로 변경하는 것은 운영체제가 아니고 mscoree.dll일 수 있다는 것입니다. 실제로 위의 상태에서 디버깅을 진행해 "mscoree.dll"을 로딩한 다음,

0:000> g
ModLoad: 00007ffe`022f0000 00007ffe`02354000   C:\WINDOWS\SYSTEM32\MSCOREE.DLL
ntdll!NtMapViewOfSection+0x14:
00007ffe`19cfc5c4 c3              ret
0:000> 

다시 PE Header 값을 확인해 보면,

0:000> dt _IMAGE_FILE_HEADER 00000000`00380084
ntdll!_IMAGE_FILE_HEADER
   +0x000 Machine          : 0x14c
   +0x002 NumberOfSections : 3
   +0x004 TimeDateStamp    : 0x5e022dd0
   +0x008 PointerToSymbolTable : 0
   +0x00c NumberOfSymbols  : 0
   +0x010 SizeOfOptionalHeader : 0xf0
   +0x012 Characteristics  : 0x22

0:000> dw 00000000`00380084+0x14 L1
00000000`00380098  020b

값이 바뀌어 있습니다. (DllMain 함수 내에서 바꾸는 코드가 호출되는 걸까요? ^^)




관련해서 검색해 보면,

The Relationship Between .NET And The Windows Kernel
; http://debugandconquer.blogspot.com/2015/04/the-relationship-between-net-and.html

다음의 내용을 볼 수 있습니다.

AnyCPU Executables - How Does It Work?

The documentation of mscoree’s _CorValidateImage refers to changing 32-bit (PE32) executable image to 64-bit (PE32+) executable image in memory (an executable in memory is called an Image) on 64-bit Windows, and you might think that it's all to it, However that's a user mode function that is supposed to be called in the newly created process by the NTDLL Loader, the decision about the architecture of a process happens earlier, and in kernel mode (kernel structures like EPROCESS depend on it), so there has to be some kernel mode code knowing about .NET which decides which architecture to use.

Note: I debugged and _CorValidateImage isn't getting called on Windows 8.1 (on Windows 7 it does), its responsibility seems to have moved to the Loader's LdrpCorValidateImage and LdrpCorFixupImage functions.


여기서 재미있는 점이 있습니다. 운영체제는 PE32 header를 갖는 AnyCPU 이미지를 x64 시스템에서는 64bit 프로세스로 실행해 주는데 결국 위의 링크에서도 언급하고 있지만 EPROCESS 커널 자료 구조를 위해서라도 Kernel 레벨에서 32비트 이미지와 동일하게 빌드되어 있는 AnyCPU 이미지를 판단해야 한다는 것입니다.

아마도, Kernel 측의 Loader에서는 PE32 header만으로는 판단하지 못하고 "Data Directory"까지 내려가 CLR Runtime Header를 가지고 있는지, 만약 가지고 있다면 그 안에 "ILONLY", "32BITPREF"가 설정되었는지를 보고 AnyCPU로서의 적절한 프로세스 구성을 하게 될 것입니다.

참고로 _CorValidateImage 함수에 대한 마이크로소프트의 공식 문서를 보면,

_CorValidateImage Function
; https://learn.microsoft.com/en-us/dotnet/framework/unmanaged-api/hosting/corvalidateimage-function

웬만큼 궁금했던 내용들을 다 설명하고 있군요. ^^

In Windows XP and later versions, the operating system loader checks for managed modules by examining the COM Descriptor Directory bit in the common object file format (COFF) header. A set bit indicates a managed module. If the loader detects a managed module, it loads MsCorEE.dll and calls _CorValidateImage, which performs the following actions:

  • Confirms that the image is a valid managed module.
  • Changes the entry point in the image to an entry point in the common language runtime (CLR).
  • For 64-bit versions of Windows, modifies the image that is in memory by transforming it from PE32 to PE32+ format.
  • Returns to the loader when the managed module images are loaded.

For executable images, the operating system loader then calls the _CorExeMain function, regardless of the entry point specified in the executable. For DLL assembly images, the loader calls the _CorDllMain function.

_CorExeMain or _CorDllMain performs the following actions:

  • Initializes the CLR.
  • Locates the managed entry point from the assembly's CLR header.
  • Begins execution.

The loader calls the _CorImageUnloading function when managed module images are unloaded. However, this function does not perform any action; it just returns.




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







[최초 등록일: ]
[최종 수정일: 4/15/2024]

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

비밀번호

댓글 작성자
 



2022-07-21 09시01분
정성태

... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13099정성태7/14/20227798.NET Framework: 2031. C# 11 - 사용자 정의 checked 연산자파일 다운로드1
13098정성태7/13/20226082개발 환경 구성: 647. Azure - scale-out 상태의 App Service에서 특정 인스턴스에 요청을 보내는 방법 [1]
13097정성태7/12/20225490오류 유형: 817. Golang - binary.Read: invalid type int32
13096정성태7/8/20228242.NET Framework: 2030. C# 11 - UTF-8 문자열 리터럴
13095정성태7/7/20226321Windows: 208. AD 도메인에 참여하지 않은 컴퓨터에서 Kerberos 인증을 사용하는 방법
13094정성태7/6/20226023오류 유형: 816. Golang - "short write" 오류 원인
13093정성태7/5/20226951.NET Framework: 2029. C# - HttpWebRequest로 localhost 접속 시 2초 이상 지연
13092정성태7/3/20227886.NET Framework: 2028. C# - HttpWebRequest의 POST 동작 방식파일 다운로드1
13091정성태7/3/20226707.NET Framework: 2027. C# - IPv4, IPv6를 모두 지원하는 서버 소켓 생성 방법
13090정성태6/29/20225838오류 유형: 815. PyPI에 업로드한 패키지가 반영이 안 되는 경우
13089정성태6/28/20226321개발 환경 구성: 646. HOSTS 파일 변경 시 Edge 브라우저에 반영하는 방법
13088정성태6/27/20225442개발 환경 구성: 645. "Developer Command Prompt for VS 2022" 명령행 환경의 폰트를 바꾸는 방법
13087정성태6/23/20228398스크립트: 41. 파이썬 - FastAPI / uvicorn 호스팅 환경에서 asyncio 사용하는 방법 [1]
13086정성태6/22/20227815.NET Framework: 2026. C# 11 - 문자열 보간 개선 2가지파일 다운로드1
13085정성태6/22/20227876.NET Framework: 2025. C# 11 - 원시 문자열 리터럴(raw string literals)파일 다운로드1
13084정성태6/21/20226518개발 환경 구성: 644. Windows - 파이썬 2.7을 msi 설치 없이 구성하는 방법
13083정성태6/20/20227090.NET Framework: 2024. .NET 7에 도입된 GC의 메모리 해제에 대한 segment와 region의 차이점 [2]
13082정성태6/19/20226135.NET Framework: 2023. C# - Process의 I/O 사용량을 보여주는 GetProcessIoCounters Win32 API파일 다운로드1
13081정성태6/17/20226210.NET Framework: 2022. C# - .NET 7 Preview 5 신규 기능 - System.IO.Stream ReadExactly / ReadAtLeast파일 다운로드1
13080정성태6/17/20226828개발 환경 구성: 643. Visual Studio 2022 17.2 버전에서 C# 11 또는 .NET 7.0 preview 적용
13079정성태6/17/20224569오류 유형: 814. 파이썬 - Error: The file/path provided (...) does not appear to exist
13078정성태6/16/20226588.NET Framework: 2021. WPF - UI Thread와 Render Thread파일 다운로드1
13077정성태6/15/20226921스크립트: 40. 파이썬 - PostgreSQL 환경 구성
13075정성태6/15/20225881Linux: 50. Linux - apt와 apt-get의 차이 [2]
13074정성태6/13/20226183.NET Framework: 2020. C# - NTFS 파일에 사용자 정의 속성값 추가하는 방법파일 다운로드1
13073정성태6/12/20226390Windows: 207. Windows Server 2022에 도입된 WSL 2
... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...