Microsoft MVP성태의 닷넷 이야기
.NET Framework: 871. .NET AnyCPU로 빌드된 PE 헤더의 로딩 전/후 차이점 [링크 복사], [링크+제목 복사]
조회: 10483
글쓴 사람
정성태 (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분
정성태

1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13374정성태6/20/20233111오류 유형: 866. 파이썬 - <class 'AttributeError'> module 'flask.json' has no attribute 'JSONEncoder'
13373정성태6/19/20234400오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
13372정성태6/15/20233113개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
13371정성태6/15/20233133개발 환경 구성: 681. openssl - 인증서 버전(V1 / V3)
13370정성태6/14/20233299개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233096개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233226개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233338오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233133.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20232897오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233683.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233245스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233166.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233639오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233037오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233354오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233665.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233464.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233769DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233690.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20233958.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233571.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234074VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233326오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233665.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233571.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...